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
sequencelengths 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 | ccff8bbccef895aa5c475dbfea4222bc | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static void main(String args[])throws IOException{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t --> 0){
int n = sc.nextInt();
String s = sc.next();
boolean max = false;
StringBuilder str1 = new StringBuilder();
StringBuilder str2 = new StringBuilder();
for(char c : s.toCharArray()){
if( c== '2' && !max){
str1.append('1');
str2.append('1');
}else if(c == '2' && max){
str1.append('2');
str2.append('0');
}else if( c == '1' && !max){
max = true;
str1.append('0');
str2.append('1');
}else if(c == '1' && max){
str1.append('1');
str2.append('0');
}else if(c == '0'){
str1.append('0');
str2.append('0');
}
}
System.out.println(str1.toString());
System.out.println(str2.toString());
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 10a857229004c75af6fc8c4483a9b9c8 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static void main(String args[])throws IOException{
Scanner sc = new Scanner(System.in);
int t1 = sc.nextInt();
while(t1 --> 0){
int n = sc.nextInt();
String s = sc.next();
boolean max = false;
StringBuilder str1 = new StringBuilder();
StringBuilder str2 = new StringBuilder();
for(char c : s.toCharArray()){
if( c== '2' && !max){
str1.append('1');
str2.append('1');
}else if(c == '2' && max){
str1.append('2');
str2.append('0');
}else if( c == '1' && !max){
max = true;
str1.append('0');
str2.append('1');
}else if(c == '1' && max){
str1.append('1');
str2.append('0');
}else if(c == '0'){
str1.append('0');
str2.append('0');
}
}
System.out.println(str1.toString());
System.out.println(str2.toString());
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 0af5022dc4963001d2eeb694f5b38484 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class geek {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i1 = 0; i1 < n; i1++) {
StringBuffer str1 = new StringBuffer();
StringBuffer str2 = new StringBuffer();
Long l = Long.parseLong(br.readLine());
String str = br.readLine();
boolean b = false;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '2') {
if (!b) {
str1.append("1");
str2.append("1");
} else {
str1.append("0");
str2.append("2");
}
} else if (str.charAt(i) == '0') {
str1.append("0");
str2.append("0");
} else {
if (!b) {
b = true;
str1.append("1");
str2.append("0");
} else {
str1.append("0");
str2.append("1");
}
}
}
System.out.println(str1 + "\n" + str2);
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 89527df27ed1ecff2ee94040152ead11 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
public class code12 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0) {
int n = scn.nextInt();
String str = scn.next();
int a = -1;
for(int i=0; i<n; i++) {
if(str.charAt(i)=='1') {
a =i;
break;
}
}
StringBuilder s1 = new StringBuilder("");
StringBuilder s2 = new StringBuilder("");
int i = 0;
while(i<n && i != a) {
if(str.charAt(i) == '2') {
s1.append('1');
s2.append('1');
}
if(str.charAt(i)=='0') {
s1.append('0');
s2.append('0');
}
i++;
}
if(a != -1) {
s1.append('1');
s2.append('0');
i++;
}
while(i<n) {
s1.append('0');
s2.append(str.charAt(i));
i++;
}
System.out.println(s1);
System.out.println(s2);
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 38145ad8a5465d00253be70f121dbc3c | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader sc=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
int test=Integer.parseInt(sc.readLine());
for(int t=0;t<test;t++){
int i;
int n=Integer.parseInt(sc.readLine());
String x=sc.readLine();
char[] ch=x.toCharArray();
int c=x.indexOf('1');//String a="",b="";
char[] a=new char[n];
char[] b=new char[n];
for(i=0;i<n;i++)
{
if(i==c){a[i]='1';b[i]='0';continue;}
if(ch[i]=='2' && c!=-1)
{
if(i<c){a[i]='1';b[i]='1';}
else{a[i]='0';b[i]='2';}
continue;
}
else if(ch[i]=='2' && c==-1)
{
a[i]='1';
b[i]='1';
continue;
}
else if(ch[i]=='1')
{
a[i]='0';
b[i]='1';
continue;
}
else if(ch[i]=='0')
{
a[i]='0';
b[i]='0';
continue;
}
}
bw.write(String.valueOf(a)+"\n"+String.valueOf(b));
bw.newLine();
bw.flush();
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 2b609d433432ac9bd64e04528e713d9c | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int t = in.readInt();
while(t-- > 0) {
int n = in.readInt();
char s[] = in.readString().toCharArray();
char trick[] = new char[n];
char ans[] = new char[n];
Arrays.fill(trick, '0');
Arrays.fill(ans, '0');
boolean b = true;
for(int i = 0; i<n; i++) {
if(s[i] == '1') {
trick[i] = '1';
ans[i] = '0';
for(int j = i+1; j<n; j++) {
ans[j] = s[j];
}
break;
}
else if(s[i] == '2') {
ans[i] = '1';
trick[i] = '1';
}
else {
ans[i] = trick[i] = '0';
}
}
System.out.println(trick);
System.out.println(ans);
}
}
}
class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 122558b2a27403a620a16f943a1ed494 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0){
String n = sc.next();
String o = sc.next();
String s = o;
StringBuilder a = new StringBuilder("");
StringBuilder b = new StringBuilder("");
int flagOne = 0;
int pos = o.length();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(flagOne == 0 && c == '2'){
a.append('1');
b.append('1');
} else if(flagOne == 1 && c == '2'){
a.append('0');
b.append('2');
} else if(c == '1' && flagOne == 0){
a.append('1');
b.append('0');
flagOne = 1;
pos = i + 1;
break;
} else if(c == '0'){
a.append('0');
b.append('0');
}
}
if(pos != o.length()) {
for (int i = pos; i < o.length(); i++)
a.append('0');
b.append(o.substring(pos));
}
System.out.println(a + "\n" + b);
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 4f37d06dcb4ea6d77c57cb0fa709c7da | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class TernaryXOR
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int test=sc.nextInt();
for(int t=1;t<=test;t++)
{
int n=sc.nextInt();
String x=sc.next();
String a="",b="";
int j=x.indexOf('1');
a=x.substring(0,j==-1?n:j).replaceAll("2","1");
b=x.substring(0,j==-1?n:j).replaceAll("2","1");
if(j!=-1)
{
a+="1";
b+="0";
String rep=new String(new char[n-j-1]).replace("\0","0");
a=a+rep;
b=b+x.substring(j+1);
}
System.out.println(a);
System.out.println(b);
}
}
} | Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 243adbebdb9ab57a8065dbc17713f493 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int n, f;
String x;
StringBuilder a, b;
for (int i = 0; i<t; i++) {
n = Integer.parseInt(br.readLine());
x = br.readLine();
f = x.indexOf("1");
a = new StringBuilder(n);
b = new StringBuilder(n);
if (f==-1) {
a.append(x.replace('2', '1'));
System.out.println(a);
System.out.println(a);
}
else {
b.append(x.substring(0, f).replace('2', '1'));
a.append(b+"1");
b.append('0');
while (a.length()<x.length()) {
a.append('0');
}
if (b.length()<x.length()) {
b.append(x.substring(b.length()));
}
System.out.println(a);
System.out.println(b);
}
}
}
} | Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | fd40bf5c7b2211c7e1fc030e9d6a2127 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.Scanner;
public class C {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n = sc.nextInt();
String tr=sc.next();
StringBuffer str= new StringBuffer(tr);
StringBuffer a= new StringBuffer("1");
StringBuffer b= new StringBuffer("1");
int j=1;
for (; j < n; j++) {
xor(str.charAt(j),a,b);
if(str.charAt(j)=='1')
break;
}
j++;
for (; j < n; j++)
{
a.append(0);
b.append(str.charAt(j));
}
System.out.println(a);
System.out.println(b);
}
}
static void xor(char x, StringBuffer a, StringBuffer b){
if (x=='0'){
a.append(0);
b.append(0);
}
else if(x=='1'){
a.append(1);
b.append(0);
}
else
{
a.append(1);
b.append(1);
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 0d9f93a42a68958c425e1ee42b1cba25 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | // 02/08/20 12:35 PM Aug 2020
import java.util.*;
public class _1328C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
String s = sc.next();
StringBuilder st1 = new StringBuilder();
StringBuilder st2 = new StringBuilder();
boolean check=true;
for (int i = 0; i < n; ++i) {
char ch = s.charAt(i);
if (ch == '2') {
if (!check) {
st1.append(0);
st2.append(2);
} else {
st1.append(1);
st2.append(1);
}
} else if (ch == '1') {
if (check) {
check=false;
st1.append(1);
st2.append(0);
} else {
st1.append(0);
st2.append(1);
}
} else {
st1.append(0);
st2.append(0);
}
}
System.out.println(st1);
System.out.println(st2);
}
}
} | Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | be0fb3fe124baa6b0efa5e2f3e87aa72 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class C_POST {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
String str = br.readLine();
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
boolean ptr = false;
for (int i = 0; i < n; i++) {
if (str.charAt(i) == '0') {
a.append('0');
b.append('0');
} else if (str.charAt(i) == '1') {
if (!ptr) {
a.append('0');
b.append('1');
ptr = true;
} else {
a.append('1');
b.append('0');
}
} else if (str.charAt(i) == '2') {
if (!ptr) {
a.append('1');
b.append('1');
} else {
a.append('2');
b.append('0');
}
}
}
System.out.println(a.toString());
System.out.println(b.toString());
}
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 35bbaa335e3ec8db47bb421216629c63 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main{
public static void main(String Args[])throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-->0)
{
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
int n = Integer.parseInt(br.readLine());
String s = br.readLine();
for(int i = 0;i<n;i++)
{
if(s.charAt(i)=='2')
{
s1.append("1");
s2.append("1");
}
else if(s.charAt(i)=='1')
{
s1.append("1");
s2.append( "0");
s2.append(s.substring(i+1));
for(int j = 1;j<=n-i-1;j++)
s1.append("0");
break;
}
else
{
s1.append("0");
s2.append("0");
}
}
System.out.println(s1.toString()+"\n"+s2.toString());
}
}
} | Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | fdb693cf4cc11642ef47e94f291cddfd | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class TernaryXOR {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
for (int i = 0; i < t; i++) {
int n = input.nextInt();
String str = input.next();
boolean bool = false;
StringBuffer ans1 = new StringBuffer();
StringBuffer ans2 = new StringBuffer();
for (int j = 0; j < n; j++) {
if (str.charAt(j) == '0') {
ans1.append(0);
ans2.append(0);
} else if (str.charAt(j) == '1' && bool == false) {
ans1.append(1);
ans2.append(0);
bool = true;
} else if (str.charAt(j) == '1' && bool == true) {
ans1.append(0);
ans2.append(1);
} else {
if (bool == true) {
ans1.append(0);
ans2.append(2);
} else {
ans1.append(1);
ans2.append(1);
}
}
}
System.out.println(ans1);
System.out.println(ans2);
}
input.close();
}
}
| Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | d99b2761fa6b37b468d5bb6653223be8 | train_000.jsonl | 1585233300 | A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /*
* Remember a 6.72 student can know more than a 10.0 student.
* Grades don't determine intelligence, they test obedience.
* I Never Give Up.
* I will become Candidate Master.
* I will defeat Saurabh Anand.
* Skills are Cheap,Passion is Priceless.
* Obsession is necessary.
* Author : Sameer Raj
*/
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.lang.Math.*;
import static java.lang.System.out;
import static java.util.Arrays.fill;
import static java.lang.Math.log;
import static java.lang.Math.abs;
public class ContestMain implements Runnable{
private static Reader in=new Reader();
private static StringBuilder ans=new StringBuilder();
private static long MOD=(long)1e9+7;
private static final int N=(int) (1e5+7); // 1e5+7
private static ArrayList<Integer> v[]=new ArrayList[N];
private static boolean mark[]=new boolean[N];
// private static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
/*Not try to hack the sort function*/
public static void sort(long arr[]){
for(int i=arr.length-1;i>=2;i--){
int x=new Random().nextInt(i-1);
long temp=arr[x];
arr[x]=arr[i];
arr[i]=temp;
}
Arrays.sort(arr);
}
public static void sort(int arr[]){
for(int i=arr.length-1;i>=2;i--){
int x=new Random().nextInt(i-1);
int temp=arr[x];
arr[x]=arr[i];
arr[i]=temp;
}
Arrays.sort(arr);
}
private static long gcd(long a, long b){
if(b==0)return a;
return gcd(b,a%b);
}
/*Code lies here*/
@Override
public void run(){
int t=in.nextInt();
int n,a[],b[];
while(t-->0){
n=in.nextInt();
String x=in.next();
a=new int[n];
b=new int[n];
fill(a,-1);fill(b,-1);
int ind=n;
for(int i=0;i<x.length();i++){
if(x.charAt(i)=='1'){
a[i]=0;b[i]=1;
ind=i+1;
break;
}
else if(x.charAt(i)=='2'){
a[i]=1;b[i]=1;
}
else {
a[i]=0;b[i]=0;
}
}
for(int i=ind;i<n;i++){
if(x.charAt(i)=='2'){
b[i]=0;a[i]=2;
}
else if(x.charAt(i)=='1'){
a[i]=1;b[i]=0;
}
else {a[i]=0;b[i]=0;}
}
for(int i=0;i<n;i++)
if(a[i]==-1){a[i]=1;b[i]=1;}
for(int i=0;i<n;i++)
app(a[i]);
app("\n");
for(int i=0;i<n;i++)
app(b[i]);
app("\n");
}
pn(ans);
}
public static void main(String[] args) throws IOException{
new Thread(null,new ContestMain(),"Accepted",1<<26).start();
/* 0_0 I am watching you 0_0 */
}
static class Pair<T> implements Comparable<Pair>{
int l;
int r;
Pair(){
l=0;
r=0;
}
Pair(int k,int v){
l=k;
r=v;
}
@Override
public int compareTo(Pair o){
if(l!=o.l)return (int)(l-o.l);
return (int)(r-o.r);
}
// Fenwick tree question comparator
// @Override
// public int compareTo(Pair o) {
// if(o.r!=r)return (int) (r-o.r);
// else return (int)(l-o.l);
// }
}
/* BINARY SEARCH FUNCTIONS */
public static int ceilSearch(int l,int r,int val,int ar[]){
int mid;
while(l+1!=r&&l<r){
mid=(l+r)/2;
if(ar[mid]<val)l=mid;
else r=mid;
}
if(ar[l]>=val)return l;
else if(ar[r]>=val)return r;
else return -1;
}
public static int ceilSearch(int l,int r,long val,long ar[]){
int mid;
while(l+1!=r&&l<r){
mid=(l+r)/2;
if(ar[mid]<val)l=mid;
else r=mid;
}
if(ar[l]>=val)return l;
else if(ar[r]>=val)return r;
else return -1;
}
public static int floorSearch(int l,int r,int val,int ar[]){
int mid;
while(l+1!=r&&l<r){
mid=(l+r)/2;
if(ar[mid]>val)r=mid;
else l=mid;
}
if(ar[r]<=val)return r;
else if(ar[l]<=val)return l;
else return -1;
}
public static int floorSearch(int l,int r,long val,long ar[]){
int mid;
while(l+1!=r&&l<r){
mid=(l+r)/2;
if(ar[mid]>val)r=mid;
else l=mid;
}
if(ar[r]<=val)return r;
else if(ar[l]<=val)return l;
else return -1;
}
/* MODULAR OPERATIONS */
private static long mod(long a,long b){
return (b+a%b)%b;
}
private static long modInv(long a){
return powmod(a,MOD-2);
}
private static long powmod(long x,long n){
if(n==0||x==0)return 1;
else if(n%2==0)return(powmod((x*x)%MOD,n/2));
else return (x*(powmod((x*x)%MOD,(n-1)/2)))%MOD;
}
public static long mult(long a,long b){
return mod(mod(a,MOD)*mod(b,MOD),MOD);
}
public static long add(long a,long b){
return mod(mod(a,MOD)+mod(b,MOD),MOD);
}
public static long sub(long a,long b){
return mod(mod(a,MOD)-mod(b,MOD),MOD);
}
/* MAX-MIN FUNCTIONS */
public static long min(long a,long b){
return Math.min(a, b);
}
public static int min(int a,int b){
return Math.min(a, b);
}
public static long max(long a,long b){
return Math.max(a, b);
}
public static int max(int a,int b){
return Math.max(a, b);
}
public static long min(long ar[]){
return Arrays.stream(ar).min().getAsLong();
}
public static int min(int ar[]){
return Arrays.stream(ar).min().getAsInt();
}
public static long max(long ar[]){
return Arrays.stream(ar).max().getAsLong();
}
public static int max(int ar[]){
return Arrays.stream(ar).max().getAsInt();
}
//Reader Class
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader(){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;
}
}
//Looping methods
static void rep(int ar[],int start,int end){
for(int i=start;i<end;i++)
ar[i]=in.nextInt();
}
static void rep(long ar[],int start,int end){
for(int i=start;i<end;i++)
ar[i]=in.nextLong();
}
static void rep(String ar[],int start,int end){
for(int i=start;i<end;i++)
ar[i]=in.next();
}
//Printer Methods
static void pn(Object o){out.print(o);}
static void pln(Object o){out.println(o);}
static void pln(){out.println();}
static void pf(String format,Object o){out.printf(format,o);}
//Appenders
static void app(Object o){ans.append(o);}
static void appn(Object o){ans.append(o+"\n");}
} | Java | ["4\n5\n22222\n5\n21211\n1\n2\n9\n220222021"] | 1 second | ["11111\n11111\n11000\n10211\n1\n1\n110111011\n110111010"] | null | Java 8 | standard input | [
"implementation",
"greedy"
] | c4c8cb860ea9a5b56bb35532989a9192 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$). | 1,200 | For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any. | standard output | |
PASSED | 23bf12cc6cafc5361a989abae001c90e | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* @author master_j
* @version 0.4.1
* @since Mar 22, 2015
*/
public class Solution {
private void solve() throws IOException {
int w = io.nI(), h = io.nI(), rooksNum = io.nI(), rectsNum = io.nI();
Rook[] rooks = new Rook[rooksNum];
for (int i = 0; i < rooks.length; i++)
rooks[i] = new Rook(io);
Rect[] rects = new Rect[rectsNum];
for (int i = 0; i < rects.length; i++)
rects[i] = new Rect(io, i);
boolean[] ans = new boolean[rectsNum];
int rookPtr, rectPtr;
Arrays.sort(rooks, Rook.lrComp);
Arrays.sort(rects, Rect.lrComp);
SegmentTreeMinS stLR = new SegmentTreeMinS(1 + 1 + h);
rookPtr = 0;
rectPtr = 0;
while (true) {
Rook rook = null;
if (rookPtr < rooks.length)
rook = rooks[rookPtr];
Rect rect = null;
if (rectPtr < rects.length)
rect = rects[rectPtr];
if (rect == null)
break;
if (rook != null && rook.x <= rect.x1) {
stLR.update(rook.y, rook.x);
rookPtr++;
} else {
if (rect.x0 <= stLR.min(rect.y0, rect.y1))
ans[rect.id] = true;
rectPtr++;
}
}
Arrays.sort(rooks, Rook.btComp);
Arrays.sort(rects, Rect.btComp);
SegmentTreeMinS stBT = new SegmentTreeMinS(1 + 1 + w);
rookPtr = 0;
rectPtr = 0;
while (true) {
Rook rook = null;
if (rookPtr < rooks.length)
rook = rooks[rookPtr];
Rect rect = null;
if (rectPtr < rects.length)
rect = rects[rectPtr];
if (rect == null)
break;
if (rook != null && rook.y <= rect.y1) {
stBT.update(rook.x, rook.y);
rookPtr++;
} else {
if (rect.y0 <= stBT.min(rect.x0, rect.x1))
ans[rect.id] = true;
rectPtr++;
}
}
for (boolean b : ans)
io.wln(b ? "YES" : "NO");
}//2.2250738585072012e-308
public static void main(String[] args) throws IOException {
IO.launchSolution(args);
}
Solution(IO io) throws IOException {
this.io = io;
solve();
}
private final IO io;
}
class IO {
static final String _localArg = "master_j";
private static final String _problemName = "";
private static final IO.Mode _inMode = Mode.STD_;
private static final IO.Mode _outMode = Mode.STD_;
private static final boolean _autoFlush = false;
static enum Mode {STD_, _PUT_TXT, PROBNAME_}
private final StreamTokenizer st;
private final BufferedReader br;
private final Reader reader;
private final PrintWriter pw;
private final Writer writer;
static void launchSolution(String[] args) throws IOException {
boolean local = (args.length == 1 && args[0].equals(IO._localArg));
IO io = new IO(local);
long nanoTime = 0;
if (local) {
nanoTime -= System.nanoTime();
io.wln("<output>");
}
io.flush();
new Solution(io);
io.flush();
if (local) {
io.wln("</output>");
nanoTime += System.nanoTime();
final long D9 = 1000000000, D6 = 1000000, D3 = 1000;
if (nanoTime >= D9)
io.wf("%d.%d seconds\n", nanoTime / D9, nanoTime % D9);
else if (nanoTime >= D6)
io.wf("%d.%d millis\n", nanoTime / D6, nanoTime % D6);
else if (nanoTime >= D3)
io.wf("%d.%d micros\n", nanoTime / D3, nanoTime % D3);
else
io.wf("%d nanos\n", nanoTime);
}
io.close();
}
IO(boolean local) throws IOException {
if (_inMode == Mode.PROBNAME_ || _outMode == Mode.PROBNAME_)
if (_problemName.length() == 0)
throw new IllegalStateException("You imbecile. Where's my <_problemName>?");
if (_problemName.length() > 0)
if (_inMode != Mode.PROBNAME_ && _outMode != Mode.PROBNAME_)
throw new IllegalStateException("You imbecile. What's the <_problemName> for?");
Locale.setDefault(Locale.US);
if (local) {
reader = new FileReader("input.txt");
writer = new OutputStreamWriter(System.out);
} else {
switch (_inMode) {
case STD_:
reader = new InputStreamReader(System.in);
break;
case PROBNAME_:
reader = new FileReader(_problemName + ".in");
break;
case _PUT_TXT:
reader = new FileReader("input.txt");
break;
default:
throw new NullPointerException("You imbecile. Gimme _inMode.");
}
switch (_outMode) {
case STD_:
writer = new OutputStreamWriter(System.out);
break;
case PROBNAME_:
writer = new FileWriter(_problemName + ".out");
break;
case _PUT_TXT:
writer = new FileWriter("output.txt");
break;
default:
throw new NullPointerException("You imbecile. Gimme _outMode.");
}
}
br = new BufferedReader(reader);
st = new StreamTokenizer(br);
pw = new PrintWriter(writer, _autoFlush);
if (local && _autoFlush)
wln("Note: auto-flush is on.");
}
void wln() {pw.println(); }
void wln(boolean x) {pw.println(x);}
void wln(char x) {pw.println(x);}
void wln(char x[]) {pw.println(x);}
void wln(double x) {pw.println(x);}
void wln(float x) {pw.println(x);}
void wln(int x) {pw.println(x);}
void wln(long x) {pw.println(x);}
void wln(Object x) {pw.println(x);}
void wln(String x) {pw.println(x);}
void wf(String f, Object...o){pw.printf(f, o);}
void w(boolean x) {pw.print(x);}
void w(char x) {pw.print(x);}
void w(char x[]) {pw.print(x);}
void w(double x) {pw.print(x);}
void w(float x) {pw.print(x);}
void w(int x) {pw.print(x);}
void w(long x) {pw.print(x);}
void w(Object x) {pw.print(x);}
void w(String x) {pw.print(x);}
int nI() throws IOException {st.nextToken(); return (int)st.nval;}
double nD() throws IOException {st.nextToken(); return st.nval;}
float nF() throws IOException {st.nextToken(); return (float)st.nval;}
long nL() throws IOException {st.nextToken(); return (long)st.nval;}
String nS() throws IOException {st.nextToken(); return st.sval;}
int[] nIa(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nI();
return a;
}
double[] nDa(int n) throws IOException {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nD();
return a;
}
String[] nSa(int n) throws IOException {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = nS();
return a;
}
void wc(String x) {wc(x.toCharArray());}
void wc(char c1, char c2) {for (char c = c1; c<=c2; c++) wc(c);}
void wc(char x[]) {for (char c : x) wc(c); }
void wc(char x) {st.ordinaryChar(x); st.wordChars(x, x);}
public boolean eof() {return st.ttype == StreamTokenizer.TT_EOF;}
public boolean eol() {return st.ttype == StreamTokenizer.TT_EOL;}
void flush() {pw.flush();}
void close() throws IOException {reader.close(); br.close(); flush(); pw.close();}
}
class SegmentTreeMinS {
private final int n;
private final int[] tree;
SegmentTreeMinS(int n) {
this.n = n;
this.tree = new int[4 * n];
Arrays.fill(tree, -1);
}
int min(int l, int r) {
return min(1, 0, n - 1, l, r);
}
private int min(int v, int tl, int tr, int l, int r) {
if (l > r)
return Integer.MAX_VALUE;
if (l == tl && r == tr)
return tree[v];
int tm = (tl + tr) / 2;
return Math.min(min(2 * v, tl, tm, l, Math.min(tm, r)),
min(1 + 2 * v, 1 + tm, tr, Math.max(l, 1 + tm), r));
}
void update(int i, int val) {
update(1, i, val, 0, n - 1);
}
private void update(int v, int i, int val, int tl, int tr) {
if (i < tl || tr < i)
return;
if (tl == tr) {
tree[v] = val;
return;
}
int tm = (tl + tr) / 2;
update(2 * v, i, val, tl, tm);
update(1 + 2 * v, i, val, 1 + tm, tr);
tree[v] = Math.min(tree[2 * v], tree[1 + 2 * v]);
}
}
class Rook {
final int x, y;
Rook(IO io) throws IOException {
this.x = io.nI();
this.y = io.nI();
}
static Comparator<Rook> lrComp = new Comparator<Rook>() {
@Override
public int compare(Rook r0, Rook r1) {
return r0.x - r1.x;
}
};
static Comparator<Rook> btComp = new Comparator<Rook>() {
@Override
public int compare(Rook r0, Rook r1) {
return r0.y - r1.y;
}
};
}
class Rect {
final int x0, y0, x1, y1;
final int id;
Rect(IO io, int id) throws IOException {
this.x0 = io.nI();
this.y0 = io.nI();
this.x1 = io.nI();
this.y1 = io.nI();
this.id = id;
}
static Comparator<Rect> lrComp = new Comparator<Rect>() {
@Override
public int compare(Rect r0, Rect r1) {
return r0.x1 - r1.x1;
}
};
static Comparator<Rect> btComp = new Comparator<Rect>() {
@Override
public int compare(Rect r0, Rect r1) {
return r0.y1 - r1.y1;
}
};
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 55f1271d613bf0903c60a39faa533fb3 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* @author master_j
* @version 0.4.1
* @since Mar 22, 2015
*/
public class Solution {
private void solve() throws IOException {
int w = io.nI(), h = io.nI(), rooksNum = io.nI(), rectsNum = io.nI();
Rook[] rooks = new Rook[rooksNum];
for (int i = 0; i < rooks.length; i++)
rooks[i] = new Rook(io);
Rect[] rects = new Rect[rectsNum];
for (int i = 0; i < rects.length; i++)
rects[i] = new Rect(io, i);
boolean[] ans = new boolean[rectsNum];
int rookPtr, rectPtr;
Arrays.sort(rooks, Rook.lrComp);
Arrays.sort(rects, Rect.lrComp);
// SegmentTreeMinS stLR = new SegmentTreeMinS(1 + 1 + h);
SegmentTreeMinD stLR = new SegmentTreeMinD(1 + 1 + h);
rookPtr = 0;
rectPtr = 0;
while (true) {
Rook rook = null;
if (rookPtr < rooks.length)
rook = rooks[rookPtr];
Rect rect = null;
if (rectPtr < rects.length)
rect = rects[rectPtr];
if (rect == null)
break;
if (rook != null && rook.x <= rect.x1) {
stLR.update(rook.y, rook.x);
rookPtr++;
} else {
if (rect.x0 <= stLR.min(rect.y0, rect.y1))
ans[rect.id] = true;
rectPtr++;
}
}
Arrays.sort(rooks, Rook.btComp);
Arrays.sort(rects, Rect.btComp);
//SegmentTreeMinS stBT = new SegmentTreeMinS(1 + 1 + w);
SegmentTreeMinD stBT = new SegmentTreeMinD(1 + 1 + w);
rookPtr = 0;
rectPtr = 0;
while (true) {
Rook rook = null;
if (rookPtr < rooks.length)
rook = rooks[rookPtr];
Rect rect = null;
if (rectPtr < rects.length)
rect = rects[rectPtr];
if (rect == null)
break;
if (rook != null && rook.y <= rect.y1) {
stBT.update(rook.x, rook.y);
rookPtr++;
} else {
if (rect.y0 <= stBT.min(rect.x0, rect.x1))
ans[rect.id] = true;
rectPtr++;
}
}
for (boolean b : ans)
io.wln(b ? "YES" : "NO");
}//2.2250738585072012e-308
public static void main(String[] args) throws IOException {
IO.launchSolution(args);
}
Solution(IO io) throws IOException {
this.io = io;
solve();
}
private final IO io;
}
class IO {
static final String _localArg = "master_j";
private static final String _problemName = "";
private static final IO.Mode _inMode = Mode.STD_;
private static final IO.Mode _outMode = Mode.STD_;
private static final boolean _autoFlush = false;
static enum Mode {STD_, _PUT_TXT, PROBNAME_}
private final StreamTokenizer st;
private final BufferedReader br;
private final Reader reader;
private final PrintWriter pw;
private final Writer writer;
static void launchSolution(String[] args) throws IOException {
boolean local = (args.length == 1 && args[0].equals(IO._localArg));
IO io = new IO(local);
long nanoTime = 0;
if (local) {
nanoTime -= System.nanoTime();
io.wln("<output>");
}
io.flush();
new Solution(io);
io.flush();
if (local) {
io.wln("</output>");
nanoTime += System.nanoTime();
final long D9 = 1000000000, D6 = 1000000, D3 = 1000;
if (nanoTime >= D9)
io.wf("%d.%d seconds\n", nanoTime / D9, nanoTime % D9);
else if (nanoTime >= D6)
io.wf("%d.%d millis\n", nanoTime / D6, nanoTime % D6);
else if (nanoTime >= D3)
io.wf("%d.%d micros\n", nanoTime / D3, nanoTime % D3);
else
io.wf("%d nanos\n", nanoTime);
}
io.close();
}
IO(boolean local) throws IOException {
if (_inMode == Mode.PROBNAME_ || _outMode == Mode.PROBNAME_)
if (_problemName.length() == 0)
throw new IllegalStateException("You imbecile. Where's my <_problemName>?");
if (_problemName.length() > 0)
if (_inMode != Mode.PROBNAME_ && _outMode != Mode.PROBNAME_)
throw new IllegalStateException("You imbecile. What's the <_problemName> for?");
Locale.setDefault(Locale.US);
if (local) {
reader = new FileReader("input.txt");
writer = new OutputStreamWriter(System.out);
} else {
switch (_inMode) {
case STD_:
reader = new InputStreamReader(System.in);
break;
case PROBNAME_:
reader = new FileReader(_problemName + ".in");
break;
case _PUT_TXT:
reader = new FileReader("input.txt");
break;
default:
throw new NullPointerException("You imbecile. Gimme _inMode.");
}
switch (_outMode) {
case STD_:
writer = new OutputStreamWriter(System.out);
break;
case PROBNAME_:
writer = new FileWriter(_problemName + ".out");
break;
case _PUT_TXT:
writer = new FileWriter("output.txt");
break;
default:
throw new NullPointerException("You imbecile. Gimme _outMode.");
}
}
br = new BufferedReader(reader);
st = new StreamTokenizer(br);
pw = new PrintWriter(writer, _autoFlush);
if (local && _autoFlush)
wln("Note: auto-flush is on.");
}
void wln() {pw.println(); }
void wln(boolean x) {pw.println(x);}
void wln(char x) {pw.println(x);}
void wln(char x[]) {pw.println(x);}
void wln(double x) {pw.println(x);}
void wln(float x) {pw.println(x);}
void wln(int x) {pw.println(x);}
void wln(long x) {pw.println(x);}
void wln(Object x) {pw.println(x);}
void wln(String x) {pw.println(x);}
void wf(String f, Object...o){pw.printf(f, o);}
void w(boolean x) {pw.print(x);}
void w(char x) {pw.print(x);}
void w(char x[]) {pw.print(x);}
void w(double x) {pw.print(x);}
void w(float x) {pw.print(x);}
void w(int x) {pw.print(x);}
void w(long x) {pw.print(x);}
void w(Object x) {pw.print(x);}
void w(String x) {pw.print(x);}
int nI() throws IOException {st.nextToken(); return (int)st.nval;}
double nD() throws IOException {st.nextToken(); return st.nval;}
float nF() throws IOException {st.nextToken(); return (float)st.nval;}
long nL() throws IOException {st.nextToken(); return (long)st.nval;}
String nS() throws IOException {st.nextToken(); return st.sval;}
int[] nIa(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nI();
return a;
}
double[] nDa(int n) throws IOException {
double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = nD();
return a;
}
String[] nSa(int n) throws IOException {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = nS();
return a;
}
void wc(String x) {wc(x.toCharArray());}
void wc(char c1, char c2) {for (char c = c1; c<=c2; c++) wc(c);}
void wc(char x[]) {for (char c : x) wc(c); }
void wc(char x) {st.ordinaryChar(x); st.wordChars(x, x);}
public boolean eof() {return st.ttype == StreamTokenizer.TT_EOF;}
public boolean eol() {return st.ttype == StreamTokenizer.TT_EOL;}
void flush() {pw.flush();}
void close() throws IOException {reader.close(); br.close(); flush(); pw.close();}
}
class SegmentTreeMinS {
private final int n;
private final int[] tree;
SegmentTreeMinS(int n) {
this.n = n;
this.tree = new int[4 * n];
Arrays.fill(tree, -1);
}
int min(int l, int r) {
return min(1, 0, n - 1, l, r);
}
private int min(int v, int tl, int tr, int l, int r) {
if (l > r)
return Integer.MAX_VALUE;
if (l == tl && r == tr)
return tree[v];
int tm = (tl + tr) / 2;
return Math.min(min(2 * v, tl, tm, l, Math.min(tm, r)),
min(1 + 2 * v, 1 + tm, tr, Math.max(l, 1 + tm), r));
}
void update(int i, int val) {
update(1, i, val, 0, n - 1);
}
private void update(int v, int i, int val, int tl, int tr) {
if (i < tl || tr < i)
return;
if (tl == tr) {
tree[v] = val;
return;
}
int tm = (tl + tr) / 2;
update(2 * v, i, val, tl, tm);
update(1 + 2 * v, i, val, 1 + tm, tr);
tree[v] = Math.min(tree[2 * v], tree[1 + 2 * v]);
}
}
class SegmentTreeMinD {
private final SegmentTreeMinD left, right;
private final int l, r;
private int val;
SegmentTreeMinD(int n) {
this.l = 0;
this.r = n - 1;
this.val = -1;
this.left = new SegmentTreeMinD(0, r / 2);
this.right = new SegmentTreeMinD(1 + r / 2, r);
}
private SegmentTreeMinD(int l, int r) {
this.l = l;
this.r = r;
this.val = -1;
if (l == r) {
this.left = null;
this.right = null;
} else {
int m = (l + r) / 2;
this.left = new SegmentTreeMinD(l, m);
this.right = new SegmentTreeMinD(1 + m, r);
}
}
void update(int i, int val) {
if (i < l || r < i)
return;
if (l == r) {
this.val = val;
return;
}
left.update(i, val);
right.update(i, val);
this.val = Math.min(left.val, right.val);
}
int min(int tl, int tr) {
if (tl > tr)
return Integer.MAX_VALUE;
if (l == tl && r == tr)
return val;
return Math.min(left.min(tl, Math.min(left.r, tr)),
right.min(Math.max(right.l, tl), tr));
}
}
class Rook {
final int x, y;
Rook(IO io) throws IOException {
this.x = io.nI();
this.y = io.nI();
}
static Comparator<Rook> lrComp = new Comparator<Rook>() {
@Override
public int compare(Rook r0, Rook r1) {
return r0.x - r1.x;
}
};
static Comparator<Rook> btComp = new Comparator<Rook>() {
@Override
public int compare(Rook r0, Rook r1) {
return r0.y - r1.y;
}
};
}
class Rect {
final int x0, y0, x1, y1;
final int id;
Rect(IO io, int id) throws IOException {
this.x0 = io.nI();
this.y0 = io.nI();
this.x1 = io.nI();
this.y1 = io.nI();
this.id = id;
}
static Comparator<Rect> lrComp = new Comparator<Rect>() {
@Override
public int compare(Rect r0, Rect r1) {
return r0.x1 - r1.x1;
}
};
static Comparator<Rect> btComp = new Comparator<Rect>() {
@Override
public int compare(Rect r0, Rect r1) {
return r0.y1 - r1.y1;
}
};
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 763b841a1a5369f1c6935c2f47f8f61d | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import static java.lang.Integer.max;
import static java.lang.Integer.min;
import java.util.ArrayList;
import static java.util.Arrays.sort;
import java.util.Comparator;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TreeSet;
//<editor-fold defaultstate="collapsed" desc="Main">
public class Main {
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
private void run() {
try {
Locale.setDefault(Locale.US);
} catch (Exception e) {
}
boolean oj = true;
try {
oj = System.getProperty("MYLOCAL") == null;
} catch (Exception e) {
}
if (oj) {
sc = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
// try {
// sc = new FastScanner(new FileReader ("stacks.in" ));
// out = new PrintWriter(new FileWriter("stacks.out"));
// } catch (IOException e) {
// MLE();
// }
} else {
try {
sc = new FastScanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
MLE();
}
}
Solver s = new Solver();
s.sc = sc;
s.out = out;
s.solve();
if (!oj) {
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
}
out.flush();
}
private void show(int[] arr) {
for (int v : arr) {
err.print(" " + v);
}
err.println();
}
public static void exit() {
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
err.printf("Mem: %d\n", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20);
out.flush();
out.close();
System.exit(0);
}
public static void MLE() {
int[][] arr = new int[1024 * 1024][];
for (int i = 0; i < arr.length; i++) {
arr[i] = new int[1024 * 1024];
}
}
public static void main(String[] args) {
new Main().run();
}
static long timeBegin = System.currentTimeMillis();
static FastScanner sc;
static PrintWriter out;
static PrintStream err = System.err;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader reader) {
br = new BufferedReader(reader);
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception ex) {
return null;
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return br.readLine();
} catch (IOException ex) {
return null;
}
}
}
//</editor-fold>
class Solver {
void aser(boolean OK) {
if (!OK) {
Main.MLE();
}
}
FastScanner sc;
PrintWriter out;
static PrintStream err = System.err;
class Qwer{
int x1, y1, x2, y2, id;
public Qwer(int x1, int y1, int x2, int y2, int id) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.id = id;
}
}
class Tree{
int n;
int[] tree;
public Tree(int n) {
this.n = n;
tree = new int[4*n];
}
void set(int pos, int val){
set(pos,val, 1,1,n);
}
private void set(int pos, int val, int v, int tl, int tr) {
if(tl == tr){
aser(pos == tl);
tree[v] = val;
} else {
int tm = (tl + tr) / 2;
if( pos <= tm ) set(pos, val, 2*v , tl , tm);
else set(pos, val, 2*v+1, tm+1, tr);
tree[v] = min(tree[2*v], tree[2*v+1]);
}
}
int get(int l, int r){
return get(l,r, 1,1,n);
}
private int get(int l, int r, int v, int tl, int tr) {
if(l > r) return Integer.MAX_VALUE;
if(l==tl && r==tr){
return tree[v];
} else {
int tm = (tl + tr) / 2;
return min(
get( l, min(r,tm), 2*v , tl , tm),
get(max(l,tm+1), r, 2*v+1, tm+1, tr)
);
}
}
}
int maxX, maxY, cntL, Q;
Point[] ps;
Qwer[] q;
boolean[] answer;
void solve() {
maxX = sc.nextInt();
maxY = sc.nextInt();
cntL = sc.nextInt();
Q = sc.nextInt();
ps = new Point[cntL];
for (int i = 0; i < cntL; i++) {
ps[i] = new Point(sc.nextInt(), sc.nextInt());
}
q = new Qwer[Q];
for (int i = 0; i < Q; i++) {
q[i] = new Qwer(sc.nextInt(), sc.nextInt(),
sc.nextInt(), sc.nextInt(), i);
}
answer = new boolean[Q];
for (int iter = 0; iter < 2; iter++) {
sort(ps, new Comparator<Point>(){
@Override
public int compare(Point a, Point b) {
return Integer.compare(a.x, b.x);
}
});
sort(q, new Comparator<Qwer>() {
@Override
public int compare(Qwer a, Qwer b) {
return Integer.compare(a.x2, b.x2);
}
});
int posPs = 0, posQ = 0;
Tree tree = new Tree(max(maxX,maxY)+5);
for (int x = 1; x <= maxX; x++) {
for( ;posPs < ps.length && ps[posPs].x == x; ++posPs ){
tree.set( ps[posPs].y, ps[posPs].x );
}
for( ; posQ < q.length && q[posQ].x2 == x; ++posQ ){
int minx = tree.get( q[posQ].y1, q[posQ].y2 );
if( q[posQ].x1 <= minx )
answer[q[posQ].id] = true;
}
}
int t;
t = maxX; maxX = maxY; maxY = t;
for (Point p : ps) {
t = p.x; p.x = p.y; p.y = t;
}
for (Qwer qq : q) {
t = qq.x1; qq.x1 = qq.y1; qq.y1 = t;
t = qq.x2; qq.x2 = qq.y2; qq.y2 = t;
}
}
for (boolean b : answer) {
out.println(b?"YES":"NO");
}
}
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 387ab747cdc28e6d8f892300a9b47ceb | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 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.Comparator;
import java.util.StringTokenizer;
public class Main {
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter writer;
static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
static boolean eof = false;
static String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static void main(String[] args) throws IOException {
tokenizer = null;
// reader = new BufferedReader(new FileReader("grave.in"));
// writer = new PrintWriter(new FileWriter("grave.out"));
reader = new BufferedReader(new InputStreamReader(System.in, "ISO-8859-1"));
writer = new PrintWriter(System.out);
banana();
reader.close();
writer.close();
}
static class P {
public int x, y;
public P(int _x, int _y) {
this.x = _x;
this.y = _y;
}
}
static class Rect {
public int x1, x2, y1, y2, id;
public Rect(int _x1, int _x2, int _y1, int _y2, int _id) {
this.x1 = _x1;
this.x2 = _x2;
this.y1 = _y1;
this.y2 = _y2;
this.id = _id;
}
}
static int tree[];
static int maxTree[];
static void update(int t, int tl, int tr, int index, int value) {
tree[t] = Math.min(tree[t], value);
if (tl == tr) {
tree[t] = value;
return;
}
int tm = (tl + tr) / 2;
if (index <= tm)
update(2 * t, tl, tm, index, value);
else
update(2 * t + 1, tm + 1, tr, index, value);
tree[t] = Math.min(tree[2 * t], tree[2 * t + 1]);
}
static int inf = 1000000;
static int getMax(int t, int tl, int tr, int l, int r) {
if (l > r)
return 0;
if (l == tl && r == tr)
return maxTree[t];
int tm = (tl + tr) / 2;
return Math.max(getMax(2 * t, tl, tm, l, Math.min(r, tm)),
getMax(2 * t + 1, tm + 1, tr, Math.max(tm + 1, l), r));
}
static int getMin(int t, int tl, int tr, int l, int r) {
if (l > r)
return inf;
if (l == tl && r == tr)
return tree[t];
int tm = (tl + tr) / 2;
return Math.min(getMin(2 * t, tl, tm, l, Math.min(tm, r)),
getMin(2 * t + 1, tm + 1, tr, Math.max(l, tm + 1), r));
}
static void banana() throws IOException {
int n = nextInt();
int m = nextInt();
int k = nextInt();
int q = nextInt();
P a[] = new P[k];
for (int i = 0; i < k; ++i) {
a[i] = new P(nextInt(), nextInt());
}
boolean ans[] = new boolean[q];
Rect b[] = new Rect[q];
for (int i = 0; i < q; ++i) {
int x1 = nextInt();
int y1 = nextInt();
int x2 = nextInt();
int y2 = nextInt();
b[i] = new Rect(x1, x2, y1, y2, i);
}
Arrays.sort(a, new Comparator<P>() {
@Override
public int compare(P a, P b) {
return a.y - b.y;
}
});
Arrays.sort(b, new Comparator<Rect>() {
@Override
public int compare(Rect a, Rect b) {
return a.y2 - b.y2;
}
});
tree = new int[4 * n + 20];
Arrays.fill(tree, 0);
int counter = 0;
int c = 0;
for (int i = 1; i <= m; ++i) {
while (counter < k && a[counter].y == i) {
update(1, 1, n, a[counter].x, i);
++counter;
}
while (c < q && b[c].y2 == i) {
int val = getMin(1, 1, n, b[c].x1, b[c].x2);
if (val != inf && val >= b[c].y1)
ans[b[c].id] = true;
++c;
}
}
counter = 0;
c = 0;
Arrays.sort(b, new Comparator<Rect>() {
@Override
public int compare(Rect a, Rect b) {
return a.x2 - b.x2;
}
});
Arrays.sort(a, new Comparator<P>() {
@Override
public int compare(P a, P b) {
return a.x - b.x;
}
});
tree = new int[4 * m + 20];
Arrays.fill(tree, 0);
counter = 0;
c = 0;
for (int i = 1; i <= n; ++i) {
while (counter < k && a[counter].x == i) {
update(1, 1, m, a[counter].y, i);
++counter;
}
while (c < q && b[c].x2 == i) {
int val = getMin(1, 1, m, b[c].y1, b[c].y2);
if (val >= b[c].x1 && val != inf)
ans[b[c].id] = true;
++c;
}
}
for (int i = 0; i < q; ++i) {
writer.println(ans[i] ? "YES" : "NO");
}
}
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 2a872e715c6fe87fa2b5e1533ec46f2c | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
FastScanner in;
PrintWriter out;
int n, m, k, q;
class Point {
int x, y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
class Query {
Point p0, p1;
int num;
public Query(Point p0, Point p1) {
super();
this.p0 = p0;
this.p1 = p1;
}
}
class SegmentTree {
int[] t, a;
int n;
public SegmentTree(int[] a) {
n = a.length;
t = new int[4 * n];
this.a = a;
build(0, 0, n);
}
void build(int v, int l, int r) {
if (r - l == 1) {
t[v] = a[l];
return;
}
int m = (l + r) / 2;
build(2 * v + 1, l, m);
build(2 * v + 2, m, r);
t[v] = Math.min(t[2 * v + 1], t[2 * v + 2]);
}
void setTo(int i, int val) {
setTo(0, 0, n, i, val);
}
void setTo(int v, int tl, int tr, int i, int val) {
if (i >= tr || i < tl) {
return;
}
if (tr - tl == 1) {
a[i] = val;
t[v] = a[i];
return;
}
int tm = (tl + tr) / 2;
if (i < tm)
setTo(2 * v + 1, tl, tm, i, val);
else
setTo(2 * v + 2, tm, tr, i, val);
t[v] = Math.min(t[2 * v + 1], t[2 * v + 2]);
}
int getMin(int l, int r) {
return getMin(0, 0, n, l, r);
}
int getMin(int v, int tl, int tr, int l, int r) {
if (tl >= r || tr <= l)
return Integer.MAX_VALUE;
if (tl >= l && tr <= r) {
return t[v];
}
int tm = (tl + tr) / 2;
int val0 = getMin(2 * v + 1, tl, tm, l, r);
int val1 = getMin(2 * v + 2, tm, tr, l, r);
return Math.min(val0, val1);
}
}
void go(Query[] qs, Point[] pts, boolean[] can) {
Arrays.sort(qs, new Comparator<Query>() {
@Override
public int compare(Query o1, Query o2) {
if (o1.p1.y != o2.p1.y)
return Integer.compare(o1.p1.y, o2.p1.y);
return Integer.compare(o1.num, o2.num);
}
});
Arrays.sort(pts, new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
if (o1.y != o2.y)
return Integer.compare(o1.y, o2.y);
return Integer.compare(o1.x, o2.x);
}
});
int[] a = new int[n];
Arrays.fill(a, Integer.MIN_VALUE);
SegmentTree segTree = new SegmentTree(a);
int p = 0;
for (int i = 0; i < qs.length; i++) {
int maxY = qs[i].p1.y;
while (p < pts.length && pts[p].y <= maxY) {
segTree.setTo(pts[p].x, pts[p].y);
p++;
}
int min = segTree.getMin(qs[i].p0.x, qs[i].p1.x + 1);
if (min >= qs[i].p0.y)
can[qs[i].num] = true;
}
}
Point swap(Point p) {
return new Point(p.y, p.x);
}
void solve() {
n = in.nextInt(); m = in.nextInt();
int k = in.nextInt(), q = in.nextInt();
Point[] pts = new Point[k];
for (int i = 0; i < k; i++) {
pts[i] = new Point(in.nextInt() - 1, in.nextInt() - 1);
}
Query[] qs = new Query[q];
boolean[] can = new boolean[q];
for (int i = 0; i < q; i++) {
qs[i] = new Query(new Point(in.nextInt() - 1, in.nextInt() - 1), new Point(in.nextInt() - 1, in.nextInt() - 1));
qs[i].num = i;
}
go(qs, pts, can);
for (int i = 0; i < k; i++) {
pts[i] = swap(pts[i]);
}
for (int i = 0; i < q; i++) {
int minX = qs[i].p0.x, minY = qs[i].p0.y;
int maxX = qs[i].p1.x, maxY = qs[i].p1.y;
qs[i].p0 = new Point(minY, minX);
qs[i].p1 = new Point(maxY, maxX);
}
int tmp = n;
n = m;
m = tmp;
go(qs, pts, can);
for (boolean b : can) {
if (b)
out.println("YES");
else
out.println("NO");
}
}
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new A().run();
}
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | ee43b9985945b6522c6a7b4600220631 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class B {
boolean[] vert(int n, int m, int k, int q, Point[] p) {
boolean[] ans = new boolean[q];
Arrays.sort(p);
ST tree = new ST(100100);
for (Point x : p) {
if (x.isPoint()) {
tree.set(x.y1, x.x1);
} else {
int min = tree.get(x.y1, x.y2 + 1);
if (min < x.x1) continue;
ans[x.id] = true;
}
}
return ans;
}
void solve() throws IOException {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
int[] x = new int[k];
int[] y = new int[k];
for (int i = 0; i < k; ++i) {
x[i] = in.nextInt();
y[i] = in.nextInt();
}
int[] x1 = new int[q];
int[] y1 = new int[q];
int[] x2 = new int[q];
int[] y2 = new int[q];
for (int i = 0; i < q; ++i) {
x1[i] = in.nextInt();
y1[i] = in.nextInt();
x2[i] = in.nextInt();
y2[i] = in.nextInt();
}
Point[] p1 = new Point[q + k];
int s1 = 0;
for (int i = 0; i < k; ++i) {
p1[s1++] = new Point(x[i], y[i]);
}
for (int i = 0; i < q; ++i) {
p1[s1++] = new Point(x1[i], y1[i], x2[i], y2[i], i);
}
boolean[] a1 = vert(n, m, k, q, p1);
Point[] p2 = new Point[q + k];
int s2 = 0;
for (int i = 0; i < k; ++i) {
p2[s2++] = new Point(y[i], x[i]);
}
for (int i = 0; i < q; ++i) {
p2[s2++] = new Point(y1[i], x1[i], y2[i], x2[i], i);
}
boolean[] a2 = vert(m, n, k, q, p2);
for (int i = 0; i < q; ++i) {
out.println(a1[i] || a2[i] ? "YES" : "NO");
}
}
static FastReader in;
static PrintWriter out;
static PrintStream err;
public static void main(String[] args) {
try {
in = new FastReader();
out = new PrintWriter(System.out);
err = System.err;
new B().solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
class ST {
int n;
int[] min;
ST(int n) {
this.n = n;
min = new int[4 * n];
Arrays.fill(min, Integer.MIN_VALUE);
}
int get(int l, int r) {
return _get(l, r, 0, 0, n);
}
int _get(int l, int r, int v, int L, int R) {
if (l <= L && R <= r) return min[v];
if (l >= R || L >= r) return Integer.MAX_VALUE;
int M = (L + R) / 2;
return Math.min(_get(l, r, 2 * v + 1, L, M),
_get(l, r, 2 * v + 2, M, R));
}
void set(int pos, int val) {
_set(pos, val, 0, 0, n);
}
void _set(int pos, int val, int v, int l, int r) {
if (r - l == 1) {
min[v] = val;
} else {
int m = (l + r) / 2;
if (pos < m) {
_set(pos, val, 2 * v + 1, l, m);
} else {
_set(pos, val, 2 * v + 2, m, r);
}
min[v] = Math.min(min[2 * v + 1], min[2 * v + 2]);
}
}
}
class Point implements Comparable<Point> {
int x1, x2, y1, y2;
int type;
int id;
boolean isPoint() {
return type == -1;
}
Point(int x, int y) {
x1 = x;
x2 = x;
y1 = y;
y2 = y;
type = -1;
}
public Point(int x1, int y1, int x2, int y2, int id) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.id = id;
type = 1;
}
int getPos() {
return x2;
}
@Override
public int compareTo(Point o) {
if (getPos() != o.getPos()) return Integer.compare(getPos(), o.getPos());
return Integer.compare(type, o.type);
}
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | b9bc104a39807c4984f9a0159739663f | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.util.Arrays;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.io.BufferedReader;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Vadim Semenov
*/
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) {
int rows = in.nextInt();
int columns = in.nextInt();
int rooks = in.nextInt();
int queries = in.nextInt();
List<Integer>[][] rooksHere = new List[2][];
rooksHere[0] = new List[rows];
rooksHere[1] = new List[columns];
List<Integer>[][] endsHere = new List[2][];
endsHere[0] = new List[rows];
endsHere[1] = new List[columns];
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < endsHere[i].length; ++j) {
rooksHere[i][j] = new ArrayList<>();
endsHere[i][j] = new ArrayList<>();
}
}
for (int i = 0; i < rooks; ++i) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
rooksHere[0][x].add(y);
rooksHere[1][y].add(x);
}
int[][][] area = new int[2][2][queries];
for (int i = 0; i < queries; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 2; ++k) {
area[j][k][i] = in.nextInt() - 1;
if (j == 1) {
endsHere[k][area[j][k][i]].add(i);
}
}
}
}
boolean[] isProtected = new boolean[queries];
for (int dir = 0; dir < 2; ++dir) {
RMQ rmq = new RMQ(endsHere[dir ^ 1].length);
for (int coordinate = 0; coordinate < endsHere[dir].length; ++coordinate) {
for (int i : rooksHere[dir][coordinate]) {
rmq.update(i, coordinate);
}
for (int i : endsHere[dir][coordinate]) {
isProtected[i] |= rmq.query(area[0][dir ^ 1][i], area[1][dir ^ 1][i]) >= area[0][dir][i];
}
}
}
for (boolean yes : isProtected) {
out.println(yes ? "YES" : "NO");
}
}
private static class RMQ {
private int[] data;
private int offset;
public RMQ(int capacity) {
offset = Integer.highestOneBit(capacity);
if ((capacity & capacity - 1) != 0) offset <<= 1;
data = new int[offset << 1];
Arrays.fill(data, -1);
}
public void update(int at, int val) {
at += offset;
data[at] = val;
at >>>= 1;
while (at > 0) {
data[at] = Math.min(data[at << 1], data[(at << 1) | 1]);
at >>>= 1;
}
}
public int query(int from, int to) {
from += offset;
to += offset;
int result = Integer.MAX_VALUE;
while (from <= to) {
if ((from & 1) == 1) {
result = Math.min(result, data[from]);
from++;
}
if ((to & 1) == 0) {
result = Math.min(result, data[to]);
to--;
}
from >>>= 1;
to >>>= 1;
}
return result;
}
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(readLine());
}
return tokenizer.nextToken();
}
public String readLine() {
String line;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 2b45d67388d4f78915f9f9cbea3fd01a | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(), q = in
.nextInt();
int[] x = new int[k], y = new int[k];
for (int i = 0; i < k; i++) {
x[i] = in.nextInt() - 1;
y[i] = in.nextInt() - 1;
}
int[] x1 = new int[q], x2 = new int[q], y1 = new int[q], y2 = new int[q];
for (int i = 0; i < q; i++) {
x1[i] = in.nextInt() - 1;
y1[i] = in.nextInt() - 1;
x2[i] = in.nextInt() - 1;
y2[i] = in.nextInt() - 1;
}
boolean[] ans = new boolean[q];
for (int rot = 0; rot < 2; rot++) {
List<Event> events = new ArrayList<>();
for (int i = 0; i < k; i++) {
events.add(new Event(x[i], 0, i));
}
for (int i = 0; i < q; i++) {
events.add(new Event(x2[i], 1, i));
}
Collections.sort(events);
SegmentTree st = new SegmentTree(m);
for (Event e : events) {
if (e.type == 0) {
st.set(y[e.id], x[e.id]);
} else {
int from = y1[e.id], to = y2[e.id];
int min = st.get(from, to);
if (min >= x1[e.id]) {
ans[e.id] = true;
}
}
}
for (int i = 0; i < k; i++) {
int tmp = x[i];
x[i] = y[i];
y[i] = tmp;
}
for (int i = 0; i < q; i++) {
int tmp = x1[i];
x1[i] = y1[i];
y1[i] = tmp;
tmp = x2[i];
x2[i] = y2[i];
y2[i] = tmp;
}
int tmp = n;
n = m;
m = tmp;
}
for (int i = 0; i < q; i++) {
out.println(ans[i] ? "YES" : "NO");
}
}
class Event implements Comparable<Event> {
int pos, type;
int id;
public Event(int pos, int type, int id) {
super();
this.pos = pos;
this.type = type;
this.id = id;
}
@Override
public int compareTo(Event o) {
int t = Integer.compare(pos, o.pos);
if (t == 0) {
return Integer.compare(type, o.type);
}
return t;
}
}
class SegmentTree {
int[] min;
int size;
public SegmentTree(int n) {
min = new int[4 * n];
Arrays.fill(min, -1);
size = n;
}
void set(int pos, int val) {
set(0, size, pos, val, 0);
}
void set(int left, int right, int pos, int val, int i) {
if (left + 1 == right) {
min[i] = val;
return;
}
int mid = (left + right) >> 1;
if (pos < mid) {
set(left, mid, pos, val, 2 * i + 1);
} else {
set(mid, right, pos, val, 2 * i + 2);
}
min[i] = Math.min(min[2 * i + 1], min[2 * i + 2]);
}
int get(int l, int r) {
return get(0, size, l, r + 1, 0);
}
int get(int left, int right, int l, int r, int i) {
if (l <= left && right <= r) {
return min[i];
}
if (right <= l || r <= left) {
return Integer.MAX_VALUE;
}
int mid = (left + right) >> 1;
int ans1 = get(left, mid, l, r, 2 * i + 1);
int ans2 = get(mid, right, l, r, 2 * i + 2);
return Math.min(ans1, ans2);
}
}
class BIT {
int[] tree;
public BIT(int n) {
tree = new int[n];
}
int get(int from, int to) {
int res = get(to);
if (from > 0) {
res -= get(from - 1);
}
return res;
}
int get(int pos) {
int res = 0;
while (pos >= 0) {
res += tree[pos];
pos = (pos & (pos + 1)) - 1;
}
return res;
}
void add(int pos) {
while (pos < tree.length) {
tree[pos]++;
pos |= pos + 1;
}
}
}
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void main(String[] args) {
new E().run();
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 4fb339e9d04ddd9427f838a95156a070 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class E_VK2015_Round1 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int h = in.nextInt();
Point[] data = new Point[k];
for (int i = 0; i < k; i++) {
data[i] = new Point(in.nextInt(), in.nextInt());
}
Square[] q = new Square[h];
for (int i = 0; i < h; i++) {
q[i] = new Square(i, in.nextInt(), in.nextInt(), in.nextInt(),
in.nextInt());
}
Arrays.sort(q, new Comparator<Square>() {
@Override
public int compare(Square o1, Square o2) {
// TODO Auto-generated method stub
return Integer.compare(o1.x2, o2.x2);
}
});
Arrays.sort(data);
// System.out.println(Arrays.toString(data));
boolean[] result = new boolean[h];
int[] tree = new int[4 * Math.max(n, m) + 10];
Arrays.fill(tree, -1);
int index = 0;
for (int i = 0; i < h; i++) {
while (index < k && data[index].x <= q[i].x2) {
update(0, data[index].y, data[index].x, 1, m, tree);
index++;
}
int v = get(0, q[i].y1, q[i].y2, 1, m, tree);
if (v < q[i].x1) {
} else {
result[q[i].index] = true;
}
}
Arrays.sort(q, new Comparator<Square>() {
@Override
public int compare(Square o1, Square o2) {
// TODO Auto-generated method stub
return Integer.compare(o1.y2, o2.y2);
}
});
Arrays.sort(data, new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
// TODO Auto-generated method stub
return Integer.compare(o1.y, o2.y);
}
});
tree = new int[4 * Math.max(n, m) + 10];
Arrays.fill(tree, -1);
index = 0;
for (int i = 0; i < h; i++) {
while (index < k && data[index].y <= q[i].y2) {
update(0, data[index].x, data[index].y, 1, n, tree);
index++;
}
int v = get(0, q[i].x1, q[i].x2, 1, n, tree);
// System.out.println(v + " " + " " + q[i].x1 + " " + q[i].x2 + " "
// + q[i].index);
if (v < q[i].y1) {
} else {
result[q[i].index] = true;
}
}
for (boolean v : result) {
if (v) {
out.println("YES");
} else {
out.println("NO");
}
}
out.close();
}
static int left(int index) {
return 2 * index + 1;
}
static int right(int index) {
return 2 * index + 2;
}
static int get(int index, int l1, int r1, int l, int r, int[] tree) {
if (l > r1 || r < l1) {
return Integer.MAX_VALUE;
}
if (l1 <= l && r <= r1) {
return tree[index];
}
int mid = (l + r) >> 1;
int a = get(left(index), l1, r1, l, mid, tree);
int b = get(right(index), l1, r1, mid + 1, r, tree);
return Math.min(a, b);
}
static void update(int index, int p, int v, int l, int r, int[] tree) {
if (l > p || r < p) {
return;
}
if (l == p && r == p) {
tree[index] = v;
return;
}
int mid = (l + r) >> 1;
update(left(index), p, v, l, mid, tree);
update(right(index), p, v, mid + 1, r, tree);
tree[index] = Math.min(tree[left(index)], tree[right(index)]);
}
static class Square {
int index, x1, y1, x2, y2;
public Square(int index, int x1, int y1, int x2, int y2) {
super();
this.index = index;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
@Override
public int compareTo(Point o) {
return x - o.x;
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new
// BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new
// FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 8791c43d5b2e3034b880859be3938bdb | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.util.Arrays;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Artem Gilmudinov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Reader in = new Reader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
class Rectangle {
public int x1, y1, x2, y2, id;
public Rectangle(int x1, int y1, int x2, int y2, int id) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.id = id;
}
}
class Tower {
public int x, y;
public Tower(int x, int y) {
this.x = x;
this.y = y;
}
}
public void solve(int testNumber, Reader in, PrintWriter out) {
int n, m, k, q;
n = in.ni(); m = in.ni(); k = in.ni(); q = in.ni();
Tower[] towers = new Tower[k];
Rectangle[] rectangles = new Rectangle[q];
for(int i = 0; i < k; i++) {
towers[i] = new Tower(in.ni() - 1, in.ni() - 1);
}
for(int i = 0; i < q; i++ ){
rectangles[i] = new Rectangle(in.ni() - 1, in.ni() - 1, in.ni() - 1, in.ni() - 1, i);
}
HashMap<Integer, ArrayList<Integer>> colMap = new HashMap<>();
HashMap<Integer, ArrayList<Integer>> rowMap = new HashMap<>();
for(int i = 0; i < k; i++) {
ArrayList<Integer> list = colMap.get(towers[i].y);
if(list == null) {
list = new ArrayList<>();
}
list.add(towers[i].x);
colMap.put(towers[i].y, list);
list = rowMap.get(towers[i].x);
if(list == null) {
list = new ArrayList<>();
}
list.add(towers[i].y);
rowMap.put(towers[i].x, list);
}
HashMap<Integer, ArrayList<Integer>> rectCol = new HashMap<>();
HashMap<Integer, ArrayList<Integer>> rectRow = new HashMap<>();
for(int i = 0; i < q; i++) {
ArrayList<Integer> list = rectCol.get(rectangles[i].y2);
if(list == null) {
list = new ArrayList<>();
}
list.add(i);
rectCol.put(rectangles[i].y2, list);
list = rectRow.get(rectangles[i].x2);
if(list == null) {
list = new ArrayList<>();
}
list.add(i);
rectRow.put(rectangles[i].x2, list);
}
int[] last = new int[n];
Arrays.fill(last, -1);
SegmentTreeInt st = new SegmentTreeInt(last, Integer.MAX_VALUE, new SegmentTreeInt.Operation() {
public int get(int x, int y) {
return Math.min(x, y);
}
});
boolean[] col = new boolean[q];
boolean[] row = new boolean[q];
for(int i = 0; i < m; i++) {
ArrayList<Integer> list = colMap.get(i);
if(list != null) {
for(int j = 0; j < list.size(); j++) {
st.update(0, st.numberOfLeafs - 1, list.get(j), 0, i);
}
}
list = rectCol.get(i);
if(list != null) {
for(int j = 0; j < list.size(); j++) {
Rectangle rect = rectangles[list.get(j)];
int min = st.get(0, st.numberOfLeafs - 1, rect.x1, rect.x2, 0);
if(min >= rect.y1) {
col[rect.id] = true;
}
}
}
}
last = new int[m];
Arrays.fill(last, -1);
st = new SegmentTreeInt(last, Integer.MAX_VALUE, new SegmentTreeInt.Operation() {
public int get(int x, int y) {
return Math.min(x, y);
}
});
for(int i = 0; i < n; i++) {
ArrayList<Integer> list = rowMap.get(i);
if(list != null) {
for(int j = 0; j < list.size(); j++) {
st.update(0, st.numberOfLeafs - 1, list.get(j), 0, i);
}
}
list = rectRow.get(i);
if(list != null) {
for(int j = 0; j < list.size(); j++) {
Rectangle rect = rectangles[list.get(j)];
int min = st.get(0, st.numberOfLeafs - 1, rect.y1, rect.y2, 0);
if(min >= rect.x1) {
row[rect.id] = true;
}
}
}
}
for(int i = 0; i < q; i++) {
if(col[i] || row[i]) {
out.println("YES");
} else {
out.println("NO");
}
}
}
}
class Reader {
private BufferedReader in;
private StringTokenizer st = new StringTokenizer("");
private String delim = " ";
public Reader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public String next() {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(rl());
}
return st.nextToken(delim);
}
public String rl() {
try {
return in.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public int ni() {
return Integer.parseInt(next());
}
}
class SegmentTreeInt{
public int b[], defaultValue;
Operation operation;
public int numberOfLeafs;
public static interface Operation {
public int get(int x, int y);
}
public SegmentTreeInt(int[] a, int defaultValue, Operation operation) {
this.operation = operation;
this.defaultValue = defaultValue;
int n = a.length;
int size = 1;
while(size < n) {
size <<= 1;
}
numberOfLeafs = size;
b = new int[size * 2 - 1];
for(int i = size - 1; i < size - 1 + n; i++) {
b[i] = a[i - size + 1];
}
for(int i = size - 1 + n; i < b.length; i++) {
b[i] = defaultValue;
}
for(int i = size - 2; i >= 0; i--) {
b[i] = operation.get(b[2 * i + 1], b[2 * i + 2]);
}
}
public int get(int l, int r, int q_l, int q_r, int node) {
if(q_l > q_r) {
return defaultValue;
}
if(l == q_l && r == q_r) {
return b[node];
}
int mid = l + (r - l) / 2;
return operation.get(get(l, mid, q_l, Math.min(mid, q_r), node * 2 + 1),
get(mid + 1, r, Math.max(mid + 1, q_l), q_r, node * 2 + 2));
}
public void update(int l, int r, int pos, int node, int value) {
if(l == pos && r == pos) {
b[node] = value;
return;
}
int mid = l + (r - l) / 2;
if(pos <= mid) {
update(l, mid, pos, 2 * node + 1, value);
} else {
update(mid + 1, r, pos, 2 * node + 2, value);
}
b[node] = operation.get(b[2 * node + 1], b[2 * node + 2]);
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | a97fc27aaf013c99ec8a90c36cc2e3a2 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static class Rook {
int x, y;
public Rook(int x, int y) {
this.x = x;
this.y = y;
}
static Comparator<Rook> byX = (Rook a, Rook b) -> {
return Integer.compare(a.x, b.x);
};
}
static class Query {
int x1, y1, x2, y2, id;
public Query(int x1, int y1, int x2, int y2, int id) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.id = id;
}
static Comparator<Query> byX2 = (Query a, Query b) -> {
return Integer.compare(a.x2, b.x2);
};
}
static class Node {
int l, r;
Node left, right;
int min;
public Node(int l, int r) {
this.l = l;
this.r = r;
min = -1;
if (r - l > 1) {
int mid = (l + r) >> 1;
left = new Node(l, mid);
right = new Node(mid, r);
}
}
void set(int pos, int x) {
if (l == pos && pos + 1 == r) {
min = x;
return;
}
(pos < left.r ? left : right).set(pos, x);
min = Math.min(left.min, right.min);
}
int get(int ql, int qr) {
if (ql >= r || l >= qr) {
return Integer.MAX_VALUE;
}
if (ql <= l && r <= qr) {
return min;
}
return Math.min(left.get(ql, qr), right.get(ql, qr));
}
}
boolean[] go(Rook[] rs, Query[] qs, int size) {
Node root = new Node(0, size);
boolean[] ret = new boolean[qs.length];
for (int i = 0, j = 0; i < qs.length; i++) {
while (j < rs.length && rs[j].x <= qs[i].x2) {
root.set(rs[j].y, rs[j].x);
j++;
}
int val = root.get(qs[i].y1, qs[i].y2 + 1);
ret[qs[i].id] = val >= qs[i].x1;
}
return ret;
}
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int k = nextInt();
int q = nextInt();
Rook[] rx = new Rook[k];
Rook[] ry = new Rook[k];
for (int i = 0; i < k; i++) {
int x1 = nextInt() - 1;
int y1 = nextInt() - 1;
rx[i] = new Rook(x1, y1);
ry[i] = new Rook(y1, x1);
}
Arrays.sort(rx, Rook.byX);
Arrays.sort(ry, Rook.byX);
Query[] qx = new Query[q];
Query[] qy = new Query[q];
for (int i = 0; i < q; i++) {
int x1 = nextInt() - 1;
int y1 = nextInt() - 1;
int x2 = nextInt() - 1;
int y2 = nextInt() - 1;
qx[i] = new Query(x1, y1, x2, y2, i);
qy[i] = new Query(y1, x1, y2, x2, i);
}
Arrays.sort(qx, Query.byX2);
Arrays.sort(qy, Query.byX2);
boolean[] ansX = go(rx, qx, m);
boolean[] ansY = go(ry, qy, n);
for (int i = 0; i < q; i++) {
out.println(ansX[i] || ansY[i] ? "YES" : "NO");
}
}
E() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new E();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | fe5a417b51ca552bd15ffb3e65f40ca9 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.*;
import static java.lang.Math.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.function.*;
import java.lang.*;
public class Main {
final static boolean debug = false;
final static String fileName = "";
final static boolean useFiles = false;
public static void main(String[] args) throws FileNotFoundException {
long start;
if (debug)
start = System.nanoTime();
InputStream inputStream;
OutputStream outputStream;
if (useFiles) {
inputStream = new FileInputStream(fileName + ".in");
outputStream = new FileOutputStream(fileName + ".out");
} else {
inputStream = System.in;
outputStream = System.out;
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task(in, out);
solver.solve();
if(debug)
out.println((System.nanoTime() - start) / 1e+9);
out.close();
}
}
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 double nextDouble(){
return Double.parseDouble(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public byte nextByte(){
return Byte.parseByte(next());
}
}
class P{
char A, B;
P(char a, char b){
if (a < b){
A = a;
B = b;
}
else{
A = b;
B = a;
}
}
boolean equals(P r){
return r.A == A && r.B == B;
}
}
class Rook{
int X, Y;
Rook(int x, int y){
X = x;
Y = y;
}
}
class Query{
int X1, X2, Y1, Y2;
int Id;
Query(int x1, int y1, int x2, int y2, int id){
X1 = x1;
X2 = x2;
Y1 = y1;
Y2 = y2;
Id = id;
}
}
class Task {
public void solve() {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int q = in.nextInt();
Rook[] rooks = new Rook[k];
for (int i = 0; i < k; i++) {
rooks[i] = new Rook(in.nextInt() - 1, in.nextInt() - 1);
}
Query[] queries = new Query[q];
for (int i = 0; i < q; i++) {
queries[i] = new Query(in.nextInt() - 1, in.nextInt() - 1, in.nextInt() - 1, in.nextInt() - 1, i);
}
boolean[] x = doIt(n, m, queries, rooks);
for (Rook rook : rooks) {
int t = rook.X;
rook.X = rook.Y;
rook.Y = t;
}
for (Query query : queries) {
int t = query.X1;
query.X1 = query.Y1;
query.Y1 = t;
t = query.X2;
query.X2 = query.Y2;
query.Y2 = t;
}
boolean[] y = doIt(m, n, queries, rooks);
for (int i = 0; i < queries.length; i++) {
out.println(x[i] || y[i] ? "YES" : "NO");
}
}
boolean[] doIt(int n, int m, Query[] queries, Rook[] rooks) {
ArrayList<Query>[] queriesByY = new ArrayList[m];
for (int i = 0; i < m; i++) {
queriesByY[i] = new ArrayList<>();
}
for (Query query : queries) {
queriesByY[query.Y1].add(query);
}
int[] position = new int[n];
ArrayList<Rook>[] byX = new ArrayList[n];
for (int i = 0; i < n; i++) {
byX[i] = new ArrayList<>();
}
for (Rook rook : rooks) {
byX[rook.X].add(rook);
}
for (int x = 0; x < n; x++) {
Collections.sort(byX[x], new Comparator<Rook>() {
@Override
public int compare(Rook o1, Rook o2) {
return o1.Y - o2.Y;
}
});
}
ArrayList<Rook>[] byY = new ArrayList[m];
for (int i = 0; i < m; i++) {
byY[i] = new ArrayList<>();
}
for (Rook rook : rooks) {
byY[rook.Y].add(rook);
}
boolean[] result = new boolean[queries.length];
BinaryOperatorSegmentTree tree = new BinaryOperatorSegmentTree(n, Math::max);
for (int x = 0; x < n; x++) {
if (byX[x].size() == 0) {
tree.set(x, m);
} else {
tree.set(x, byX[x].get(0).Y);
}
}
for (int y = 0; y < m; y++) {
for (Query q : queriesByY[y]) {
result[q.Id] = tree.get(q.X1, q.X2) <= q.Y2;
}
for (Rook rook : byY[y]) {
if (position[rook.X] >= byX[rook.X].size() - 1)
tree.set(rook.X, m);
else {
position[rook.X]++;
tree.set(rook.X, byX[rook.X].get(position[rook.X]).Y);
}
}
}
return result;
}
private InputReader in;
private PrintWriter out;
Task(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
}
}
class BinaryOperatorSegmentTree {
private int[] t;
private int n;
private BinaryOperator<Integer> operator;
BinaryOperatorSegmentTree(int n, BinaryOperator<Integer> operator) {
this.n = n;
t = new int[n << 2];
this.operator = operator;
}
BinaryOperatorSegmentTree(int[] array, BinaryOperator<Integer> operator) {
this(array.length, operator);
build(0, 0, n - 1, array);
}
private void build(int v, int tl, int tr, int[] array) {
if (tr == tl) {
t[v] = array[tl];
} else {
int tm = (tl + tr) >> 1;
build(2 * v + 1, tl, tm, array);
build(2 * v + 2, tm + 1, tr, array);
t[v] = operator.apply(t[2 * v + 1], t[2 * v + 2]);
}
}
int get(int l, int r) {
if (!(0 <= l && l < n && 0 <= r && r < n))
throw new IllegalArgumentException("indices: (" + l + ", " + r + "). Bounds: (0, " + (n - 1) + ")");
return get(0, 0, n - 1, l, r);
}
void set(int index, int value) {
if (0 > index || index > n)
throw new IllegalArgumentException("index: " + index + ". Bounds: " + (n - 1));
set(0, 0, n - 1, index, value);
}
private int get(int v, int tl, int tr, int l, int r) {
if (l > r)
return 0;
if (tl == l && tr == r)
return t[v];
int tm = (tl + tr) >> 1;
return operator.apply(get(2 * v + 1, tl, tm, l, Math.min(tm, r)),
get(2 * v + 2, tm + 1, tr, Math.max(tm + 1, l), r));
}
private void set(int v, int tl, int tr, int index, int value) {
if (tr == tl)
t[v] = operator.apply(value, t[v]);
else {
int tm = (tl + tr) >> 1;
if (index <= tm)
set(2 * v + 1, tl, tm, index, value);
else
set(2 * v + 2, tm + 1, tr, index, value);
t[v] = operator.apply(t[2 * v + 1], t[2 * v + 2]);
}
}
public int[] toArray() {
int[] result = new int[n];
for (int i = 0; i < n; i++)
result[i] = get(i, i);
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < n; i++)
result += get(i, i) + " ";
return result;
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 59bd48e49800a66ddbe35784bca90409 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class E implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new E(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) throws IOException {
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;
}
int[] readIntArrayWithDecrease(int size) throws IOException {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@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;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<E.IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, 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<E.IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, 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;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final 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);
}
/////////////////////////////////////////////////////////////////////
final static int INF = 1000 * 1000 * 1000;
static class MinSegmentTree {
int size;
int[] tree;
MinSegmentTree(int size) {
this.size = size;
this.tree = new int[size << 2];
}
void set(int index, int value) {
set(1, 0, size - 1, index, value);
}
int set(int v, int l, int r, int index, int value) {
if (l == r) {
return tree[v] = value;
} else {
int vLeft = (v << 1);
int vRight = (vLeft + 1);
int m = ((l + r) >> 1);
if (index <= m) {
set(vLeft, l, m, index, value);
} else {
set(vRight, m + 1, r, index, value);
}
return tree[v] = min(tree[vLeft], tree[vRight]);
}
}
int get(int left, int right) {
return get(1, 0, size - 1, left, right);
}
int get(int v, int l, int r, int left, int right) {
if (right < l || r < left) return INF;
if (left == l && r == right) {
return tree[v];
} else {
int vLeft = (v << 1);
int vRight = (vLeft + 1);
int m = ((l + r) >> 1);
int leftRes = get(vLeft, l, m, left, min(m, right));
int rightRes = get(vRight, m + 1, r, max(left, m + 1), right);
return min(leftRes, rightRes);
}
}
}
class Area {
Point min, max;
int index;
Area(Point min, Point max, int index) {
this.min = min;
this.max = max;
this.index = index;
}
}
void solve() throws IOException {
int xSize = readInt() + 1;
int ySize = readInt() + 1;
int rocksCount = readInt();
int queriesCount = readInt();
Point[] rocks = readPointArray(rocksCount);
Area[] areas = new Area[queriesCount];
for (int i = 0; i < queriesCount; ++i) {
areas[i] = new Area(readPoint(), readPoint(), i);
}
boolean[] answers = new boolean[queriesCount];
Arrays.fill(answers, false);
{
// iterator -> x, tree -> y
List<Area>[] xAreas = new List[xSize];
for (int x = 0; x < xSize; ++x) {
xAreas[x] = new ArrayList<E.Area>();
}
for (Area area : areas) {
xAreas[area.max.x].add(area);
}
List<Point>[] xRocks = new List[xSize];
for (int x = 0; x < xSize; ++x) {
xRocks[x] = new ArrayList<Point>();
}
for (Point rock : rocks) {
xRocks[rock.x].add(rock);
}
MinSegmentTree yTree = new MinSegmentTree(ySize);
for (int x = 0; x < xSize; ++x) {
for (Point rock : xRocks[x]) {
yTree.set(rock.y, x);
}
for (Area area : xAreas[x]) {
int minX = yTree.get(area.min.y, area.max.y);
if (minX >= area.min.x) {
answers[area.index] = true;
}
}
}
}
{
// iterator -> y, tree -> x
List<Area>[] yAreas = new List[ySize];
for (int y = 0; y < ySize; ++y) {
yAreas[y] = new ArrayList<E.Area>();
}
for (Area area : areas) {
yAreas[area.max.y].add(area);
}
List<Point>[] yRocks = new List[ySize];
for (int y = 0; y < ySize; ++y) {
yRocks[y] = new ArrayList<Point>();
}
for (Point rock : rocks) {
yRocks[rock.y].add(rock);
}
MinSegmentTree xTree = new MinSegmentTree(xSize);
for (int y = 0; y < ySize; ++y) {
for (Point rock : yRocks[y]) {
xTree.set(rock.x, y);
}
for (Area area : yAreas[y]) {
int minY = xTree.get(area.min.x, area.max.x);
if (minY >= area.min.y) {
answers[area.index] = true;
}
}
}
}
for (boolean answer : answers) {
out.println(answer ? "YES" : "NO");
}
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | c4617e046f306cb082ecfef86febc514 | train_000.jsonl | 1426946400 | Polycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected. | 256 megabytes | import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.File;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author abra
*/
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);
E solver = new E();
solver.solve(1, in, out);
out.close();
}
}
class E extends SimpleSavingChelperSolution {
class Node {
Node left, right;
int l, r, m, val;
Node(int[] a, int l, int r) {
this.l = l;
this.r = r;
m = (l + r) / 2;
if (l + 1 == r) {
val = a[l];
} else {
left = new Node(a, l, m);
right = new Node(a, m, r);
val = Math.min(left.val, right.val);
}
}
void update(int i, int x) {
if (l + 1 == r) {
val = x;
} else {
if (i < m) {
left.update(i, x);
} else {
right.update(i, x);
}
val = Math.min(left.val, right.val);
}
}
int get(int ll, int rr) {
if (ll == l && rr == r) {
return val;
}
int res = Integer.MAX_VALUE;
if (ll < m) {
res = left.get(ll, Math.min(m, rr));
}
if (rr > m) {
res = Math.min(res,
right.get(Math.max(m, ll), rr)
);
}
return res;
}
}
public void solve(int testNumber) {
int W = in.nextInt();
int H = in.nextInt();
int n = in.nextInt();
int m = in.nextInt();
int[][] lads = new int[n][2];
int[][] rects = new int[m][4];
for (int i = 0; i < n; i++) {
lads[i][0] = in.nextInt() - 1;
lads[i][1] = in.nextInt() - 1;
}
for (int i = 0; i < m; i++) {
rects[i][0] = in.nextInt() - 1;
rects[i][1] = in.nextInt() - 1;
rects[i][2] = in.nextInt() - 1;
rects[i][3] = in.nextInt() - 1;
}
List<Integer>[] ladsW = new List[W];
List<Integer>[] rectEndsW = new List[W];
List<Integer>[] ladsH = new List[H];
List<Integer>[] rectEndsH = new List[H];
for (int i = 0; i < W; i++) {
ladsW[i] = new ArrayList<>();
rectEndsW[i] = new ArrayList<>();
}
for (int i = 0; i < H; i++) {
ladsH[i] = new ArrayList<>();
rectEndsH[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
ladsW[lads[i][0]].add(i);
ladsH[lads[i][1]].add(i);
}
for (int i = 0; i < m; i++) {
rectEndsW[rects[i][2]].add(i);
rectEndsH[rects[i][3]].add(i);
}
boolean[] ans = new boolean[m];
// DOWN -> TOP
int[] a = new int[W];
Arrays.fill(a, -1);
Node node = new Node(a, 0, W);
for (int i = 0; i < H; i++) {
for (int j : ladsH[i]) {
node.update(lads[j][0], i);
}
for (int j : rectEndsH[i]) {
int t = node.get(rects[j][0], rects[j][2] + 1);
if (t >= rects[j][1]) {
ans[j] = true;
}
}
}
// LEFT -> RIGHT
a = new int[H];
Arrays.fill(a, -1);
node = new Node(a, 0, H);
for (int i = 0; i < W; i++) {
for (int j : ladsW[i]) {
node.update(lads[j][1], i);
}
for (int j : rectEndsW[i]) {
int t = node.get(rects[j][1], rects[j][3] + 1);
if (t >= rects[j][0]) {
ans[j] = true;
}
}
}
for (int i = 0; i < m; i++) {
out.println(ans[i] ? "YES" : "NO");
}
}
}
abstract class SimpleSavingChelperSolution extends SavingChelperSolution {
public String processOutputPreCheck(int testNumber, String output) {
return output;
}
public String processOutputPostCheck(int testNumber, String output) {
return output;
}
}
class InputReader {
BufferedReader br;
StringTokenizer in;
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
boolean hasMoreTokens() {
while (in == null || !in.hasMoreTokens()) {
String s = nextLine();
if (s == null) {
return false;
}
in = new StringTokenizer(s);
}
return true;
}
public String nextString() {
return hasMoreTokens() ? in.nextToken() : null;
}
public String nextLine() {
try {
in = null; // riad legacy
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
abstract class SavingChelperSolution {
protected int testNumber;
public InputReader in;
public OutputWriter out;
private OutputWriter toFile;
private boolean local = new File("chelper.properties").exists();
public OutputWriter debug = local
? new OutputWriter(System.out)
: new OutputWriter(new OutputStream() {
public void write(int b) {
}
});
public SavingChelperSolution() {
try {
toFile = new OutputWriter("last_test_output.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public abstract void solve(int testNumber);
public abstract String processOutputPreCheck(int testNumber, String output);
public abstract String processOutputPostCheck(int testNumber, String output);
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.testNumber = testNumber;
ByteArrayOutputStream substituteOutContents = new ByteArrayOutputStream();
OutputWriter substituteOut = new OutputWriter(substituteOutContents);
this.in = in;
this.out = substituteOut;
solve(testNumber);
substituteOut.flush();
String result = substituteOutContents.toString();
result = processOutputPreCheck(testNumber, result);
out.print(result);
out.flush();
if (local) {
debug.flush();
result = processOutputPostCheck(testNumber, result);
toFile.print(result);
toFile.flush();
}
}
}
class OutputWriter extends PrintWriter {
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
}
| Java | ["4 3 3 3\n1 1\n3 2\n2 3\n2 3 2 3\n2 1 3 3\n1 2 2 3"] | 2 seconds | ["YES\nYES\nNO"] | NotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook. | Java 8 | standard input | [
"data structures",
"sortings"
] | ab2db2c83d0c9de72f40c9a4c813a37f | The first line contains four integers n, m, k and q (1 ≤ n, m ≤ 100 000, 1 ≤ k, q ≤ 200 000) — the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≤ x ≤ n, 1 ≤ y ≤ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≤ x1 ≤ x2 ≤ n, 1 ≤ y1 ≤ y2 ≤ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≤ x ≤ x2, y1 ≤ y ≤ y2. Strategically important areas can intersect of coincide. | 2,400 | Print q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise. | standard output | |
PASSED | 7cbcf775529a342dc05197444af27cc3 | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.IntStream;
public class _158B
{
public static void main(String... args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Map<Integer, Integer> map = new HashMap<>();
map.put(4, 0);
map.put(3, 0);
map.put(2, 0);
map.put(1, 0);
IntStream.range(0, n).mapToObj(i -> in.nextInt()).forEach(i -> map.computeIfPresent(i, (k, v) -> v + 1));
int count = map.get(4);
Integer c3 = map.get(3);
Integer c1 = map.get(1);
int min = Math.min(c1, c3);
map.computeIfPresent(3, (k, v) -> v - min);
map.computeIfPresent(1, (k, v) -> v - min);
count += min;
Integer c2 = map.get(2);
count += (c2 / 2);
map.computeIfPresent(2, (k, v) -> v % 2);
if (map.get(1) == 0)
{
count += map.get(3);
count += map.get(2);
}
else
{
Integer c = map.get(1);
int q = c / 4;
count += q;
map.computeIfPresent(1, (k, v) -> v % 4);
Integer a = map.get(1);
Integer b = map.get(2) * 2;
if (a + b == 0)
{
count += 0;
}
else if (a + b <= 4)
{
count += 1;
}
else
{
count += 2;
}
}
System.out.println(count);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 8 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | e846aca4ad16a72a940f43562aaa41bb | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.*;
public class Ayrton{
public static void main(String ...ar){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []a = new int[n];
int one = 0;
int two=0;
int three=0;
int four=0;
for(int i=0; i<n; i++){
a[i] = sc.nextInt();
if(a[i] == 1){
one++;
}
else if(a[i] == 2){
two++;
}
else if(a[i] == 3){
three++;
}
else if(a[i] == 4){
four++;
}
}
int taxi = four;//ALL CLEAR
if(three > 0){
if(one > three){
taxi += three;
one = one - three;
three = 0;
}
else if(one < three){
taxi += one;
three = three - one;
one = 0;
}
else if(one == three){
taxi += three;
three = 0;
one = 0;
}
}
if(three > 0){
taxi += three;
three = 0;
}
//System.out.println(taxi);
//ALL CLEAR
if(two > 0){
taxi += two/2;
two = two%2;
}
//System.out.println(taxi);
if(two > 0){
if(one > 0){
taxi++;
two=0;
if(one <= 2){
one = 0;
}
else{
one = one - 2;
}
}
else{
taxi++;
two=0;
}
}
//System.out.println(taxi);
if(one > 0){
taxi += one/4;
one = one%4;
if(one > 0){
taxi++;
}
}
System.out.println(taxi);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 8 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | 798fac1831a2bd4facdcfbbaf3c9c7ff | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.*;
public class Ayrton{
public static void main(String ...ar){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []a = new int[n];
for(int i=0; i<n; i++){
a[i] = sc.nextInt();
}
Arrays.sort(a);
int max = 4;
int sum = 0;
int rides = 0;
/*
for(int i=0;i<n; i++){
System.out.print(a[i] + " ");
}
System.out.println();
*/
int one = 0;
int two = 0;
int three = 0;
int four = 0;
for(int i=0; i<n; i++){
if(a[i] == 1){
one++;
}
else if(a[i] == 2){
two++;
}
else if(a[i] == 3){
three++;
}
else{
four++;
}
}
//System.out.println(one + " " + two + " " + three + " " + four);
/////////////////////////////////////////////////////////////////////////
int temp;
//
rides = four;
//
//
temp = two/2;
rides += temp;
two = two - temp*2;
//
//
if(three <= one){
rides += three;
one = one - three;
three = 0;
}
else{
rides += three;
one = 0;
three = 0;
}
//All Clear uptil now
/* if(two > 0 && one > 0){
if(one <= 2){
rides++;
two = 0;
one = 0;
}
else{
rides++;
two = 0;
one = one -2;
}
}
else if(two > 0 && one == 0){
rides = rides + two;
two = 0;
}
else if(two == 0 && one > 0){
temp = one/4;
rides += temp;
one = one - temp*4;
}
if(one > 0){
rides++;
one = 0;
}
*/
if(two > 0){
if(one > 0){
if(one <= 2){
rides++;
one = 0;
two = 0;
}
else{
rides++;
one = one - 2;
two = 0;
}
}
else{
rides++;
two = 0;
}
}
if(one > 0){
temp = one/4;
rides += temp;
one = one - temp*4;
if(one > 0){
rides++;
one = 0;
}
}
//Final reference
System.out.println(rides);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 8 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | a3a99bbeb876888cac8e5ba94ceee64e | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int num[] = new int[4];
int taxi = 0;
for (int i = 0; i < n; i++) {
num[s.nextInt() - 1]++;
}
// 3 1 처리
if (num[2] > 0 && num[0] > 0) {
int tmp;
if (num[2] > num[0]) {
tmp = num[0];
} else {
tmp = num[2];
}
// int tmp = Math.abs((num[2] - num[0]));
// System.out.println("tmp : " + tmp);
taxi += tmp;
num[0] -= tmp;
num[2] -= tmp;
}
// 2 2 처리
taxi += (num[1] / 2);
num[1] -= (num[1] / 2) * 2;
// 1 2 처리
if (num[1] == 1) {
if (num[0] >= 2) {
taxi++;
num[0] -= 2;
num[1]--;
} else {
if (num[0] > 0) {
taxi++;
num[0]--;
num[1]--;
} else {
taxi++;
num[1]--;
System.out.println(taxi + num[3] + num[2]);
return;
}
}
}
if (num[0] > 0) {
taxi += (num[0] / 4);
if (num[0] - (num[0] / 4) * 4 > 0) {
taxi++;
}
}
System.out.println(taxi + num[3] + num[2]);
// for (int i = 0; i < 4; i++) {
// System.out.println(num[i]);
// }
return;
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 8 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | b4d6fe75e7a9b67d0137faaaf7f8ad1c | train_000.jsonl | 1330804800 | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Taxis {
public static void main(String[] args) throws IOException{
BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));
int grupos = Integer.parseInt(entrada.readLine());
String cantidad = entrada.readLine();
int le = cantidad.length();
int unos = 0;
int dos =0;
int tres = 0;
int cuatros=0;
for (int i=0;i<le;i++){
if (cantidad.charAt(i)=='1'){
unos++;
}
else if (cantidad.charAt(i)=='2'){
dos++;
}
else if (cantidad.charAt(i)=='3'){
tres++;
}
else if (cantidad.charAt(i)=='4'){
cuatros++;
}
}
int taxis = cuatros;
while (unos >0 && tres >0){ //llena con combinaciones de 3 y 1 si es posible
taxis++;
unos--;
tres--;
}
taxis = taxis + tres; //llena con los grupos de tres que queden, si es que quedan
if (dos%2==0){
taxis = taxis + dos/2;
dos = 0;
}
else if (dos%2!=0){
taxis = taxis + (dos-1)/2;
dos = 1;
if (unos>=0){
taxis++;
unos = unos -2;
}
}
if (unos>0){
if(unos%4==0){
taxis = taxis + unos/4;
}
else{
int resto = unos%4;
taxis = taxis + (unos-resto)/4 + 1;
}
}
System.out.println(taxis);
}
} | Java | ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"] | 3 seconds | ["4", "5"] | NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars. | Java 8 | standard input | [
"implementation",
"*special",
"greedy"
] | 371100da1b044ad500ac4e1c09fa8dcb | The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group. | 1,100 | Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus. | standard output | |
PASSED | e093a6c8c36e0655827214b3a15cb730 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes |
/**
*
* @author meashish
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.InputMismatchException;
public class Main {
InputReader in;
PrintStream out;
private void start() {
int n = in.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int val[] = new int[n];
val[0] = 1;
for (int i = 1; i < n; i++) {
int h = Math.min(a[i] - 1, a[i - 1]);
val[i] = Math.min(h + 1, 1 + val[i - 1]);
}
val[n - 1] = 1;
for (int i = n - 2; i >= 0; i--) {
int h = Math.min(a[i] - 1, a[i + 1]);
val[i] = Math.min(val[i], Math.min(h + 1, 1 + val[i + 1]));
}
int max = 0;
for (int i = 0; i < n; i++) {
max = Math.max(max, val[i]);
//out.print(val[i] + " ");
}
//out.println();
out.println(max);
}
public static void main(String[] args) {
//InputReader in = new InputReader(new FileInputStream(new File("in.txt")));
//PrintStream out = new PrintStream("out.txt");
InputReader in = new InputReader(System.in);
PrintStream out = System.out;
Main main = new Main();
main.in = in;
main.out = out;
main.start();
}
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
private class Pair<K, V> implements Serializable {
private K key;
public K getKey() {
return key;
}
private V value;
public V getValue() {
return value;
}
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return key + "=" + value;
}
@Override
public int hashCode() {
return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Pair) {
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) {
return false;
}
if (value != null ? !value.equals(pair.value) : pair.value != null) {
return false;
}
return true;
}
return false;
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 733e4c43def0ef34aa8877c0cf52b71a | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public final class BearAndBlocks
{
public static void main(String[] args)
{
new BearAndBlocks(System.in, System.out);
}
static class Solver
{
// BufferedReader in;
int n;
int[] heights, left, right;
InputReader in;
PrintWriter out;
void solve() throws IOException
{
n = in.nextInt();
heights = new int[n];
left = new int[n];
right = new int[n];
for (int i = 0; i < n; i++)
heights[i] = in.nextInt();
left[0] = Math.min(1, heights[0]);
for (int i = 1; i < n; i++)
left[i] = Math.min(left[i - 1] + 1, heights[i]);
right[n - 1] = Math.min(1, heights[n - 1]);
for (int i = n - 2; i >= 0; i--)
right[i] = Math.min(right[i + 1] + 1, heights[i]);
int ans = 1;
for (int i = 0; i < n; i++)
ans = Math.max(ans, Math.min(left[i], right[i]));
out.println(ans);
}
Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public InputReader(InputStream stream)
{
this.stream = stream;
}
}
public BearAndBlocks(InputStream inputStream, OutputStream outputStream)
{
// uncomment below line to change to BufferedReader
// BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver(in, out);
try
{
solver.solve();
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
out.flush();
out.close();
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 56c59d9d7bc2932e9e0473573c3a046b | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.Scanner;
public class BearAndBlocks {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int heights[] = new int[n + 2];
for (int i = 1; i <= n; ++i)
heights[i] = scanner.nextInt();
scanner.close();
int results[] = new int[n + 2];
for (int i = 1; i <= n; ++i)
results[i] = Math.min(results[i - 1] + 1, heights[i]);
int max = Integer.MIN_VALUE;
for (int i = n; i > 0; --i)
max = Math.max(max,
results[i] = Math.min(results[i + 1] + 1, results[i]));
System.out.println(max);
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 85797312ee04003a2c63e80e63c3702a | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.*;
import java.io.*;
/*NO RESPECT*/
public class Main implements Runnable {
static boolean showTime = false;
public void solve() throws IOException {
int n = nextInt();
int[] h = new int[n];
for(int i = 0; i < n; i++) h[i] = nextInt() - 1;
int[] left = new int[n];
int[] right = new int[n];
left[0] = 0;
for( int i = 1; i < n; i++){
left[i] = Math.min(h[i], left[i-1] + 1);
}
right[n-1] = 0;
for(int i = n - 2; i >= 0; i--){
right[i] = Math.min(h[i], right[i + 1] + 1);
}
int answer = 0;
for(int i = 0; i < n; i++){
//out.println(left[i] + " " + right[i]);
int m = Math.min(left[i], right[i]);
answer = Math.max(answer, m);
}
out.println(answer+1);
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr){
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
if(showTime)System.err.println( (end - start) / 1000.0);
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | a8fb080e4ac42c21fc0a87a4c5026a96 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | //package practice;
/**
* Created by Rajan Waliya on 03-Sep-15.
*/
import java.io.*;
import java.util.*;
//public
class D574 {
Reader sc;
PrintWriter out;
int n;
int[] h;
void solve() throws IOException {
n = sc.nextInt();
h = new int[n+2];
for(int i=1;i<=n;i++){
h[i]=sc.nextInt();
}
int[] res = new int[n+2];// keeps the steps it will take to destroy ith
//from left to right
for(int i=1;i<=n;i++){
res[i]=Math.min(h[i],res[i-1]+1); //will either finish from left or one day at a time; whatever comes first
}
//from right to left
for(int i=n;i>0;i--){
res[i]= Math.min(res[i],res[i+1]+1);
}
int ans = 0;
//find max of these
for(int i=1;i<=n;i++){
ans = Math.max(ans,res[i]);
}
System.out.println(ans);
}
//_______congratulation!!! main logic has ended, no need to understand what is after this line.________
void runIO() throws Exception {
sc = new Reader();
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws Exception {
new D574().runIO();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10L + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public String next() throws IOException {
StringBuilder sb = new StringBuilder();
byte c;
while ((c = read()) <= ' ') ;
do {
sb.append((char) c);
} while ((c = read()) > ' ');
return sb.toString();
}
public int nextInt2() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 41a56beed44ccf6a555360e23c3dcc3c | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | //package practice;
/**
* Created by Rajan Waliya on 03-Sep-15.
*/
import java.io.*;
import java.util.*;
//public
class D574 {
Reader sc;
PrintWriter out;
int n;
int[] h;
void solve() throws IOException {
n = sc.nextInt();
h = new int[n+2];
for(int i=1;i<=n;i++){
h[i]=sc.nextInt();
}
int[] res = new int[n+2];// keeps the steps it will take to destroy ith
//from left to right
for(int i=1;i<=n;i++){
res[i]=Math.min(h[i],res[i-1]+1);
}
//from right to left
for(int i=n;i>0;i--){
res[i]= Math.min(res[i],res[i+1]+1);
}
int ans = 0;
//find max of these
for(int i=1;i<=n;i++){
ans = Math.max(ans,res[i]);
}
System.out.println(ans);
}
//_______congratulation!!! main logic has ended, no need to understand what is after this line.________
void runIO() throws Exception {
sc = new Reader();
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws Exception {
new D574().runIO();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10L + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public String next() throws IOException {
StringBuilder sb = new StringBuilder();
byte c;
while ((c = read()) <= ' ') ;
do {
sb.append((char) c);
} while ((c = read()) > ' ');
return sb.toString();
}
public int nextInt2() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | fc22c5642cfe4c1380ab43412a20cbb1 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class Main{
public static int gcd(int a, int b){
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static int mcm(int a, int b){
return Math.abs(a*b)/gcd(a,b);
}
public static void main(String args[])throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
int n = Integer.parseInt(in.readLine());
int arr[] = readInts(in.readLine());
int r[] = new int[n];
int r2[] = new int[n];
r[0] = 1;
r[n-1] = 1;
r2[0] = 1;
r2[n-1] = 1;
for( int i = 1; i < n-1 ; i++ ){
r[i] = Math.min(i+1, n - i);
r[i] = Math.min(r[i],arr[i]);
r[i] = Math.min(r[i],r[i-1] + 1);
}
for( int i = n-2; i >=1; i-- ){
r2[i] = Math.min(i+1, n - i);
r2[i] = Math.min(r2[i],arr[i]);
r2[i] = Math.min(r2[i],r2[i+1] + 1);
}
int w = -1;
for( int i = 0; i < n; i++ ){
w = Math.max(w, Math.min(r[i],r2[i]));
}
out.append(w);
System.out.println(out);
}
public static int[] readInts(String cad){
String line[] = cad.split(" ");
int arr[] = new int[line.length];
for( int i = 0; i < arr.length ; i++ ){
arr[i] = Integer.parseInt(line[i]);
}
return arr;
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | e5333650bb17e305fbc9a7c6ae2a26e5 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int[] h = sc.readIntArray(n);
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = Math.min(h[i], Math.min(i + 1, n - i));
}
for (int i = 1; i < n; i++) {
dp[i] = Math.min(dp[i], dp[i-1] + 1);
}
for (int i = n - 2; i >= 0; i--) {
dp[i] = Math.min(dp[i], dp[i+1] + 1);
}
int max = Arrays.stream(dp).max().getAsInt();
System.out.println(max);
}
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 | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 338e2921608ad86f0f7d09f9ada15902 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class ProblemD {
public static void main(String[] args){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
String line = br.readLine();
int size = Integer.parseInt(line);
//System.out.println(line);
String line2 = br.readLine();
//System.out.println(line2);
StringTokenizer st = new StringTokenizer(line2);
int[] inputArray = new int[size];
for(int a = 0; a < size; a++){
inputArray[a] = Integer.parseInt(st.nextToken());
if(inputArray[a] > 100000){
inputArray[a] = 100000;
}
}
int[] trackArray = new int[size];
for(int a = 0; a < size; a++){
trackArray[a] = 1000000;
}
trackArray[0] = 1;
trackArray[size - 1] = 1;
for(int a = 1; a < size; a++){
trackArray[a] = Math.min(Math.min(trackArray[a-1] + 1, inputArray[a]), trackArray[a]);
trackArray[size - 1 - a] = Math.min(Math.min(trackArray[size - a] + 1, inputArray[size - 1 - a]), trackArray[size - 1 - a]);
}
if(size % 2 == 1 && size > 1){
trackArray[size/2] = Math.min(Math.min(trackArray[size/2 - 1] + 1, trackArray[size/2 + 1] + 1), inputArray[size/2]);
}
//we have the end
int max = -1;
for(int a = 0; a < size; a++){
if(max < trackArray[a]){
max = trackArray[a];
}
}
System.out.println(max);
//debug(trackArray);
}
catch(Exception e){
//The classic exception handle
//System.out.println("CRAP");
}
}
public static void debug(int[] test){
for(int a = 0; a < test.length; a++){
System.out.print(test[a] + " ");
}
System.out.println();
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | d2538a64b731152222cb0d74035ed4c8 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes |
import java.util.Scanner;
public class Main {
public static long min(long x,long y){
return x<y?x:y;
}
public static long count(long[] original){
int n = original.length;
long[] left = new long[n];
long[] right = new long[n];
long best = 1;
for(int i=0;i<n;i++){
best = min(best,original[i]);
left[i] = best;
best++;
}
best = 1;
for(int i=n-1;i>=0;i--){
best = min(best,original[i]);
right[i] = best;
best++;
}
best = 0;
for(int i=0;i<n;i++){
long value = min(left[i],right[i]);
if(value>best)best = value;
}
return best/*min(best,n%2==0?(n/2):(n/2)+1)*/;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] arr = new long[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextLong();
}
System.out.println(count(arr));
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 74fbe3a99d597fa55105d043541439b4 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String [] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int array[] = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0;i < n;i++){
array[i] = Integer.parseInt(st.nextToken());
}
int low = 0;
int high = n/2 + 5;
while(low < high){
int mid = (low + high)/2;
boolean forward[] = new boolean[n];
boolean backward[] = new boolean[n];
int cnt = 1;
for(int i = 0;i < n;i++){
if(array[i] < cnt){
cnt = array[i];
}
if(cnt == mid){
forward[i - mid + 1] = true;
cnt--;
}
cnt++;
}
cnt = 1;
for(int i = n - 1;i >= 0;i--){
if(array[i] < cnt){
cnt = array[i];
}
if(cnt == mid){
backward[i + mid - 1] = true;
cnt--;
}
cnt++;
}
boolean flag = false;
for(int i = 0;i < n;i++){
//System.out.println(i + " " + (i + 2*mid - 2));
if(i + 2*mid - 2 < n && forward[i] && backward[i + 2*mid - 2]){
flag = true;
}
}
//System.out.println(mid + " " + flag);
if(!flag)high = mid;
else low = mid + 1;
}
System.out.print(low - 1);
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 84217a301cbddaab3183d3183aa842d8 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int nbB = sc.nextInt();
int[] height = new int[nbB];
// we don't care of the first value
sc.nextInt();
height[0] = 1;
for (int i = 1; i < nbB; i++) {
int input = sc.nextInt();
height[i] = min(input, height[i - 1] + 1, nbB - i);
int distanceToPrevToCheck = 1;
while (height[i] + distanceToPrevToCheck < height[i - distanceToPrevToCheck]) {
height[i - distanceToPrevToCheck] = height[i] + distanceToPrevToCheck;
distanceToPrevToCheck++;
}
}
int max = 1;
for (int i = 1; i < nbB; i++) {
if (height[i] > max) {
max = height[i];
}
}
// System.out.println(Arrays.toString(height));
System.out.println(max);
}
private static int min(int input, int i, int j) {
return Math.min(input, Math.min(i, j));
}
// -----------MyScanner class for faster input thx Flatfoot----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (this.st == null || !this.st.hasMoreElements()) {
try {
this.st = new StringTokenizer(this.br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return this.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 = this.br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// --------------------------------------------------------
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | a98292e630378fb92b4c9113d3123c0e | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Random;
import java.util.StringTokenizer;
public class D
{
public static final Random RANDOM = new Random(System.currentTimeMillis());
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
private PrintWriter printWriter;
public D()
{
this(new BufferedReader(new InputStreamReader(System.in)));
}
public D(BufferedReader bufferedReader)
{
this.bufferedReader = bufferedReader;
this.stringTokenizer = null;
this.printWriter = new PrintWriter(new BufferedOutputStream(System.out));
}
public D(String file) throws FileNotFoundException
{
this(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
}
private String next() throws IOException
{
while ((this.stringTokenizer == null) || (!this.stringTokenizer.hasMoreTokens()))
{
this.stringTokenizer = new StringTokenizer(this.bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(next());
}
public long nextLong() throws IOException
{
return Long.parseLong(next());
}
public String nextLine() throws IOException
{
return this.bufferedReader.readLine();
}
public void close()
{
printWriter.close();
}
public static void main(String[] args)
{
D template = new D();
try
{
template.solve();
}
catch (IOException exception)
{
exception.printStackTrace();
}
template.close();
}
public static int[] destroy(int[] h)
{
int[] result = new int[h.length];
for (int index = 0; index < h.length; index++)
{
if (h[index] > 0)
{
int internal = h[index] - 1;
if (index > 0)
{
internal = Math.min(internal, h[index - 1]);
}
else
{
internal = 0;
}
if (index < h.length - 1)
{
internal = Math.min(internal, h[index + 1]);
}
else
{
internal = 0;
}
result[index] = internal;
}
}
return result;
}
public static boolean destroyed(int[] h)
{
boolean result = true;
for (int index = 0; index < h.length; index++)
{
result &= h[index] == 0;
}
return result;
}
public static int solve(int n, int[] h)
{
int result = 0;
for (int index = 0; index < h.length; index++)
{
if (index == 0)
{
h[index] = Math.min(1, h[index]);
}
else
{
h[index] = Math.min(h[index - 1] + 1, h[index]);
}
}
for (int index = h.length - 1; index >= 0; index--)
{
if (index == h.length - 1)
{
h[index] = Math.min(1, h[index]);
}
else
{
h[index] = Math.min(h[index + 1] + 1, h[index]);
}
result = Math.max(result, h[index]);
}
// while (!destroyed(h))
// {
// result += 1;
// h = destroy(h);
// }
return result;
}
public void solve() throws IOException
{
int n = nextInt();
int[] h = new int[n];
for (int index = 0; index < n; index++)
{
h[index] = nextInt();
}
this.printWriter.println(solve(n, h));
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 620d83ec25af43bcee84728ad154511f | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public int howMuch(int n, int [] t) {
int worst = 0;
int [] res = new int[n + 1];
Arrays.fill(res, 0);
for(int i = 1; i<=n; i++) {
worst = Math.min(worst, t[i - 1] - i);
res[i] = i + worst;
}
worst = n + 1;
for(int i = n; i>=1; i--) {
worst = Math.min(worst, t[i - 1] + i);
res[i] = Math.min(res[i], worst - i);
}
int r = 0;
for(int i = 1; i<=n; i++) {
r = Math.max(r, res[i]);
}
return r;
}
public static void main(String [] argv) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int []a = new int[n];
for(int i = 0; i<n; i++) {
a[i] = sc.nextInt();
}
Main main = new Main();
System.out.println(main.howMuch(n, a));
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 6e19d9506fce31bc064fba679b5afb76 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author asdf_alex
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int[] le = new int[n], ri = new int[n];
int d = 0;
for (int i = 0; i < n; ++i){
++d;
d = Math.min(d, a[i]);
le[i] = d;
}
d = 0;
int ans = 0;
for (int i = n-1; i >= 0; --i){
++d;
d = Math.min(d, a[i]);
ri[i] = d;
}
for (int i = 0; i < n; ++i) ans = Math.max(ans, Math.min(le[i], ri[i]));
out.println(ans);
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextIntArray(int size) {
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = nextInt();
}
return result;
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 3ea8601f84c60ab0e18326079bbda369 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.*; //PrintWriter
import java.math.*; //BigInteger, BigDecimal
import java.util.*; //StringTokenizer, ArrayList
public class R318_Div2_D
{
FastReader in;
PrintWriter out;
public static void main(String[] args) {
new R318_Div2_D().run();
}
void run()
{
in = new FastReader(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void solve()
{
int n = in.nextInt();
int[] h = new int[n];
int[] l = new int[n];
int[] r = new int[n];
for (int i = 0; i < n; i++)
h[i] = in.nextInt();
l[0] = 1;
for (int i = 1; i < n; i++)
l[i] = Math.min(h[i], Math.min(i+1, l[i-1]+1));
r[n-1] = 1;
for (int i = n-2; i >= 0; i--)
r[i] = Math.min(h[i], Math.min(n-i, r[i+1]+1));
int max = 0;
for (int i = 0; i < n; i++)
max = Math.max(max, Math.min(l[i], r[i]));
out.println(max);
}
//-----------------------------------------------------
void runWithFiles() {
in = new FastReader(new File("input.txt"));
try {
out = new PrintWriter(new File("output.txt"));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
solve();
out.close();
}
class FastReader
{
BufferedReader br;
StringTokenizer tokenizer;
public FastReader(InputStream stream)
{
br = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public FastReader(File f) {
try {
br = new BufferedReader(new FileReader(f));
tokenizer = null;
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(br.readLine());
}
catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return br.readLine();
}
catch(Exception e) {
throw(new RuntimeException());
}
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
BigInteger nextBigInteger() {
return new BigInteger(next());
}
BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 9d313e3f7f22cb016809b03fccd86b3d | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.*;
import java.util.*;
public class cf318_d_2 {
public void solve() throws IOException {
int n = nextInt();
int a[] = new int[n];
int l[] = new int[n];
int r[] = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
l[0] = 1;
for (int i = 1; i < n; ++i) {
l[i] = Math.min(a[i], l[i - 1] + 1);
}
r[n - 1] = 1;
for (int i = n - 2; i >= 0; --i) {
r[i] = Math.min(a[i], r[i + 1] + 1);
}
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = Math.max(ans, Math.min(l[i], r[i]));
}
out.print(ans);
}
public void run() throws IOException {
try {
// br = new BufferedReader(new FileReader(new File(".in")));
// out = new PrintWriter(".out");
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
br.close();
out.close();
} catch (IOException e) {
}
}
public static void main(String[] args) throws IOException {
new cf318_d_2().run();
}
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
try {
in = new StringTokenizer(br.readLine());
} catch (IOException | NullPointerException e) {
throw new IOException();
}
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | b7e184adb49b26bf3c5a3115015de8c9 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes |
import java.io.*;
import java.util.*;
public class D {
InputStream is;
int __t__ = 1;
int __f__ = 0;
int __FILE_DEBUG_FLAG__ = __f__;
String __DEBUG_FILE_NAME__ = "src/T";
FastScanner in;
PrintWriter out;
class State implements Comparable<State> {
int id;
int op;
State(int id, int op) {
this.id = id;
this.op = op;
}
public int compareTo(State s) {
return op - s.op;
}
public String toString() {
return getClass().getName() + " : " + id + " " + op;
}
}
public void solve() {
int n = in.nextInt();
int[] h = in.nextIntArray(n);
PriorityQueue<State> pq = new PriorityQueue<State>();
int[] operation = new int[n];
Arrays.fill(operation, Integer.MAX_VALUE);
boolean[] used = new boolean[n];
for (int i = 0; i < n; i++) {
operation[i] = Math.min(i + 1, n - i);
operation[i] = Math.min(operation[i], h[i]);
pq.add(new State(i, operation[i]));
}
int res = 0;
while (!pq.isEmpty()) {
State st = pq.poll();
if (used[st.id]) continue;
used[st.id] = true;
res = Math.max(res, st.op);
if (st.id > 0 && !used[st.id-1]) {
int nextId = st.id - 1;
int nextOp = Math.min(st.op + 1, operation[nextId]);
pq.add(new State(nextId, nextOp));
}
if (st.id < n - 1 && !used[st.id+1]) {
int nextId = st.id + 1;
int nextOp = Math.min(st.op + 1, operation[nextId]);
pq.add(new State(nextId, nextOp));
}
}
System.out.println(res);
}
public void run() {
if (__FILE_DEBUG_FLAG__ == __t__) {
try {
is = new FileInputStream(__DEBUG_FILE_NAME__);
} catch (FileNotFoundException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
System.out.println("FILE_INPUT!");
} else {
is = System.in;
}
in = new FastScanner(is);
out = new PrintWriter(System.out);
solve();
}
public static void main(String[] args) {
new D().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());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextIntArray(m);
}
return map;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
long[][] nextLongMap(int n, int m) {
long[][] map = new long[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextLongArray(m);
}
return map;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][m];
for (int i = 0; i < n; i++) {
map[i] = in.nextDoubleArray(m);
}
return map;
}
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[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
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 | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 21d386efbe7d6e197c48846d71b0856c | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.*;
import java.io.*;
public class CF574D{
public static int index;
public static void main(String[] args)throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = in.nextInt();
int [] a = new int[n+2];
for(int i = 1; i <= n; i++){
a[i] = in.nextInt();
}
for(int i = 1; i <= n; i++){
if(a[i-1] < a[i]) a[i] = a[i-1] + 1;
}
for(int i = n; i >= 1; i--){
if(a[i+1] < a[i]) a[i] = a[i+1] + 1;
}
int max = 0;
for(int i = 1; i <= n; i++){
max = Math.max(max, a[i]);
}
pw.println(max);
pw.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next()throws Exception {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
public String nextLine()throws Exception {
String line = null;
tokenizer = null;
line = reader.readLine();
return line;
}
public int nextInt()throws Exception {
return Integer.parseInt(next());
}
public double nextDouble() throws Exception{
return Double.parseDouble(next());
}
public long nextLong()throws Exception {
return Long.parseLong(next());
}
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | b8aa8dbe30b8ee12a81fb37abef6ee80 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.*;
import java.util.*;
public class PrD {
public static void main(String[] args) throws IOException {
new PrD().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out, true);
solve();
out.flush();
}
// int n;
// int[] a;
// int[] time;
//
// int getTime(int i) {
// if(i == 0 || i == n + 1) {
// return 0;
// }
// if(time[i] != 0) {
// return time[i];
// }
// time[i] = Math.min(Math.min(time[i-1] + 1, time[i+1] + 1), a[i]);
// return time[i];
// }
//
void solve() throws IOException {
int n = nextInt();
int[] a = new int[n + 2];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
int[] time = new int[n + 2];
TreeSet<Integer> magic = new TreeSet<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (time[o1] != time[o2]) {
return Integer.compare(time[o1], time[o2]);
}
return Integer.compare(o1, o2);
}
});
// magic.add(0);
// magic.add(n+1);
for (int i = 1; i <= n; i++) {
time[i] = Math.min(i, Math.min(n - i + 1, a[i]));
magic.add(i);
}
while (!magic.isEmpty()) {
int min = magic.pollFirst();
if (time[min - 1] > time[min] + 1) {
magic.remove(min - 1);
time[min - 1] = time[min] + 1;
magic.add(min - 1);
}
if (time[min + 1] > time[min] + 1) {
magic.remove(min + 1);
time[min + 1] = time[min] + 1;
magic.add(min + 1);
}
}
int max = 0;
for (int i = 1; i <= n; i++) {
max = Math.max(max, time[i]);
}
out.println(max);
// for(int i = 1; i <= n; i++) {
// if(time[i] == 0) {
// getTime(i);
// }
// }
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | a4957f348187e83b7c32f5a934e5980d | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.Scanner;
/**
* Created by slycer on 9/15/15.
*/
public class BearandBlocks {
public static void main ( String [] args ){
Scanner s = new Scanner( System.in );
int n = s.nextInt();
int [] data = new int[n+2];
for ( int i=1; i<=n; i++ ){
data[i] = s.nextInt();
}
int [] left = new int[ n + 2 ];
int [] right = new int[ n + 2 ];
for ( int i=1; i<=n; i++ ){
left[i] = Math.min( left[i-1] + 1, data[i] );
// System.out.print( left[i] + " " );
}
//System.out.println();
for ( int i=n; i>=1; i-- ){
right[i] = Math.min( right[i+1] + 1, data[i] );
//System.out.print( right[i] + " " );
}
//System.out.println();
int sol = 0;
for ( int i=1; i<=n; i++ ){
sol = Math.max( sol, Math.min( left[i], right[i] ) ) ;
}
System.out.println( sol );
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | cdf7d5b26925ac292326cf9d39135519 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 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.stream.IntStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author padington
*/
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.nextInt();
int[] h = new int[n + 1];
int[] res = new int[n + 2];
for (int i = 1; i <= n; i++) {
h[i] = in.nextInt();
}
for (int i = 1; i <= n; i++) {
res[i] = minOfArray(res[i - 1] + 1, i, h[i]);
}
int ans = 0;
for (int i = n; i > 0; i--) {
res[i] = minOfArray(res[i], res[i + 1] + 1, n - i + 1);
ans = Math.max(ans, res[i]);
}
out.println(ans);
}
int minOfArray(int... array) {
return IntStream.of(array).min().getAsInt();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 183339083b68cd4e5b8e1cedda2331d7 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 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.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author padington
*/
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.nextInt();
int[] h = new int[n + 1];
int[] res = new int[n + 1];
for (int i = 1; i <= n; i++) {
h[i] = in.nextInt();
}
int worst = 0;
for (int i = 1; i <= n; i++) {
worst = Math.min(worst, h[i] - i);
res[i] = i + worst;
}
worst = 0;
int ans = 0;
for (int i = n; i > 0; i--) {
worst = Math.min(worst, h[i] - (n - i + 1));
res[i] = Math.min(res[i], worst + (n - i + 1));
ans = Math.max(ans, res[i]);
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 9d354e9c4836d8260114d3dde47e732b | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 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.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author padington
*/
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.nextInt();
int[] h = new int[n + 1];
int[] res = new int[n + 1];
for (int i = 1; i <= n; i++) {
h[i] = in.nextInt();
}
int worst = 0;
for (int i = 1; i <= n; i++) {
worst = Math.min(worst, h[i] - i);
res[i] = i + worst;
}
worst = 0;
int ans = 0;
for (int i = n; i > 0; i--) {
worst = Math.min(worst, h[i] - (n - i + 1));
res[i] = Math.min(res[i], worst + (n - i + 1));
res[i] = Math.min(res[i], (n - i + 1));
ans = Math.max(ans, res[i]);
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | cf0adb5589c2d65806cab6142e7ddb30 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class Main {
private FastScanner in;
private PrintWriter out;
private void solve() throws IOException {
int n = in.nextInt(), ans = 0;
int[] h = new int[n + 1], l = new int[n + 1], r = new int[n + 2];
for (int i = 1; i <= n; i++)
h[i] = in.nextInt();
for (int i = 1; i <= n; i++)
l[i] = min(l[i - 1] + 1, h[i]);
for (int i = n; i > 0; i--)
r[i] = min(r[i + 1] + 1, h[i]);
for (int i = 1; i <= n; i++)
ans = max(ans, min(l[i], r[i]));
out.print(ans);
}
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());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean ready() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | baa598c1d14547af173c804c479fc24f | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i, k=0;
int[] h= new int[100002];
int[] l= new int[100002];
int[] r= new int[100002];
int n=in.nextInt();
for (i=1; i<=n; i++)
h[i]=in.nextInt();
for (i=1; i<=n; i++)
l[i] = Math.min(l[i - 1] + 1, h[i]);
for (i=n; i>0; i--)
r[i] = Math.min(r[i + 1] + 1, h[i]);
for (i=1; i<=n; i++)
k = Math.max(k, Math.min(l[i], r[i]));
System.out.print(k+"");
in.close();
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 466b164b260e808587f801c8695fc359 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] m = new int[n];
for (int i = 0; i < n; ++i) m[i] = in.nextInt();
int[] right = new int[n];
int[] left = new int[n];
right[0] = left[n - 1] = 1;
int res = 0;
for (int i = 1; i < n; ++i) right[i] = Math.min(right[i - 1] + 1, m[i]);
for (int i = n - 2; i >= 0; --i) left[i] = Math.min(left[i + 1] + 1, m[i]);
for (int i = 0; i < n; ++i) res = Math.max(res, Math.min(right[i], left[i]));
out.println(res);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | fc496caedf9371e6134d32ceb1f0cb9d | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.Scanner;
//
public class GYM2E {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = scan.nextInt();
}
int[] left = new int[n];
int[] right = new int[n];
left[0] = 1;
right[n-1] = 1;
for(int i = 1; i < n; i++){
left[i] = Math.min(arr[i]-1, left[i-1])+1;
}
for(int i = n-2; i >= 0; i--){
right[i] = Math.min(arr[i]-1, right[i+1])+1;
}
int ans = 0;
for(int i = 0; i < n; i++){
ans = Math.max(ans, Math.min(left[i], right[i]));
}
System.out.println(ans);
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | eaf142c970e90ec5d48f732282dd0dde | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.PrintStream;
import java.util.Scanner;
public class myclass {
public static PrintStream out = System.out;
public static Scanner in = new Scanner(System.in);
public static void main(String[] args){
int n = in.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
int dp1[]= new int[n], dp2[] = new int[n];
dp1[0] = 1;
for (int i = 1; i < n; i++)
dp1[i] = Math.min(dp1[i - 1] + 1, a[i]);
dp2[n - 1] = 1;
for (int i = n - 2; i >= 0; i--)
dp2[i] = Math.min(dp2[i + 1] + 1, a[i]);
int ans = 0;
for (int i = 0; i < n; i++)
ans = Math.max(ans, Math.min(dp1[i], dp2[i]));
out.println(ans);
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 9e64550699b5d0986c8a9f0f12340c9c | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedInputStream;
import java.util.Scanner;
public class DBlocks {
public static void main(String[] args) {
final Scanner scanner = new Scanner(new BufferedInputStream(System.in));
int N = scanner.nextInt();
int[] height = new int[N + 1];
int[] shutdown = new int[N + 1];
for (int i = 1; i <= N; i++)
height[i] = scanner.nextInt();
int cascade = 0;
for (int i = 1; i <= N; i++) {
cascade = Math.min(cascade, height[i] - i); // note that cascade is always a non-positive number
shutdown[i] = i + cascade;
}
cascade = 0;
for (int i = N; i >= 1; i--) {
cascade = Math.min(cascade, height[i] - (N - i + 1));
shutdown[i] = Math.min(shutdown[i], (N - i + 1) + cascade);
}
int minTime = 0;
for (int i = 1; i <= N; i++)
minTime = Math.max(minTime, shutdown[i]);
System.out.println(minTime);
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | be0736a27239c3d51153f373ec88ed77 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class SolveD {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static void main(String[] args) throws IOException {
new SolveD().run();
}
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
int[] needLeft = new int[n];
int[] needRight = new int[n];
for (int i = 0; i < n; i++) {
if (i == 0) {
needLeft[i] = 1;
needRight[n - i - 1] = 1;
} else {
needLeft[i] = Math.min(needLeft[i - 1], a[i - 1]) + 1;
needRight[n - i - 1] = Math.min(needRight[n - i], a[n - i]) + 1;
}
}
int answer = 0;
for (int i = 0; i < n; i++) {
int current = Math.min(a[i],Math.min(needLeft[i], needRight[i]));
answer = Math.max(answer, current);
}
out.println(answer);
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in)); // new InputStreamReader(System.in)
out = new PrintWriter(System.out); // System.out
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 0ee6a1bda123a63d924b474f76a50462 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class q5 {
public static int gcd(int a,int b) {
if(b==0) return a;
else return gcd(b,a%b);
}
// Credits to GFG
static public int dfs(ArrayList<Integer>[] graph,ArrayList<Integer> arr, int start, int[] visited) {
visited[start]=1;
boolean leaf=true;
int ans=0;
int totalchild=0;
for(int i:graph[start]) {
if(visited[i]==0) {
ans+=q5.dfs(graph, arr, i, visited);
leaf=false;
}
}
if(leaf) ans=1;
arr.add(ans);
return ans;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Editorial implementation for practice
Reader.init(System.in);
StringBuffer output=new StringBuffer("");
PrintWriter out=new PrintWriter(System.out);
int n=Reader.nextInt();
int[] arr=new int[n+2];
for(int i=1;i<=n;i++) arr[i]=Reader.nextInt();
for(int i=1;i<=n;i++) {
arr[i]=Math.min(arr[i], arr[i-1]+1);
}
for(int i=n;i>=1;i--) {
arr[i]=Math.min(arr[i], arr[i+1]+1);
}
int max=0;
for(int i=1;i<=n;i++) {
max=Math.max(max, arr[i]);
}
output.append(max);
out.write(output.toString());
out.flush();
}
}
class Node2{
String name;
double ft,st;
Node2(String a,double b,double c){
name=a;
ft=b;
st=c;
}
}
class Heap{
int[] mylist;
int[] mymap;
int[] vtxmymap;
int size;
long[] update;
long updatevalue;
int[] removed;
Heap(int[] graph){
int l=graph.length;
updatevalue=0;
removed=new int[l];
update=new long[l];
size=l-1;
mylist=new int[l];
mymap=new int[l];
vtxmymap=new int[l];
for(int i=size;i>0;i--) {
if(i>size/2) {
mylist[i]=graph[i];
mymap[i]=i;
vtxmymap[i]=i;
}
else {
mylist[i]=graph[i];
mymap[i]=i;
vtxmymap[i]=i;
boolean end=false;
int parent=i;
while(!end) {
int leftchild=2*parent;
int rightchild=2*parent+1;
if(leftchild>size) {
end=true;
}
else if(rightchild>size) {
if(mylist[leftchild]<mylist[parent]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[leftchild];
int parentDeg=mylist[parent];
int childDeg=mylist[leftchild];
mylist[parent]=childDeg;
mylist[leftchild]=parentDeg;
mymap[parentNode]=leftchild;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[leftchild]=parentNode;
parent=leftchild;
}
else end=true;
}
else {
if(mylist[leftchild]<=mylist[rightchild]) {
if(mylist[leftchild]<mylist[parent]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[leftchild];
int parentDeg=mylist[parent];
int childDeg=mylist[leftchild];
mylist[parent]=childDeg;
mylist[leftchild]=parentDeg;
mymap[parentNode]=leftchild;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[leftchild]=parentNode;
parent=leftchild;
}
else end=true;
}
else {
if(mylist[rightchild]<mylist[parent]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[rightchild];
int parentDeg=mylist[parent];
int childDeg=mylist[rightchild];
mylist[parent]=childDeg;
mylist[rightchild]=parentDeg;
mymap[parentNode]=rightchild;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[rightchild]=parentNode;
parent=rightchild;
}
else end=true;
}
}
}
}
}
}
void update(int child) {
if(update[child]==updatevalue) return;
boolean end=false;
while(!end) {
update[child]=updatevalue;
int parent=child/2;
if(parent<1) end=true;
else {
if(mylist[parent]>mylist[child]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[child];
int parentDeg=mylist[parent];
int childDeg=mylist[child];
mylist[parent]=childDeg;
mylist[child]=parentDeg;
mymap[parentNode]=child;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[child]=parentNode;
parent=child;
}
else end=true;
}
}
}
int peek() {
return mylist[1];
}
int pop() {
int toreturn=mylist[1];
removed[vtxmymap[1]]=1;
mylist[1]=mylist[size];
int changedNode=vtxmymap[size];
vtxmymap[1]=changedNode;
mymap[changedNode]=1;
boolean end=false;
size--;
if(size==0) end=true;
int parent=1;
while(!end) {
int leftchild=2*parent;
int rightchild=2*parent+1;
if(leftchild>size) {
end=true;
}
else if(rightchild>size) {
if(mylist[leftchild]<mylist[parent]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[leftchild];
int parentDeg=mylist[parent];
int childDeg=mylist[leftchild];
mylist[parent]=childDeg;
mylist[leftchild]=parentDeg;
mymap[parentNode]=leftchild;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[leftchild]=parentNode;
parent=leftchild;
}
else end=true;
}
else {
if(mylist[leftchild]<=mylist[rightchild]) {
if(mylist[leftchild]<mylist[parent]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[leftchild];
int parentDeg=mylist[parent];
int childDeg=mylist[leftchild];
mylist[parent]=childDeg;
mylist[leftchild]=parentDeg;
mymap[parentNode]=leftchild;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[leftchild]=parentNode;
parent=leftchild;
}
else end=true;
}
else {
if(mylist[rightchild]<mylist[parent]) {
int parentNode=vtxmymap[parent];
int childNode=vtxmymap[rightchild];
int parentDeg=mylist[parent];
int childDeg=mylist[rightchild];
mylist[parent]=childDeg;
mylist[rightchild]=parentDeg;
mymap[parentNode]=rightchild;
mymap[childNode]=parent;
vtxmymap[parent]=childNode;
vtxmymap[rightchild]=parentNode;
parent=rightchild;
}
else end=true;
}
}
}
return toreturn;
}
}
class DisJoint {
int[] parent;
int[] rank;
int[] size;
DisJoint(int n){
parent=new int[n+1];
rank=new int[n+1];
for(int i=0;i<=n;i++) {
parent[i]=i;
}
}
int find(int value) {
int par=parent[value];
if(par==value)
return par;
parent[value]=find(par);
return parent[value];
}
void union(int data1,int data2) {
int parent1=find(data1);
int parent2=find(data2);
if(parent1!=parent2) {
if(rank[parent1]>=rank[parent2]) {
parent[parent2]=parent1;
if(rank[parent1]==rank[parent2])
rank[parent1]++;
}
else {
parent[parent1]=parent2;
}
}
}
}
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 nextLine() throws IOException{
return reader.readLine();
}
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() );
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 3d331c3ae91b9fb58b3ae058d0552917 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
public class BearAndBlocks {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int[] H = new int[N + 2];
for (int i = 1; i <= N; i++) {
H[i] = sc.nextInt();
}
int[] dl = new int[N + 2];
int L = 0;
for (int i = 1; i <= N; i++) {
if (dist(H, i, i) <= dist(H, L, i)) {
L = i;
}
dl[i] = dist(H, L, i);
}
int[] dr = new int[N + 2];
int R = N + 1;
for (int i = N; i >= 1; i--) {
if (dist(H, i, i) <= dist(H, R, i)) {
R = i;
}
dr[i] = dist(H, R, i);
}
int maxDist = 0;
for (int i = 1; i <= N; i++) {
int dist = Math.min(dl[i], dr[i]);
maxDist = Math.max(maxDist, dist);
}
System.out.println(maxDist);
}
public static int dist(int[] H, int space, int block) {
return H[space] + Math.abs(space - block);
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 8421595c3d03f2b48b6daea09a9efce3 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class p4 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt();
int[] h = new int[n];
int[] left = new int[n];
int[] right = new int[n];
left[0] = 1; right[n - 1] = 1;
for (int i = 0; i < n; i++) {
h[i] = in.nextInt();
}
for (int i = 1; i < n; i++) {
left[i] = Math.min(h[i], Math.min(i + 1, left[i - 1] + 1));
}
for (int i = n - 2; i >= 0; i--) {
right[i] = Math.min(h[i], Math.min(n - i, right[i + 1] + 1));
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
max = Math.max(max, Math.min(left[i], right[i]));
}
out.println(max);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public boolean hasMoreElements() {
while (tokenizer == null || !tokenizer.hasMoreElements()) {
String s;
try {
s = reader.readLine();
} catch (IOException e) {
return false;
}
tokenizer = new StringTokenizer(s);
}
return tokenizer.hasMoreElements();
}
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | d1b52b98a5580199954bf7f97a7e703e | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String [] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int array[] = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0;i < n;i++){
array[i] = Integer.parseInt(st.nextToken());
}
int low = 0;
int high = n/2 + 5;
while(low < high){
int mid = (low + high)/2;
boolean forward[] = new boolean[n];
boolean backward[] = new boolean[n];
int cnt = 1;
for(int i = 0;i < n;i++){
if(array[i] < cnt){
cnt = array[i];
}
if(cnt == mid){
forward[i - mid + 1] = true;
cnt--;
}
cnt++;
}
cnt = 1;
for(int i = n - 1;i >= 0;i--){
if(array[i] < cnt){
cnt = array[i];
}
if(cnt == mid){
backward[i + mid - 1] = true;
cnt--;
}
cnt++;
}
boolean flag = false;
for(int i = 0;i < n;i++){
//System.out.println(i + " " + (i + 2*mid - 2));
if(i + 2*mid - 2 < n && forward[i] && backward[i + 2*mid - 2]){
flag = true;
}
}
//System.out.println(mid + " " + flag);
if(!flag)high = mid;
else low = mid + 1;
}
System.out.print(low - 1);
}
} | Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | e0c08e6d3b0cc3cacb80efd333bbc7d9 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Artyom Korzun
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] h = in.nextIntArray(n);
int[] l = new int[n];
int[] r = new int[n];
l[0] = 1;
for (int i = 1; i < n; i++)
l[i] = Math.min(h[i], l[i - 1] + 1);
r[n - 1] = 1;
for (int i = n - 2; i >= 0; i--)
r[i] = Math.min(h[i], r[i + 1] + 1);
int answer = -1;
for (int i = 0; i < n; i++)
answer = Math.max(answer, Math.min(r[i], l[i]));
out.print(answer);
}
}
class FastScanner {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public int[] nextIntArray(int length) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 3ca5272d5c482b7a6f9eb57011cf73f8 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.util.Scanner;
/**
* @author misterku
*/
public class Solution implements Runnable {
public static void main(String[] args) {
new Thread(new Solution()).start();
}
@Override
public void run() {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Math.min(i + 1, n - i);
if (i > 0) {
a[i] = Math.min(a[i - 1] + 1, a[i]);
}
int c = cin.nextInt();
if (c >= a[i]) {
continue;
}
a[i] = c;
int tmp = i - 1;
while (tmp >= 0 && a[tmp] > a[tmp + 1] + 1) {
a[tmp] = a[tmp + 1] + 1;
tmp--;
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, a[i]);
}
System.out.println(ans);
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | 698f7d549a519a4254dfe65b2ec54e19 | train_000.jsonl | 1440865800 | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
import java.util.stream.IntStream;
import static java.lang.Math.*;
import static java.util.stream.IntStream.range;
public class Sub {
public static void main(String[] args) throws Exception {
new Sub().doit();
}
public long gcdl(long a, long b) {
if (b == 0) return a;
return gcdl(b, a % b);
}
public long lcml(long a, long b) {
return (b / gcdl(a, b)) * a;
}
public int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public int lcm(int a, int b) {
return (b / gcd(a, b)) * a;
}
boolean check(int[] z) {
for (int i = 0; i < z.length; i++) {
if (z[i] != 0) return false;
}
return true;
}
public void doit() throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int res = 0;
int[] dpLeft = new int[n];
int[] dpRight = new int[n];
Arrays.fill(dpLeft, 987654321);
Arrays.fill(dpRight, 987654321);
dpLeft[0] = 1;
dpRight[n-1] = 1;
for (int i = 1; i < n; i++) {
dpLeft[i] = min(arr[i], dpLeft[i-1] + 1);
}
for (int i = 1; i < n; i++) {
dpRight[n-1-i] = min(arr[n-1-i], dpRight[n - i] + 1);
}
int mx = 0;
for (int i = 0; i < n; i++) {
mx = max(mx, min(dpLeft[i], dpRight[i]));
//System.err.print(dpLeft[i] + ":" + dpRight[i] + " ");
}
out.println(mx);
sc.close();
out.close();
}
}
| Java | ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"] | 1 second | ["3", "2"] | NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation. | Java 8 | standard input | [
"dp",
"shortest paths",
"data structures",
"math"
] | a548737890b4bf322d0f8989e5cd25ac | The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers. | 1,600 | Print the number of operations needed to destroy all towers. | standard output | |
PASSED | e6125d163b712afacb1d9589a6df8b33 | train_000.jsonl | 1458910800 | Johnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience.In that country there are n islands and m bridges between them, so you can travel from any island to any other. In the middle of some bridges are lying ancient powerful artifacts. Johnny is not interested in artifacts, but he can get some money by selling some artifact.At the start Johnny is in the island a and the artifact-dealer is in the island b (possibly they are on the same island). Johnny wants to find some artifact, come to the dealer and sell it. The only difficulty is that bridges are too old and destroying right after passing over them. Johnnie's character can't swim, fly and teleport, so the problem became too difficult.Note that Johnny can't pass the half of the bridge, collect the artifact and return to the same island. Determine if Johnny can find some artifact and sell it. | 512 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf302218c {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni();
List<Map<Integer, Integer>> g = new ArrayList<>(), ng = new ArrayList<>();
for (int i = 0; i < n; ++i) {
g.add(new HashMap<>());
ng.add(new HashMap<>());
}
for (int i = 0; i < m; ++i) {
int u = rni() - 1, v = ni() - 1, w = ni();
g.get(u).put(v, w);
g.get(v).put(u, w);
}
int s = rni() - 1, e = ni() - 1;
boolean[] vis = new boolean[n];
List<Integer> order = new ArrayList<>();
List<Set<Integer>> evis = new ArrayList<>();
for (int i = 0; i < n; ++i) {
evis.add(new HashSet<>());
}
del_reverse_edge(g, s, vis, order, ng, evis);
g = ng;
/* for (Map<Integer, Integer> adj : g) {
prln(adj.keySet().toString());
} */
Collections.reverse(order);
List<Map<Integer, Integer>> t = new ArrayList<>();
for (int i = 0; i < n; ++i) {
t.add(new HashMap<>());
}
for (int i = 0; i < n; ++i) {
for (int j : g.get(i).keySet()) {
t.get(j).put(i, g.get(i).get(j));
}
}
fill(vis, false);
List<List<Integer>> comps = new ArrayList<>();
int lbl[] = new int[n], cur = 0;
boolean artifact[] = new boolean[n];
for (int i : order) {
if (!vis[i]) {
List<Integer> comp = new ArrayList<>();
if (scc(t, i, vis, comp)) {
artifact[cur] = true;
}
comps.add(comp);
for (int j : comp) {
lbl[j] = cur;
}
++cur;
}
}
List<Map<Integer, Integer>> sccg = new ArrayList<>();
for (int i = 0; i < cur; ++i) {
sccg.add(new HashMap<>());
}
fill(vis, false);
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
build(g, i, vis, lbl, sccg);
}
}
/* for (Map<Integer, Integer> adj : sccg) {
prln(adj);
} */
prYN(dfs(sccg, lbl[s], artifact, lbl[e], false));
close();
}
static boolean dfs(List<Map<Integer, Integer>> g, int i, boolean[] artifact, int e, boolean seen) {
if (i == e) {
return seen || artifact[i];
}
for (int j : g.get(i).keySet()) {
if (dfs(g, j, artifact, e, seen || artifact[i] || g.get(i).get(j) == 1)) {
return true;
}
}
return false;
}
static void build(List<Map<Integer, Integer>> g, int i, boolean[] vis, int lbl[], List<Map<Integer, Integer>> cg) {
vis[i] = true;
for (int j : g.get(i).keySet()) {
if (lbl[i] != lbl[j]) {
cg.get(lbl[i]).put(lbl[j], max(cg.get(lbl[i]).getOrDefault(lbl[j], 0), g.get(i).get(j)));
}
if (!vis[j]) {
build(g, j, vis, lbl, cg);
}
}
}
static boolean scc(List<Map<Integer, Integer>> g, int i, boolean[] vis, List<Integer> comp) {
boolean ans = false;
vis[i] = true;
for (int j : g.get(i).keySet()) {
ans |= g.get(i).get(j) == 1;
if (!vis[j]) {
ans |= scc(g, j, vis, comp);
}
}
comp.add(i);
return ans;
}
static void del_reverse_edge(List<Map<Integer, Integer>> g, int i, boolean[] vis, List<Integer> order, List<Map<Integer, Integer>> ng, List<Set<Integer>> evis) {
vis[i] = true;
for (int j : g.get(i).keySet()) {
if (!evis.get(j).contains(i)) {
ng.get(i).put(j, g.get(i).get(j));
}
if (!vis[j]) {
evis.get(i).add(j);
del_reverse_edge(g, j, vis, order, ng, evis);
}
}
order.add(i);
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["6 7\n1 2 0\n2 3 0\n3 1 0\n3 4 1\n4 5 0\n5 6 0\n6 4 0\n1 6", "5 4\n1 2 0\n2 3 0\n3 4 0\n2 5 1\n1 4", "5 6\n1 2 0\n2 3 0\n3 1 0\n3 4 0\n4 5 1\n5 3 0\n1 2"] | 3 seconds | ["YES", "NO", "YES"] | null | Java 11 | standard input | [
"dsu",
"dfs and similar",
"trees",
"graphs"
] | a65813fabe4110a3ee3d891f09302be1 | The first line contains two integers n and m (1 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of islands and bridges in the game. Each of the next m lines contains the description of the bridge — three integers xi, yi, zi (1 ≤ xi, yi ≤ n, xi ≠ yi, 0 ≤ zi ≤ 1), where xi and yi are the islands connected by the i-th bridge, zi equals to one if that bridge contains an artifact and to zero otherwise. There are no more than one bridge between any pair of islands. It is guaranteed that it's possible to travel between any pair of islands. The last line contains two integers a and b (1 ≤ a, b ≤ n) — the islands where are Johnny and the artifact-dealer respectively. | 2,300 | If Johnny can find some artifact and sell it print the only word "YES" (without quotes). Otherwise print the word "NO" (without quotes). | standard output | |
PASSED | ab1cdbaeebc9fbd3d59158d85b8fd0f6 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main
{
static PrintWriter pw = new PrintWriter(System.out);
static class node
{
String s;
int size;
int rounds;
int[] c1 = new int[26];
int[] c2 = new int[26];
int beauty;
node(String str , int x)
{
s =str;
size = s.length();
rounds = x;
find();
}
void find()
{
for(int i = 0 ; i<size ; i++)
{
char x = s.charAt(i);
if(x >= 'a' && x <= 'z')c1[x - 'a']++;
else c2[x - 'A']++;
}
for(int i = 0 ; i<26 ; i++)
{
beauty = Math.max(beauty , Math.max(c1[i] , c2[i]));
}
}
int get()
{
int x = size - beauty;
if(rounds == 1 && x == 0)return beauty -1;
if(x <= rounds)return size;
else return beauty + rounds;
}
}
static class p implements Comparable<p>
{
String s;
int b;
p(int x , String str ){
s = str; b = x;
}
@Override
public int compareTo(p o) {
return o.b - b;
}
}
public static void main(String[] args)throws Exception
{
Reader.init(System.in);
int r = Reader.nextInt();
int n1 = new node(Reader.next() , r).get();
int n2 = new node(Reader.next() , r).get();
int n3 = new node(Reader.next() , r).get();
ArrayList<p> ar = new ArrayList<>();
ar.add(new p(n1 , "Kuro"));
ar.add(new p(n2 , "Shiro"));
ar.add(new p(n3 , "Katie"));
Collections.sort(ar);
if(ar.get(0).b > ar.get(1).b)pw.println(ar.get(0).s);
else pw.println("Draw");
pw.close();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
public static int pars(String x) {
int num = 0;
int i = 0;
if (x.charAt(0) == '-') {
i = 1;
}
for (; i < x.length(); i++) {
num = num * 10 + (x.charAt(i) - '0');
}
if (x.charAt(0) == '-') {
return -num;
}
return num;
}
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static void init(FileReader input) {
reader = new BufferedReader(input);
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens())
{
String line = reader.readLine();
if(line == null || line.equals(""))throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return pars(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | a0ae36f79527729e7d4fdf3c86dcdf5a | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class Solution
{
public static int freq(String s){
HashMap<Character,Integer>h=new HashMap<>();
int m=1;
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(h.containsKey(ch)){
h.put(ch,h.get(ch)+1);
m=Math.max(m,h.get(ch));
}else{
h.put(ch,1);
}
}
return m;
}
public static int get(int size,int beauty,int rounds)
{
int x = size - beauty;
if(rounds == 1 && x == 0)return beauty -1;
if(x <= rounds)return size;
else return beauty + rounds;
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
StringBuilder out=new StringBuilder();
int n=Integer.parseInt(br.readLine());
String a=br.readLine();
int aa=freq(a);
String b=br.readLine();
int bb=freq(b);
String c=br.readLine();
int cc=freq(c);
aa=get(a.length(),aa,n);
bb=get(b.length(),bb,n);
cc=get(c.length(),cc,n);
int max=Math.max(aa,Math.max(bb,cc));
if(max==aa && max!=bb && max!=cc)
System.out.println("Kuro");
else if(max==bb && max!=aa && max!=cc)
System.out.println("Shiro");
else if(max==cc && max!=aa && max!=bb)
System.out.println("Katie");
else
System.out.println("Draw");
}}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 8008c51c5c13d706ed4823756b62887d | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Vadim
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
B solver = new B();
solver.solve(1, in, out);
out.close();
}
static class B {
int ind(char c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
} else {
return c - 'a' + 26;
}
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.ni();
int[] max = new int[3];
String[] names = new String[]{"Kuro", "Shiro", "Katie"};
int maxmax = -1;
int maxind = -1;
int maxcnt = 0;
for (int i = 0; i < 3; i++) {
String s = in.ns();
int[] cnt = new int[52];
for (int j = 0; j < s.length(); j++) {
int x = ind(s.charAt(j));
cnt[x]++;
max[i] = Math.max(max[i], cnt[x]);
}
if (max[i] == s.length()) {
if (n == 1)
max[i] = s.length() - 1;
else
max[i] = s.length();
} else if (max[i] + n > s.length()) {
max[i] = s.length();
} else
max[i] += n;
if (max[i] > maxmax) {
maxmax = max[i];
maxind = i;
maxcnt = 1;
} else if (max[i] == maxmax) {
maxcnt++;
}
}
if (maxcnt > 1) {
out.println("Draw");
} else
out.println(names[maxind]);
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 79ac49d68c60f1be047fc46af1af8716 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.*;
public class Main {
static ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
public static int size(int from, int exclude) {
int size = 1;
for (Integer v : tree.get(from)) {
if (v != exclude) {
size += size(v, from);
}
}
return size;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// long n = in.nextLong();
// int x = in.nextInt();
// int y = in.nextInt();
// for (int i = 0; i < n+1; ++i) {
// tree.add(new ArrayList<>());
// }
// for (int i = 0; i < n-1; ++i) {
// int a = in.nextInt();
// int b = in.nextInt();
// tree.get(a).add(b);
// tree.get(b).add(a);
// }
// Queue<Integer> queue = new ArrayDeque<>();
// int beforeY = 0;
// int beforeX = 0;
// for (Integer v : tree.get(x)) {
// queue.clear();
// queue.add(v);
// boolean found = false;
//
// while (!queue.isEmpty()) {
// Integer currVertex = queue.poll();
// for (Integer vertex : tree.get(currVertex)) {
// if (vertex == y) {
// found = true;
// beforeY = currVertex;
// break;
// }
// if (vertex != currVertex) {
// queue.add(vertex);
// }
// }
// if (found) {
// break;
// }
// }
//
// if (found) {
// beforeX = v;
// break;
// }
// }
// long sizeX = size(x, beforeX);
// long sizeY = size(y, beforeY);
// System.out.println(n*(n-1) - sizeX*sizeY);
String[] names = {"Kuro", "Shiro", "Katie"};
long n = in.nextLong();
String[] lines = {in.next(), in.next(), in.next()};
int[][] charCount = new int[3][256];
int[] max = new int[3];
for (int s_i = 0; s_i < 3; ++ s_i) {
for (int i = 0; i < lines[s_i].length(); ++i) {
charCount[s_i][lines[s_i].charAt(i)]++;
if (charCount[s_i][lines[s_i].charAt(i)] > max[s_i]) {
max[s_i] = charCount[s_i][lines[s_i].charAt(i)];
}
}
}
int length = lines[0].length();
if (n != 0) {
for (int i = 0; i < 3; ++i) {
if (max[i] == length) {
max[i] -= 2;
}
}
}
int[] max_cp = Arrays.copyOf(max, 3);
Arrays.sort(max_cp);
if (max_cp[1] + n >= length || max_cp[2] == max_cp[1]) {
System.out.println("Draw");
return;
}
for (int i = 0; i < 3; ++i) {
if (max[i] == max_cp[2]) {
System.out.println(names[i]);
return;
}
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | e0b2c3aa576b37346783aee158700dcb | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class B{
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int [] c=new int[125];
String x=sc.next();
int mx1=0;
for(char s : x.toCharArray()) {
c[s]++;
mx1=Math.max(mx1, c[s]);
}
Arrays.fill(c, 0);
String y=sc.next();
int mx2=0;
for(char s : y.toCharArray()) {
c[s]++;
mx2=Math.max(mx2, c[s]);
}
Arrays.fill(c, 0);
String z=sc.next();
int mx3=0;
for(char s : z.toCharArray()) {
c[s]++;
mx3=Math.max(mx3, c[s]);
}
int ans1=Math.min(x.length(), mx1+n);
if(n==1 && mx1==x.length())
ans1--;
int ans2=Math.min(x.length(), mx2+n);
if(n==1 && mx2==x.length())
ans2--;
int ans3=Math.min(x.length(), mx3+n);
if(n==1 && mx3==x.length())
ans3--;
// System.err.println(ans1+" "+ans2+" "+ans3);
if(ans1>ans2 && ans1>ans3)
pw.println("Kuro");
else
if(ans2>ans1 && ans2>ans3)
pw.println("Shiro");
else
if(ans3>ans1 && ans3>ans2)
pw.println("Katie");
else
pw.println("Draw");
pw.flush();
pw.close();
}
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\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 0bdd577bc9817b2dd52ad1cde721f632 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class d{
public static void main(String args[]) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = sc.nextInt();
String[] str = new String[3];
for (int i = 0; i < 3; i++)
str[i] = sc.next();
int[] count = new int[3];
HashMap<Character, Integer> freq = new HashMap<>();
for (int i = 0; i < 3; i++) {
int max = Integer.MIN_VALUE;
for (int j = 0; j < str[i].length(); j++) {
char c = str[i].charAt(j);
freq.put(c, freq.getOrDefault(c, 0) + 1);
max = Math.max(freq.get(c), max);
}
int l = str[i].length();
int x =l-max;
count[i] = x >=n ? max + n : (n==1 ? l-1 : l);
freq.clear();
}
if (count[0] > count[1] && count[0] > count[2])
out.print("Kuro");
else if (count[1] > count[0] && count[1] > count[2])
out.print("Shiro");
else if (count[2] > count[0] && count[2] > count[1])
out.print("Katie");
else
out.print("Draw");
out.close();
}
public static void shuffle(long[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static void shuffle(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static int gcd(int x, int y) {
if (y == 0)
return x;
return gcd(y, x % y);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.valueOf(next());
}
public double nextDouble() {
return Double.valueOf(next());
}
String nextLine() throws IOException {
return reader.readLine();
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | f26d406ebcabd1a43b5a2ccf5f289ca7 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes |
import java.util.Scanner;
public class TreasureHunt {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
String a = s.next();
String b = s.next();
String c = s.next();
int[] arr = new int[58];
int[] brr = new int[58];
int[] crr = new int[58];
int max = -1;
int ans1=0, ans2=0,ans3=0;
for (int i = 0; i < a.length(); i++) {
arr[a.charAt(i) - 'A']++;
if (arr[a.charAt(i) - 'A'] > max) {
max = arr[a.charAt(i) - 'A'];
}
}
if(a.length()-max>=n) {
ans1 = max+n;
}else {
ans1 = a.length();
}
if(max == a.length() && n==1) {
ans1 = max-1;
}
max=-1;
for (int i = 0; i < b.length(); i++) {
brr[b.charAt(i) - 'A']++;
if (brr[b.charAt(i) - 'A'] > max) {
max = brr[b.charAt(i) - 'A'];
}
}
if(b.length()-max>=n) {
ans2 = max+n;
}else {
ans2 = b.length();
}
if(max == b.length() && n==1) {
ans2 = max-1;
}
max=-1;
for (int i = 0; i < c.length(); i++) {
crr[c.charAt(i) - 'A']++;
if (crr[c.charAt(i) - 'A'] > max) {
max = crr[c.charAt(i) - 'A'];
}
}
if(c.length()-max>=n) {
ans3 = max+n;
}else {
ans3 = c.length();
}
if(max == c.length() && n==1) {
ans3 = max-1;
}
// System.out.print(ans1+" "+ans2+" "+ans3);
if(ans1>ans2 && ans1>ans3) {
System.out.println("Kuro");
}else if(ans2>ans1 && ans2>ans3) {
System.out.println("Shiro");
}
else if(ans1<ans3 && ans3>ans2) {
System.out.println("Katie");
}else {
System.out.println("Draw");
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 1d03c8c8192e49f704a0e3c2e62758b5 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces979B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
String kuro = st.nextToken();
st = new StringTokenizer(br.readLine());
String shiro = st.nextToken();
st = new StringTokenizer(br.readLine());
String katie = st.nextToken();
int k = kuro.length();
int[] kuroLetters = new int[256];
int[] shiroLetters = new int[256];
int[] katieLetters = new int[256];
for (int i = 0; i < k; i++) {
int p = (int) (kuro.charAt(i));
kuroLetters[p]++;
}
for (int i = 0; i < k; i++) {
int p = (int) (shiro.charAt(i));
shiroLetters[p]++;
}
for (int i = 0; i < k; i++) {
int p = (int) (katie.charAt(i));
katieLetters[p]++;
}
int kuroMax = 0;
int shiroMax = 0;
int katieMax = 0;
for (int i = 0; i < 256; i++) {
kuroMax = Math.max(kuroMax, kuroLetters[i]);
shiroMax = Math.max(shiroMax, shiroLetters[i]);
katieMax = Math.max(katieMax, katieLetters[i]);
}
if ((kuroMax == k) && (n == 1))
kuroMax = k-1;
else
kuroMax = Math.min(kuroMax+n, k);
if ((shiroMax == k) && (n == 1))
shiroMax = k-1;
else
shiroMax = Math.min(shiroMax+n, k);
if ((katieMax == k) && (n == 1))
katieMax = k-1;
else
katieMax = Math.min(katieMax+n, k);
if ((kuroMax > shiroMax) && (kuroMax > katieMax))
System.out.println("Kuro");
else if ((shiroMax > kuroMax) && (shiroMax > katieMax))
System.out.println("Shiro");
else if ((katieMax > shiroMax) && (kuroMax < katieMax))
System.out.println("Katie");
else
System.out.println("Draw");
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 6ae5b6e88609aa015f14532d6a957c4d | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.*;
public class Treasure{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] ribbons = new String[3];
for(int i = 0; i < 3; i++){
ribbons[i] = sc.next();
}
int[][] charOccurence = new int[3][256];
int[] maxOccurence = new int[3];
int maxOverall = 0;
int maxLocation = 0;
//for all ribbons
for(int i = 0; i < 3; i++){
//figure out max occuring character for current ribbon
for(int j = 0; j < ribbons[0].length(); j++){
charOccurence[i][ribbons[i].charAt(j)]++;
maxOccurence[i] = Math.max(charOccurence[i][ribbons[i].charAt(j)], maxOccurence[i]);
}
//if the max occuring character is occuring for the entire ribbon (the ribbon has only one character)
//and we need to make one move only, then the maximum beauty of this ribbon is the length of the ribbon - 1
if(maxOccurence[i] == ribbons[0].length() && n == 1){
maxOccurence[i]--;
}
//if we need to make more than one move then do math
else{
maxOccurence[i] = Math.min(ribbons[0].length(), maxOccurence[i] + Math.min(ribbons[0].length() - maxOccurence[i], n));
}
if(maxOverall < maxOccurence[i]) {
maxOverall = maxOccurence[i];
maxLocation = i;
}
}
boolean draw = false;
for(int i = 0; i < 3; i++) {
if (maxOccurence[i] == maxOverall && i != maxLocation) {
draw = true;
}
}
if(draw){
System.out.println("Draw");
}
else{
if(maxLocation == 0){
System.out.println("Kuro");
}
else if(maxLocation == 1){
System.out.println("Shiro");
}
else if(maxLocation == 2){
System.out.println("Katie");
}
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 3deaaac96e409c77a893aa9a03edaa4b | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.*;
public class Treasure{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] ribbons = new String[3];
for(int i = 0; i < 3; i++){
ribbons[i] = sc.next();
}
int[][] charOccurence = new int[3][256];
int[] maxOccurence = new int[3];
int maxOverall = 0;
int maxLocation = 0;
//for all ribbons
for(int i = 0; i < 3; i++){
//figure out max occuring character for current ribbon
for(int j = 0; j < ribbons[0].length(); j++){
charOccurence[i][ribbons[i].charAt(j)]++;
maxOccurence[i] = Math.max(charOccurence[i][ribbons[i].charAt(j)], maxOccurence[i]);
}
//if the max occuring character is occuring for the entire ribbon (the ribbon has only one character)
//and we need to make one move only, then the maximum beauty of this ribbon is the length of the ribbon - 1
if(maxOccurence[i] == ribbons[0].length() && n == 1){
maxOccurence[i]--;
}
//if we need to make more than one move then do math
else{
maxOccurence[i] = Math.min(ribbons[0].length(), maxOccurence[i] + n);
}
if(maxOverall < maxOccurence[i]) {
maxOverall = maxOccurence[i];
maxLocation = i;
}
}
boolean draw = false;
for(int i = 0; i < 3; i++) {
if (maxOccurence[i] == maxOverall && i != maxLocation) {
draw = true;
}
}
if(draw){
System.out.println("Draw");
}
else{
if(maxLocation == 0){
System.out.println("Kuro");
}
else if(maxLocation == 1){
System.out.println("Shiro");
}
else if(maxLocation == 2){
System.out.println("Katie");
}
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | bc44a0ba37a1b0bfa2e4c2defec83519 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeMap;
public class B{
public static void main(String[] args) throws Exception{
Parser ps = new Parser(System.in);
int n = ps.nextInt();
String[] ribbons = new String[3];
for(int i = 0; i < 3; i++){
ribbons[i] = ps.next();
}
int[][] charOccurence = new int[3][256];
int[] maxOccurence = new int[3];
int maxOverall = 0;
int maxLocation = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < ribbons[0].length(); j++){
charOccurence[i][ribbons[i].charAt(j)]++;
maxOccurence[i] = Math.max(charOccurence[i][ribbons[i].charAt(j)], maxOccurence[i]);
}
if(maxOccurence[i] == ribbons[0].length() && n == 1){
maxOccurence[i]--;
}
else{
maxOccurence[i] = Math.min(ribbons[0].length(), maxOccurence[i] + Math.min(ribbons[0].length() - maxOccurence[i], n));
}
if(maxOverall < maxOccurence[i]) {
maxOverall = maxOccurence[i];
maxLocation = i;
}
}
boolean draw = false;
for(int i = 0; i < 3; i++) {
if (maxOccurence[i] == maxOverall && i != maxLocation) {
draw = true;
}
}
if(draw){
System.out.println("Draw");
}
else{
if(maxLocation == 0){
System.out.println("Kuro");
}
else if(maxLocation == 1){
System.out.println("Shiro");
}
else if(maxLocation == 2){
System.out.println("Katie");
}
}
}
static class Parser
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Parser(InputStream in)
{
din = new DataInputStream(in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public long nextLong() throws Exception
{
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
//reads in the next string
public String next() throws Exception
{
StringBuilder ret = new StringBuilder();
byte c = read();
while (c <= ' ') c = read();
do
{
ret = ret.append((char)c);
c = read();
} while (c > ' ');
return ret.toString();
}
public int nextInt() throws Exception
{
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = c == '-';
if (neg) c = read();
do
{
ret = ret * 10 + c - '0';
c = read();
} while (c > ' ');
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws Exception
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws Exception
{
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | bbe3bfcb3cd8583570e7b4f56b40eb2e | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class Main extends Thread {
boolean[] prime;
FastScanner sc;
PrintWriter pw;
MathF mf;
final class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
public long nlo() {
return Long.parseLong(next());
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public String nli() {
String line = "";
if (st.hasMoreTokens()) line = st.nextToken();
else try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (st.hasMoreTokens()) line += " " + st.nextToken();
return line;
}
public double nd() {
return Double.parseDouble(next());
}
}
final class MathF {
long grtdiv(long x)
{
if(isPrime(x))
return 1;
else
{
long ans=0;
long y=(long)Math.sqrt(x)+1;
for(;y>=2;y--)
{
if(x%y==0)
ans=Math.max(ans,Math.max(y,x/y));
}
return ans;
}
}
boolean isPrime(long x)
{
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
return false;
}
}
return true;
}
long[][] mul(long[][] arr,long[][] brr,int a,int b,int c,int d)
{
long[][] crr=new long[a][d];
for(int i=0;i<a;i++)
{
for(int j=0;j<d;j++)
{
for(int k=0;k<b;k++)
{
crr[i][j]+=(((arr[i][k]%1000000007)*(brr[k][j]%1000000007))%1000000007);
}
}
}
return crr;
}
int sod(long a)
{
int ans=0;
while(a!=0)
{
ans+=(a%10);
a=a/10;
}
return ans;
}
long pow(long a,long b)
{
if(b==0)
return 1;
else
{
long x=pow(a,b/2);
if(b%2==1)
return (x*x*a);
else
return (x*x);
}
}
public long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
public long exponent(long a,long b)
{
if(b==0)
return 1;
else
{
long x=exponent(a,b/2);
x*=x;
if(b%2==1)
x*=a;
return x;
}
}
public int nod(long x) {
int i = 0;
while (x != 0) {
i++;
x = x / 10;
}
return i;
}
public int nob(long x) {
if(x==0)
return 1;
return (int) Math.floor(Math.log(x) / Math.log(2)) + 1;
}
public int[] FastradixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public void Primesieve(int n) {
prime=new boolean[n];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 3; p * p < n; p+=2) {
if (prime[p] == true) {
for (int i = p * p; i < n; i += p)
prime[i] = false;
}
}
}
}
public Main(ThreadGroup t,Runnable r,String s,long d )
{
super(t,r,s,d);
}
public void run()
{
sc=new FastScanner();
pw=new PrintWriter(System.out);
mf=new MathF();
solve();
pw.flush();
pw.close();
}
public static void main(String[] args)
{
new Main(null,null,"",1<<28).start();
}
/////////////----------------------------------------/////////////
////////////------------------MAIN-LOGIC-------------/////////////
////////////----------Remember dfs reqire ----------/////////////
///////////---------- thread for stack size -------/////////////
////////////--------------------------------------///////////////
ArrayList<Integer>[] adj;
int[] visit;
int[] mrr;
public void solve(){
long t=1;
while(t-->0) {
long n=sc.nlo();
int[] arr,brr,crr;
arr=new int[256];
brr=new int[256];
crr=new int[256];
String str=sc.next();
int l=str.length();
for(int i=0;i<l;i++)
{
arr[str.charAt(i)]++;
}
str=sc.next();
l=str.length();
for(int i=0;i<l;i++)
{
brr[str.charAt(i)]++;
}
str=sc.next();
l=str.length();
for(int i=0;i<l;i++)
{
crr[str.charAt(i)]++;
}
long a=-1,b=-1,c=-1;
for(int i=0;i<256;i++)
{
a=Math.max(a,arr[i]);
b=Math.max(b,brr[i]);
c=Math.max(c,crr[i]);
}
long N,k;
N=n;
if(a<l)
{
k=(Math.min(l-1-a,n));
n-=k;
a+=k;
if(n>0)
a=l;
}
else
{
if(n==1)
a=l-1;
else if(n>1)
a=l;
}
n=N;
if(b<l)
{
k=(Math.min(l-b,n));
n-=k;
b+=k;
if(n>0)
b=l;
}
else
{if(n==1)
b=l-1;
else if(n>1)
b=l;}
n=N;
if(c<l){
k=(Math.min(l-c,n));
n-=k;
c+=k;
if(n>0)
c=l;}
else{
if(n==1)
c=l-1;
else if(n>1)
c=l;}
long max=Math.max(Math.max(a,b),c);
if(a==max&&((b!=max)&&(c!=max)))
pw.println("Kuro");
else if(b==max&&((c!=max)&&(a!=max)))
pw.println("Shiro");
else if(c==max&&((b!=max)&&(a!=max)))
pw.println("Katie");
else
pw.println("Draw");
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 19eab0221a00310f876b104c9a93d119 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.Arrays;
import java.util.Iterator;
import java.util.PrimitiveIterator;
import java.util.Scanner;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Main{
static Scanner s=new Scanner(System.in);
void solve(){
int n=gInt();
int[][]score=new int[3][52];
int[]r= {0,0,0};
for(int v=0;v<3;++v) {
int V=v;
String str=s.next();
str.chars()
.map(i->i<='Z'?i-'A':i-'a'+26)
.forEach(i->++score[V][i]);
r[v]=Arrays.stream(score[V])
.map(i->i==str.length()&&n==1?i-1:Math.min(str.length(),i+n))
.max().getAsInt();
}
if(r[0]>r[1]&&r[0]>r[2])
System.out.println("Kuro");
else if(r[1]>r[0]&&r[1]>r[2])
System.out.println("Shiro");
else if(r[2]>r[0]&&r[2]>r[1])
System.out.println("Katie");
else
System.out.println("Draw");
}
public static void main(String[] A){
new Main().solve();
}
static int gInt(){
return Integer.parseInt(s.next());
}
static long gLong(){
return Long.parseLong(s.next());
}
static double gDouble(){
return Double.parseDouble(s.next());
}
SupplyingIterator<Integer> ints(int n){
return new SupplyingIterator<>(n,Main::gInt);
}
SupplyingIterator<Long> longs(int n){
return new SupplyingIterator<>(n,Main::gLong);
}
SupplyingIterator<Double> doubles(int n){
return new SupplyingIterator<>(n,Main::gDouble);
}
SupplyingIterator<String> strs(int n){
return new SupplyingIterator<>(n,s::next);
}
Range rep(int i){
return Range.rep(i);
}
Range rep(int f,int t,int d){
return Range.rep(f,t,d);
}
Range rep(int f,int t){
return rep(f,t,1);
}
Range rrep(int f,int t){
return rep(t,f,-1);
}
IntStream REP(int v){
return IntStream.range(0,v);
}
IntStream REP(int l,int r){
return IntStream.rangeClosed(l,r);
}
IntStream INTS(int n){
return IntStream.generate(Main::gInt).limit(n);
}
Stream<String> STRS(int n){
return Stream.generate(s::next).limit(n);
}
}
class SupplyingIterator<T> implements Iterable<T>,Iterator<T>{
int t;
Supplier<T> supplier;
SupplyingIterator(int t,Supplier<T> supplier){
this.t=t;
this.supplier=supplier;
}
@Override
public Iterator<T> iterator(){
return this;
}
@Override
public boolean hasNext(){
return t>0;
}
@Override
public T next(){
--t;
return supplier.get();
}
}
class Range implements Iterable<Integer>,PrimitiveIterator.OfInt{
int to,cur,d;
Range(int from,int to,int d){
this.cur=from-d;
this.to=to;
this.d=d;
}
Range(int n){
this(0,n-1,1);
}
@Override
public Iterator<Integer> iterator(){
return this;
}
@Override
public boolean hasNext(){
return cur+d==to||(cur!=to&&(cur<to==cur+d<to));
}
@Override
public int nextInt(){
return cur+=d;
}
static Range rep(int i){
return new Range(i);
}
static Range rep(int f,int t,int d){
return new Range(f,t,d);
}
static Range rep(int f,int t){
return rep(f,t,1);
}
static Range rrep(int f,int t){
return rep(f,t,-1);
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 6761a59df900d5b6a41171ca40a24283 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class Mainn {
InputReader scn;
PrintWriter out;
String INPUT = "";
ArrayList<Integer>[] tree;
void solve() {
int n = scn.nextInt(), size;
char[][] s = { scn.next().toCharArray(), scn.next().toCharArray(), scn.next().toCharArray() };
int[][] arr = new int[3][200];
for (int i = 0; i < 3; i++) {
for (char ch : s[i]) {
arr[i][ch]--;
}
Arrays.sort(arr[i]);
arr[i][0] *= -1;
}
size = s[0].length;
if (n >= size) {
out.println("Draw");
return;
}
int[] cnt = new int[3];
int max = 0;
for (int i = 0; i < 3; i++) {
if (n == 1) {
if (arr[i][0] == size) {
arr[i][0]--;
} else {
arr[i][0]++;
}
cnt[i] = arr[i][0];
} else {
cnt[i] = Math.min(n + arr[i][0], size);
}
max = Math.max(cnt[i], max);
}
int ind = -1;
for (int i = 0, k = 0; i < 3; i++) {
if (cnt[i] == max) {
k++;
ind = i;
}
if (k == 2) {
out.println("Draw");
return;
}
}
String[] str = { "Kuro", "Shiro", "Katie" };
out.println(str[ind]);
}
void run() throws Exception {
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new InputReader(oj);
long time = System.currentTimeMillis();
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) throws Exception {
new Mainn().run();
}
public class InputReader {
InputStream is;
public InputReader(boolean oj) {
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
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++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
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();
}
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);
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
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 * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
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 * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 41bc12cdfe95e7d047065e159a2f7a22 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(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, FastScanner in, PrintWriter out) {
int n = in.nextInt();
String[] given = new String[3];
for (int i = 0; i < 3; i++) {
given[i] = in.nextLine();
}
int l = given[0].length();
if (n >= l) {
out.print("Draw");
return;
}
int[][] mrk = new int[3][100];
for (int i = 0; i < 3; i++) {
Arrays.fill(mrk[i], 0);
for (int j = 0; j < l; j++) {
mrk[i][given[i].charAt(j) - '0']++;
}
}
int[][] left = new int[3][100];
for (int i = 0; i < 3; i++) {
Arrays.fill(left[i], Integer.MAX_VALUE);
for (int j = 0; j < 100; j++) {
int x = l - mrk[i][j];
if (x == 0 && n == 1) {
left[i][j] = 1;
} else if (x >= n) {
left[i][j] = x - n;
} else {
left[i][j] = 0;
}
}
}
Temp[] g = new Temp[3];
for (int i = 0; i < 3; i++) {
int mn = Integer.MAX_VALUE;
for (int j = 0; j < 100; j++) {
mn = Math.min(mn, left[i][j]);
}
g[i] = new Temp(mn, i);
}
Arrays.sort(g, Comparator.comparingInt(z -> z.v));
if (g[0].v == g[1].v) {
out.print("Draw");
return;
}
if (g[0].i == 0) {
out.print("Kuro");
return;
} else if (g[0].i == 1) {
out.print("Shiro");
return;
}
out.print("Katie");
return;
}
private class Temp {
int v;
int i;
public Temp(int v, int i) {
this.v = v;
this.i = i;
}
}
}
static class FastScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
if (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() {
String ret = "";
try {
ret = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 342c2971f3ca20e9cdafa7a07400c85c | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String args[]) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
InputReader in = new InputReader(inputStream);
A solver = new A();
solver.solve(in, out);
out.close();
}
static class A {
StringBuilder a, b, c;
Map<Character, Long> mpa, mpb, mpc;
void solve(InputReader in, PrintWriter out) {
long n = in.nextLong();
a = new StringBuilder(in.next());
b = new StringBuilder(in.next());
c = new StringBuilder(in.next());
mpa = new HashMap<>();
mpb = new HashMap<>();
mpc = new HashMap<>();
for (int i = 0, sz = a.length(); i < sz; i++) {
mpa.computeIfPresent(a.charAt(i), (k, v) -> v + 1);
mpa.putIfAbsent(a.charAt(i), 1L);
}
for (int i = 0, sz = b.length(); i < sz; i++) {
mpb.computeIfPresent(b.charAt(i), (k, v) -> v + 1);
mpb.putIfAbsent(b.charAt(i), 1L);
}
for (int i = 0, sz = c.length(); i < sz; i++) {
mpc.computeIfPresent(c.charAt(i), (k, v) -> v + 1);
mpc.putIfAbsent(c.charAt(i), 1L);
}
long[] ans = new long[3];
ans[0] = beauty(Collections.max(mpa.values()), a.length(), n);
ans[1] = beauty(Collections.max(mpb.values()), b.length(), n);
ans[2] = beauty(Collections.max(mpc.values()), c.length(), n);
if (ans[0] > ans[1] && ans[0] > ans[2]) {
out.print("Kuro");
} else if (ans[1] > ans[0] && ans[1] > ans[2]) {
out.print("Shiro");
} else if (ans[2] > ans[0] && ans[2] > ans[1]) {
out.print("Katie");
} else {
out.print("Draw");
}
}
long beauty(long max, long size, long turns) {
long haveToChange = size - max;
if (turns <= haveToChange) {
return turns + max;
}
if (turns == 1 && max==size) {
return size - 1;
}
return size;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() throws IOException {
if (tokenizer == null)
return reader.readLine();
String line = "";
if (tokenizer.hasMoreTokens())
line = tokenizer.nextToken("");
tokenizer = null;
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 269930fb31d3d011ff438a2170c45f7e | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes |
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Try
{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static long mod=1000000007;
static BigInteger bigInteger = new BigInteger("1000000007");
static int n = (int)1e6;
static boolean[] prime;
static ArrayList<Integer> as;
static void sieve() {
Arrays.fill(prime , true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= n ; ++i) {
if(prime[i]) {
for(int k = i * i; k< n ; k+=i) {
prime[k] = false;
}
}
}
}
static PrintWriter w = new PrintWriter(System.out);
public static void main(String[] args)
{
InputReader sc = new InputReader(System.in);
//PrintWriter w = new PrintWriter(System.out);
/*
prime = new boolean[n + 1];
sieve();
prime[1] = false;
*/
/*
as = new ArrayList<>();
for(int i=2;i<=1000000;i++)
{
if(prime[i])
as.add(i);
}
*/
/*
long a = sc.nl();
BigInteger ans = new BigInteger("1");
for (long i = 1; i < Math.sqrt(a); i++) {
if (a % i == 0) {
if (a / i == i) {
ans = ans.multiply(BigInteger.valueOf(phi(i)));
} else {
ans = ans.multiply(BigInteger.valueOf(phi(i)));
ans = ans.multiply(BigInteger.valueOf(phi(a / i)));
}
}
}
w.println(ans.mod(bigInteger));
*/
// MergeSort ob = new MergeSort();
// ob.sort(arr, 0, arr.length-1);
int []ku = new int[58];
int []sh = new int[58];
int []ka = new int[58];
int m = sc.ni();
String k = sc.rs();
String s = sc.rs();
String kat = sc.rs();
for(int i=0;i<k.length();i++)
{
ku[(int)k.charAt(i)-65]++;
}
for(int i=0;i<s.length();i++)
{
sh[(int)s.charAt(i)-65]++;
}
for(int i=0;i<kat.length();i++)
{
ka[(int)kat.charAt(i)-65]++;
}
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;
int s1 = k.length();
int s2 = s.length();
int s3 = kat.length();
for(int i=0;i<58;i++)
{
if(temp1<ku[i])
temp1 = ku[i];
if(temp2<sh[i])
temp2 = sh[i];
if(temp3<ka[i])
temp3 = ka[i];
}
if(temp1 == s1 && m==1)
s1--;
if(temp2==s2 && m==1)
s2--;
if(temp3==s3 && m==1)
s3--;
temp1 = Math.min(temp1+m,s1);
temp2 = Math.min(temp2+m,s2);
temp3 = Math.min(temp3+m,s3);
if(temp1 > temp2 && temp1 > temp3)
w.println("Kuro");
else if(temp2 > temp3 && temp2 > temp1)
w.println("Shiro");
else if(temp3 > temp1 && temp3 > temp2)
w.println("Katie");
else
w.println("Draw");
w.close();
}
public static long modMultiply(long one, long two) {
return (one % mod * two % mod) % mod;
}
static long fx(int m)
{
long re = 0;
for(int i=1;i<=m;i++)
{
re += (long) (i / gcd(i,m));
}
return re;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static long phi(long nx)
{
// Initialize result as n
double result = nx;
// Consider all prime factors of n and for
// every prime factor p, multiply result
// with (1 - 1/p)
for (int p = 0; as.get(p) * as.get(p) <= nx; ++p)
{
// Check if p is a prime factor.
if (nx % as.get(p) == 0)
{
// If yes, then update n and result
while (nx % as.get(p) == 0)
nx /= as.get(p);
result *= (1.0 - (1.0 / (double) as.get(p)));
}
}
// If n has a prime factor greater than sqrt(n)
// (There can be at-most one such prime factor)
if (nx > 1)
result *= (1.0 - (1.0 / (double) nx));
return (long)result;
//return(phi((long)result,k-1));
}
public static int primeFactors(int n)
{
int sum = 0;
// Print the number of 2s that divide n
while (n%2==0)
{
sum = 1;
//System.out.print(2 + " ");
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
// System.out.print(i + " ");
n /= i;
}
sum++;
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
sum++;
return sum;
}
static int digitsum(int x)
{
int sum = 0;
while(x > 0)
{
int temp = x % 10;
sum += temp;
x /= 10;
}
return sum;
}
static int countDivisors(int n)
{
int cnt = 0;
for (int i = 1; i*i <=n; i++)
{
if (n % i == 0 && i<=1000000)
{
// If divisors are equal,
// count only one
if (n / i == i)
cnt++;
else // Otherwise count both
cnt = cnt + 2;
}
}
return cnt;
}
static boolean isprime(int n)
{
if(n == 2)
return true;
if(n == 3)
return true;
if(n % 2 == 0)
return false;
if(n % 3 == 0)
return false;
int i = 5;
int w = 2;
while(i * i <= n)
{
if(n % i == 0)
return false;
i += w;
w = 6 - w;
}
return true;
}
static long log2(long value) {
return Long.SIZE-Long.numberOfLeadingZeros(value);
}
static boolean binarysearch(int []arr,int p,int n)
{
//ArrayList<Integer> as = new ArrayList<>();
//as.addAll(0,at);
//Collections.sort(as);
boolean re = false;
int st = 0;
int end = n-1;
while(st <= end)
{
int mid = st + (end-st)/2;
if(p > as.get(mid))
{
st = mid+1;
}
else if(p < as.get(mid))
{
end = mid-1;
}
else if(p == as.get(mid))
{
re = true;
break;
}
}
return re;
}
static class Student
{
int position;
int value;
Student(int position,int value)
{
this.position = position;
this.value = value;
}
}
/* Java program for Merge Sort */
static 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 */
}
public static int ip(String s){
return Integer.parseInt(s);
}
public static String ips(int s){
return Integer.toString(s);
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 08f8628db1e2e4ecbd6fc0ed2d495b75 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int turns = in.nextInt();
String[] players = new String[3];
for (int i = 0; i < 3; i++) players[i] = in.next();
int n = players[0].length();
int[] c = new int[3];
Arrays.fill(c, 0);
for (int i = 0; i < 3; i++) {
char[] s = players[i].toCharArray();
HashMap<Character, Integer> hash = new HashMap<>();
for (int j = 0; j < n; j++) {
if (!hash.containsKey(s[j])) hash.put(s[j], 0);
hash.replace(s[j], hash.get(s[j]) + 1);
}
for (int count : hash.values()) {
c[i] = Math.max(c[i], count);
}
}
int max = 0;
for (int i = 0; i < 3; i++) {
int colorsLeft = n - c[i];
int turnsLeft = turns;
if (colorsLeft <= turnsLeft) {
c[i] += colorsLeft;
if (colorsLeft == 0 && turnsLeft == 1) c[i]--;
} else {
c[i] += turnsLeft;
}
max = Math.max(max, c[i]);
}
if ((c[0] == max && c[1] == max) || (c[0] == max && c[2] == max) || (c[1] == max && c[2] == max)) {
out.println("Draw");
} else if (c[0] > c[1] && c[0] > c[2]) {
out.println("Kuro");
} else if (c[1] > c[0] && c[1] > c[2]) {
out.println("Shiro");
} else if (c[2] > c[0] && c[2] > c[1]) {
out.println("Katie");
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 9bfebd375523acb6aec0bcc95204cfa7 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.io.InputStream;
public class Main4 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
XeniaAndBitOperations solver = new XeniaAndBitOperations();
solver.solve(1, in, out);
out.close();
}
static class XeniaAndBitOperations {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long n = in.nextLong();
String kuro = in.next();
int lenkuro = kuro.length();
HashMap<Integer, Integer> kuromap = intialize();
String shiro = in.next();
HashMap<Integer, Integer> shiromap = intialize();
int lenshiro = shiro.length();
String katie = in.next();
HashMap<Integer, Integer> katiemap = intialize();
int lenkatie = katie.length();
if (n > 100000)
out.print("Draw");
else {
// max repeating count character for each
for (int i = 0; i < lenkuro; i++) {
int ch = kuro.charAt(i);
kuromap.put(ch, kuromap.get(ch) + 1);
}
for (int i = 0; i < lenshiro; i++) {
int ch = shiro.charAt(i);
shiromap.put(ch, shiromap.get(ch) + 1);
}
for (int i = 0; i < lenkatie; i++) {
int ch = katie.charAt(i);
katiemap.put(ch, katiemap.get(ch) + 1);
}
int maxkuro = 0;
for (Map.Entry<Integer, Integer> entry : kuromap.entrySet()) {
if (entry.getValue() > maxkuro)
maxkuro = entry.getValue();
}
int maxshiro = 0;
for (Map.Entry<Integer, Integer> entry : shiromap.entrySet()) {
if (entry.getValue() > maxshiro)
maxshiro = entry.getValue();
}
int maxkatie = 0;
for (Map.Entry<Integer, Integer> entry : katiemap.entrySet()) {
if (entry.getValue() > maxkatie)
maxkatie = entry.getValue();
}
if (n == 1) {
if (lenkuro == maxkuro)
maxkuro--;
else if (lenkuro > maxkuro)
maxkuro++;
if (lenkuro == maxshiro)
maxshiro--;
else if (lenkuro > maxshiro)
maxshiro++;
if (lenkuro == maxkatie)
maxkatie--;
else if (lenkuro > maxkatie)
maxkatie++;
} else {
if (lenkuro - maxkuro >= n)
maxkuro += n;
else {
maxkuro = lenkuro;
}
if (lenkuro - maxshiro >= n)
maxshiro += n;
else {
maxshiro = lenkuro;
}
if (lenkuro - maxkatie >= n)
maxkatie += n;
else {
maxkatie = lenkuro;
}
}
int max = Math.max(Math.max(maxkuro, maxkatie), maxshiro);
int count = 0;
if (max == maxkuro)
count++;
if (max == maxshiro)
count++;
if (max == maxkatie)
count++;
if (count > 1)
out.print("Draw");
else {
if (max == maxkuro)
out.println("Kuro");
if (max == maxshiro)
out.println("Shiro");
if (max == maxkatie)
out.println("Katie");
}
}
}
private HashMap<Integer, Integer> intialize() {
HashMap<Integer, Integer> map = new HashMap<>();
int ch = 'a';
int ch1 = 'A';
for (int i = 0; i < 26; i++) {
map.put(ch, 0);
ch++;
}
for (int i = 0; i < 26; i++) {
map.put(ch1, 0);
ch1++;
}
return map;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 1c045a0d29bae425c831ef0a5fcb097d | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) throws IOException{
//InputStream ins = new FileInputStream("E:\\rush.txt");
InputStream ins = System.in;
in = new InputReader(ins);
out = new PrintWriter(System.out);
//code start from here
new Task().solve(in, out);
out.close();
}
static int N = 50000;
static class Task{
int n;
String s[] = new String[3];
int ma[] = new int[3];
int cnt[][] = new int[3][500];
int len;
TreeMap dic = new TreeMap();
public void solve(InputReader in,PrintWriter out) {
n = in.nextInt();
for (int i = 0;i < 3;i++) s[i] = in.next();
for (int i = 0;i < 3;i++) {
for (int j = 0;j < (int)s[i].length();j++) {
cnt[i][(int)s[i].charAt(j)]++;
}
for (int j = 'a';j <= 'z';j++)
ma[i] = Math.max(ma[i], cnt[i][j]);
for (int j = 'A';j <='Z';j++)
ma[i] = Math.max(ma[i], cnt[i][j]);
if (ma[i]==(int)s[i].length()) {
if (n==1) {
ma[i]--;
}
}else {
ma[i] = Math.min(ma[i]+n, s[i].length());
}
}
String s[] = {"Kuro","Shiro","Katie"};
if(ma[0]>ma[1]) {
int x = ma[0];ma[0] = ma[1];ma[1] = x;
String t = s[0];s[0] = s[1];s[1] = t;
}
if(ma[1]>ma[2]) {
int x = ma[1];ma[1] = ma[2];ma[2] = x;
String t = s[1];s[1] = s[2];s[2] = t;
}
if(ma[0]>ma[1]) {
int x = ma[0];ma[0] = ma[1];ma[1] = x;
String t = s[0];s[0] = s[1];s[1] = t;
}
if (ma[1]==ma[2]) {
out.println("Draw");
}else {
out.println(s[2]);
}
}
}
static class InputReader{
public BufferedReader br;
public StringTokenizer tokenizer;
public InputReader(InputStream ins) {
br = new BufferedReader(new InputStreamReader(ins));
tokenizer = null;
}
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());
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 51ff6b5ddda75f8b3936993eb271ab5d | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String Kuro = in.next();
String Shiro = in.next();
String Katie = in.next();
int[] KuroCnt = new int[256];
int[] ShiroCnt = new int[256];
int[] KatieCnt = new int[256];
for (int i = 0; i < Kuro.length(); i++) {
KuroCnt[Kuro.charAt(i)]++;
ShiroCnt[Shiro.charAt(i)]++;
KatieCnt[Katie.charAt(i)]++;
}
int KuroMax = 0;
int ShiroMax = 0;
int KatieMax = 0;
for (int i = 0; i < 256; i++) {
KuroMax = Math.max(KuroMax, KuroCnt[i]);
ShiroMax = Math.max(ShiroMax, ShiroCnt[i]);
KatieMax = Math.max(KatieMax, KatieCnt[i]);
}
int KuroScore = Math.min(Kuro.length(), n + KuroMax);
if (n == 1 && KuroMax == Kuro.length()) {
KuroScore = Kuro.length() - 1;
}
int ShiroScore = Math.min(Shiro.length(), n + ShiroMax);
if (n == 1 && ShiroMax == Shiro.length()) {
ShiroScore = Shiro.length() - 1;
}
int KatieScore = Math.min(Katie.length(), n + KatieMax);
if (n == 1 && KatieMax == Katie.length()) {
KatieScore = Katie.length() - 1;
}
int MaxScore = -1;
int MaxQty = 0;
String ans = "";
if (KuroScore > MaxScore) {
MaxScore = KuroScore;
ans = "Kuro";
MaxQty = 1;
} else if (KuroScore == MaxScore) {
MaxQty++;
}
if (ShiroScore > MaxScore) {
MaxScore = ShiroScore;
ans = "Shiro";
MaxQty = 1;
} else if (ShiroScore == MaxScore) {
MaxQty++;
}
if (KatieScore > MaxScore) {
MaxScore = KatieScore;
ans = "Katie";
MaxQty = 1;
} else if (KatieScore == MaxScore) {
MaxQty++;
}
if (MaxQty == 1) {
out.println(ans);
} else {
out.println("Draw");
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | bad5439ed2e6960d819321670d1ce118 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.*;
public class Solution {
static class Score implements Comparable<Score> {
public String name;
public int score;
public Score(String name, int score) {
this.name = name;
this.score = score;
}
@Override
public int compareTo(Score arg0) {
return arg0.score - this.score;
}
};
private static int solve(int n, String s) {
Integer[] c = new Integer[52];
Arrays.fill(c, 0);
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (Character.isLowerCase(ch))
++c[ch - 'a'];
else
++c[ch - 'A' + 26];
}
if (n == 1) {
Arrays.sort(c, Collections.<Integer>reverseOrder());
return c[0] + (c[1] == 0 ? -1 : 1);
} else {
int maxc = 0;
for (int item : c)
maxc = Math.max(maxc, item);
return maxc + Math.min(n, s.length() - maxc);
}
}
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
int n = input.nextInt();
Score[] result = new Score[3];
result[0] = new Score("Kuro", 0);
result[1] = new Score("Shiro", 0);
result[2] = new Score("Katie", 0);
for (int i = 0; i < 3; ++i) {
String s = input.next();
result[i].score = solve(n, s);
}
Arrays.sort(result);
if (result[0].score == result[1].score)
System.out.println("Draw");
else
System.out.println(result[0].name);
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 5119fa92dfc686d6ee286e21001b555c | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(in.readLine());
String kuro = in.readLine();
String shiro = in.readLine();
String katie = in.readLine();
int maxb = Math.max(
maxBeauty(kuro, N),
Math.max(maxBeauty(shiro, N),
maxBeauty(katie, N)));
int count = 0;
String ans = "";
if (maxb == maxBeauty(kuro, N)) {
++count;
ans = "Kuro";
}
if (maxb == maxBeauty(shiro, N)) {
++count;
ans = "Shiro";
}
if (maxb == maxBeauty(katie, N)) {
++count;
ans = "Katie";
}
if (count >= 2) {
ans = "Draw";
}
out.write(ans + "\n");
in.close();
out.close();
}
private static int maxBeauty(String s, int N) {
int[] count = new int[300];
int total = s.length();
for (int i=0; i<total; ++i) {
char ch = s.charAt(i);
count[ch]++;
}
int maxCount = 0;
for (int i=0; i<count.length; ++i) {
if (count[i] > maxCount) {
maxCount = count[i];
}
}
if (N==1 && maxCount==total) {
return maxCount-1;
}
return Math.min(maxCount + N, total);
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | c28671a5bf04b2b4107ba124f2fa95e4 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author gaidash
*/
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 {
private int nMoves;
private int getMax(char[] a) {
int MAX = 122;
int length = a.length;
int[] count = new int[MAX + 1];
for (char c : a) count[c]++;
int max = 0;
for (int num : count) {
if (num == 0) continue;
if (num + nMoves <= length) {
max = Math.max(max, num + nMoves);
} else {
int score = length;
if (nMoves == 1 && num == length) score--;
max = Math.max(max, score);
}
}
return max;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
nMoves = in.nextInt();
char[] kuro = in.nextString().toCharArray();
char[] shiro = in.nextString().toCharArray();
char[] katie = in.nextString().toCharArray();
int maxKuro = getMax(kuro);
int maxShiro = getMax(shiro);
int maxKatie = getMax(katie);
int max = Math.max(Math.max(maxKuro, maxShiro), maxKatie);
int maxCount = (maxKuro == max ? 1 : 0) + (maxShiro == max ? 1 : 0) + (maxKatie == max ? 1 : 0);
if (maxCount > 1) {
out.print("Draw");
} else if (max == maxKuro) {
out.print("Kuro");
} else if (max == maxShiro) {
out.print("Shiro");
} else {
out.print("Katie");
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 44f00580bcb9681b0157a51a8152a014 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | //package com.company;
import java.io.*;
//import java.nio.file.Paths;
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] args)throws Exception {
Scanner s = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
long n=s.nextLong();
char[] a=s.next().toCharArray();
char[] b=s.next().toCharArray();long ma=Long.MIN_VALUE;long mb=Long.MIN_VALUE;long mc=Long.MIN_VALUE;
char[] c=s.next().toCharArray();int[] ca=new int[123];int[] cb=new int[123];int[] cc=new int[123];
for(int i=0;i<a.length;i++){
ca[a[i]]++;cb[b[i]]++;cc[c[i]]++;
ma=Math.max(ma,ca[a[i]]);
mb=Math.max(mb,cb[b[i]]);
mc=Math.max(mc,cc[c[i]]);
}
if(ma==a.length){
if(n==1){
ma-=1;
}
}else ma=Math.min(ma+n,a.length);
if(mb==a.length){
if(n==1){
mb-=1;
}
}else mb=Math.min(mb+n,a.length);
if(mc==a.length){
if(n==1){
mc-=1;
}
}else mc=Math.min(mc+n,a.length);
int c1=0;
/* if(n+ma>=a.length) c1++;
if(n+mb>=b.length) c1++;
if(n+mc>=c.length) c1++;
*/ // System.out.println(ma+" "+mb+" "+mc);
long m=Math.max(ma,Math.max(mb,mc));int j=0;
if(m==ma) j++;if(m==mb) j++;if(m==mc) j++;
if(j>1){
System.out.println("Draw");
}else if(ma>mb&&ma>mc)
System.out.println("Kuro");
else if(mb>ma&&mb>mc)
System.out.println("Shiro");
else
System.out.println("Katie");
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 057962fab33cc3cacbabb1a4077c63b6 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Created by hapsi on 11.10.2016.
*/
public class Main {
private static class FastScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner(InputStream inputStream){
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()){
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException ignored){}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static int binarySearch(int []a, int l, int r, int x) {
// To boxed array
Integer[] what = Arrays.stream( a ).boxed().toArray( Integer[]::new );
//Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );
return binarySearch(what, l ,r, x);
}
private static int binarySearch(Integer []a, int l, int r, int x){
if (l >= r) return -(l+1);
int m = (l + r) / 2;
if (a[m] > x || (a[m] == x && m > 0 && a[m-1] == x))
return binarySearch(a, l, m, x);
else if (a[m] < x)
return binarySearch(a, m + 1, r, x);
return m;
}
private static int nextSearch2(long []a, int l, int r, long x){
if (l >= r) {
if (a.length == 1 && a[0] <= x) {
return 0;
}
else if (l - 1 >= 0 && a[l-1] <= x) {
return l - 1;
}
else if (l < a.length && a[l] <= x){
return l;
}
else if(l + 1 < a.length && a[l+1] <= x) {
return l+1;
}
else if (l >= a.length && a[a.length - 1] <= x) {
return a.length - 1;
}
return -1;
}
int m = (l + r) / 2;
if (a[m] > x)
return nextSearch2(a, l, m, x);
else if (a[m] < x)
return nextSearch2(a, m + 1, r, x);
return m;
}
private static int nextSearch(int []a, int l, int r, int x){
if (l >= r) return l;
int m = (l + r) / 2;
if (a[m] > x)
return nextSearch(a, l, m, x);
else if (a[m] < x || (m < a.length - 1 && a[m+1] == x))
return nextSearch(a, m + 1, r, x);
return m + 1;
}
private static int nextSearch(LinkedList<Integer>a, int l, int r, int x){
if (l >= r) return l;
int m = (l + r) / 2;
if (a.get(m) > x)
return nextSearch(a, l, m, x);
else if (a.get(m) < x || (m < a.size() - 1 && a.get(m+1) == x))
return nextSearch(a, m + 1, r, x);
return m + 1;
}
private static int nearestSearch(int []a, int l, int r, int x) {
if (l >= r) {
if (a.length == 1) {
return 0;
}
else if (l >= a.length) {
return a.length - 1;
}
else if (l-1 >= 0) {
int d1 = Math.abs(a[l-1] - x);
int d2 = Math.abs(a[l] - x);
if (d1 <= d2) {
return l-1;
}
return l;
}
else {
return l;
}
}
int m = (l + r) / 2;
if (a[m] > x || (a[m] == x && m > 0 && a[m-1] == x)) {
return nearestSearch(a, l, m, x);
}
else if (a[m] < x) {
return nearestSearch(a, m + 1, r, x);
}
return m;
}
private static int compareStringNumbers(String a, String b){
if(a.length() > b.length()){
return 1;
}
else if(a.length() < b.length()){
return -1;
}
for(int i=0;i<a.length();i++){
if(a.charAt(i) > b.charAt(i)){
return 1;
}
else if(a.charAt(i) < b.charAt(i)){
return -1;
}
}
return 0;
}
private static int gcd (int a, int b) {
if (b == 0) return a;
return gcd (b, a % b);
}
private static List<Integer> dfs(ArrayList<ArrayList<Integer>>a, boolean used[], int v) {
used[v] = true;
List<Integer>path = null;
for (int i = 0; i < a.get(v).size(); i++) {
if(!used[a.get(v).get(i)]) {
if (path == null)
path = dfs(a, used, a.get(v).get(i));
else
path.addAll(dfs(a, used, a.get(v).get(i)));
}
}
if (path == null) path = new ArrayList<>(1);
path.add(0, v);
return path;
}
private static boolean next(int[]a){
for(int i = a.length-1;i>0;i--){
for(int j=i-1;j>=0;j--) {
if (a[i] > a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
Arrays.sort(a, j + 1, a.length);
return true;
}
}
}
return false;
}
private static class LolStack implements Cloneable {
private Long a[];
private int index = -1;
private long sum = 0;
public LolStack(){
a = new Long[100];
}
public void push(long x) {
if (a.length <= index + 1) {
a = Arrays.copyOf(a, a.length + 20);
}
a[++index] = x;
sum+=x;
}
public long pop() {
sum-=a[index];
return a[index--];
}
public boolean isEmpty(){
return index < 0;
}
public long getSum() {
return sum;
}
@Override
protected Object clone() throws CloneNotSupportedException {
LolStack t = (LolStack) super.clone();
t.a = Arrays.copyOf(a, a.length);
t.sum = sum;
t.index = index;
return t;
}
}
private static class LolQueue {
int a[];
int m[];
int maxSize;
int top = -1;
int lower = 0;
boolean computed = false;
public LolQueue(int maxSize){
this.maxSize = maxSize;
a = new int[maxSize];
m = new int[maxSize];
}
public void push(int x){
a[++top] = x;
m[top] = x;
computed = false;
}
public int pop() {
return a[lower++];
}
public int min() {
if (!computed) {
for (int i = top - 1; i >= lower; i--) {
if (m[i + 1] < m[i]) {
m[i] = m[i + 1];
}
}
computed = true;
}
return m[lower];
}
}
@SuppressWarnings("unchecked")
public static void main(String args[]) throws Exception {
FastScanner scanner = new FastScanner(System.in);
PrintWriter printer = new PrintWriter(System.out);
//scanner = new FastScanner(new FileInputStream("input.txt"));
//printer = new PrintWriter(new FileOutputStream("output.txt"));
/*
int n = scanner.nextInt(), x = scanner.nextInt() - 1, y = scanner.nextInt() - 1;
ArrayList<ArrayList<Integer>>g = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
g.add(new ArrayList<>());
}
for (int i = 0; i < n-1; i++) {
int a = scanner.nextInt() - 1, b = scanner.nextInt() - 1;
g.get(a).add(b);
g.get(b).add(a);
}
printer.println(g);
for (int i = 0; i < n; i++) {
ArrayList<Integer>path = (ArrayList<Integer>) dfs(g, new boolean[g.size()], i);
for (int j = path.size() - 2; j >= 0; j--) {
if(!g.get(path.get(j)).contains(path.get(j+1))){
path.add(j+1,path.get(j-1));
}
}
printer.println(i + " " + path);
}
*/
int n = scanner.nextInt();
Map<Character, Integer>c1 = new HashMap<>();
Map<Character, Integer>c2 = new HashMap<>();
Map<Character, Integer>c3 = new HashMap<>();
String s1 = scanner.next();
String s2 = scanner.next();
String s3 = scanner.next();
for (int i = 0; i < s1.length(); i++) {
c1.put(s1.charAt(i), c1.getOrDefault(s1.charAt(i), 0) + 1);
c2.put(s2.charAt(i), c2.getOrDefault(s2.charAt(i), 0) + 1);
c3.put(s3.charAt(i), c3.getOrDefault(s3.charAt(i), 0) + 1);
}
int max1 = f(c1, n, s1.length());
int max2 = f(c2, n, s2.length());
int max3 = f(c3, n, s3.length());
//printer.println(c1 + " " + max1);
//printer.println(c2 + " " + max2);
//printer.println(c3 + " " + max3);
if (max1 > max2 && max1 > max3){
printer.println("Kuro");
}
else if(max2 > max1 && max2 > max3){
printer.println("Shiro");
}
else if(max3 > max1 && max3 > max2) {
printer.println("Katie");
}
else{
printer.println("Draw");
}
printer.close();
}
private static int f(Map<Character, Integer>c1, int n, int sLength){
int max1 = Integer.MIN_VALUE;
for (Map.Entry<Character, Integer>c: c1.entrySet()) {
int k = c.getValue();
if (k + n > sLength) {
if (k == sLength) {
if (n % 2 == 0) {
max1 = sLength;
} else {
if (n >= sLength) {
max1 = sLength;
}
else {
if (n == 1) {
max1 = Math.max(max1, sLength - 1);
}
else {
max1 = sLength;
}
}
}
}
else {
max1 = sLength;
}
}
else {
max1 = Math.max(max1, k + n);
}
if(max1 == sLength){
break;
}
}
return max1;
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 4187ca5e42fd4afdb95d55b1f9e2f16a | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import java.util.*;
public class B979 {
static int find(int c1,int size,int n)
{
if(c1==size && n==1)
{
return c1-1;
}
else
return Math.min(size,c1+n);
}
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int small[][]=new int[3][26];
int big[][]=new int[3][26];
String s1=sc.next();
String s2=sc.next();
String s3=sc.next();
build(s1,small[0],big[0]);
build(s2,small[1],big[1]);
build(s3,small[2],big[2]);
int size=s1.length();
int x1=0,x2=0,x3=0;
for(int i=0;i<26;i++)
{
int c1=small[0][i],c2=big[0][i];
int c3=small[1][i],c4=big[1][i];
int c5=small[2][i],c6=big[2][i];
x1=Math.max(x1,find(c1,size,n));
x1=Math.max(x1,find(c2,size,n));
x2=Math.max(x2,find(c3,size,n));
x2=Math.max(x2,find(c4,size,n));
x3=Math.max(x3,find(c5,size,n));
x3=Math.max(x3,find(c6,size,n));
}
if(x1>x2 && x1>x3)
System.out.println("Kuro");
else if(x2>x1 && x2>x3)
System.out.println("Shiro");
else if(x3>x1 && x3>x2)
System.out.println("Katie");
else
System.out.println("Draw");
}
static int getmax(int a[],int b[])
{
int m=0;
for(int i=0;i<26;i++)
{
m=Math.max(m,Math.max(a[i],b[i]));
}
return m;
}
static void build(String s,int a[],int b[])
{
for(int i=0;i<s.length();i++)
{
int x=s.charAt(i);
if(x>=97)
a[x-97]++;
else
b[x-65]++;
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.