exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | f895d7c269a08f5944740fcd47b47aa3 | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.text.DecimalFormat;
import java.util.stream.LongStream;
import java.util.stream.IntStream;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0){
Naveen problem = new Naveen(sc);
problem.solve(out);
}
out.flush();
}
}
class Naveen {
int n;
int[] arr;
Naveen(FastScanner sc) {
n = sc.nextInt();
arr = sc.arrayInt(n);
}
void solve(PrintWriter out) {
int max =0;
for(int i =0;i<n;i++){
max = Math.max(max, arr[i]);
}
char ch ='b';
String s= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
out.println(s);
String s2="";
for(int i =1;i<=n;i++){
s2 =s.substring(0,arr[i-1]);
for(int j =arr[i-1];j<=max;j++){
s2 = s2+ch;
}
out.println(s2);
if(ch == 'z')
ch = 'a';
ch++;
s = s2;
}
}}
class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) {
return buffer[ptr++];
} else {
return -1;
}
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
public boolean hasNext() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
ptr++;
}
return hasNextByte();
}
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext()) {
throw new NoSuchElementException();
}
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) {
throw new NumberFormatException();
}
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] arrayInt(int N) {
int[] array = new int[N];
for (int i = 0; i < N; i++) {
array[i] = nextInt();
}
return array;
}
public long[] arrayLong(int N) {
long[] array = new long[N];
for (int i = 0; i < N; i++) {
array[i] = nextLong();
}
return array;
}
public double[] arrayDouble(int N) {
double[] array = new double[N];
for (int i = 0; i < N; i++) {
array[i] = nextDouble();
}
return array;
}
public String[] arrayString(int N) {
String[] array = new String[N];
for (int i = 0; i < N; i++) {
array[i] = next();
}
return array;
}
public int randomInt() {
Random r = new Random();
int value = r.nextInt((int) 1e6);
System.out.println(value);
return value;
}
public int[] randomInt(int N) {
int[] array = new int[N];
Random r = new Random();
for (int i = 0; i < N; i++) {
array[i] = r.nextInt((int) 1e6);
}
System.out.println(Arrays.toString(array));
return array;
}
}
class My {
public static long lower(long arr[],long key){
int low = 0;
int high = arr.length-1;
while(low < high){
int mid = low + (high - low)/2;
if(arr[mid] >= key){
high = mid;
}
else{
low = mid+1;
}
}
return low;
}
public static int upper(int arr[],int key){
int low = 0;
int high = arr.length-1;
while(low < high){
int mid = low + (high - low+1)/2;
if(arr[mid] <= key){
low = mid;
}
else{
high = mid-1;
}
}
return low;
}
static void ans(boolean b) {
System.out.println(b ? "Yes" : "No");
}
static void ANS(boolean b) {
System.out.println(b ? "YES" : "NO");
}
static String sort(String s) {
char[] ch = s.toCharArray();
Arrays.sort(ch);
return String.valueOf(ch);
}
static String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
static int[] reverse(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
static long[] reverse(long[] array) {
for (int i = 0; i < array.length / 2; i++) {
long temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
static double[] reverse(double[] array) {
for (int i = 0; i < array.length / 2; i++) {
double temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
static String[] reverse(String[] array) {
for (int i = 0; i < array.length / 2; i++) {
String temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
static char[] reverse(char[] array) {
for (int i = 0; i < array.length / 2; i++) {
char temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
return array;
}
static long min(long... numbers) {
Arrays.sort(numbers);
return numbers[0];
}
static int min(int... numbers) {
Arrays.sort(numbers);
return numbers[0];
}
static double min(double... numbers) {
Arrays.sort(numbers);
return numbers[0];
}
static long max(long... numbers) {
Arrays.sort(numbers);
return numbers[numbers.length - 1];
}
static int max(int... numbers) {
Arrays.sort(numbers);
return numbers[numbers.length - 1];
}
static double max(double... numbers) {
Arrays.sort(numbers);
return numbers[numbers.length - 1];
}
static int sum(long number) {
int sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | 10b6570352344630b9cb5b899eebb575 | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int a[] = new int[n];
char c[] = new char[200];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
String s = "";
for (int i = 0; i < 200; i++) {
c[i] = 'a';
}
for (char x : c)
pw.print(x);
pw.println();
boolean f = true;
for (int i = 0; i < n - 1; i++) {
if (f)
c[a[i]] = c[a[i]]=='a'?'b':'a' ;
else
c[a[i]] = c[a[i]]=='a'?'b':'a' ;
for (char x : c)
pw.print(x);
pw.println();
f = !f;
}
c[a[n-1]] = c[a[n-1]]=='a'?'b':'a' ;
for (char x : c)
pw.print(x);
pw.println();
}
pw.flush();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
static class pair implements Comparable<pair> {
int x, y;
pair(int s, int d) {
x = s;
y = d;
}
@Override
public int compareTo(pair p) {
return (x == p.x && y == p.y) ? 0 : 1;
}
@Override
public String toString() {
return x + " " + y;
}
}
static long mod(long ans, int mod) {
return (ans % mod + mod) % mod;
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int log(int n, int base) {
int ans = 0;
while (n + 1 > base) {
ans++;
n /= base;
}
return ans;
}
static long pow(long b, long e) {
long ans = 1;
while (e > 0) {
if ((e & 1) == 1)
ans = ((ans * 1l * b));
e >>= 1;
{
}
b = ((b * 1l * b));
}
return ans;
}
static int powmod(int b, long e, int mod) {
int ans = 1;
b %= mod;
while (e > 0) {
if ((e & 1) == 1)
ans = (int) ((ans * 1l * b) % mod);
e >>= 1;
b = (int) ((b * 1l * b) % mod);
}
return ans;
}
static int ceil(int a, int b) {
int ans = a / b;
return a % b == 0 ? ans : ans + 1;
}
static long ceil(long a, long b) {
long ans = a / b;
return a % b == 0 ? ans : ans + 1;
}
// Returns nCr % p
static int nCrModp(int n, int r, int p) {
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public int[] intArr(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] longArr(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
} | Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | f2f5ca83770d0cea6bd9d4d9c332449a | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases = Integer.valueOf(sc.nextLine());
String data = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb1, sb2;
while (cases-- > 0) {
int len = Integer.valueOf(sc.nextLine());
String[] line = sc.nextLine().split(" ");
int[] prefixNum = new int[len];
int max = -999;
for (int i = 0 ; i < len ; i++) {
prefixNum[i] = Integer.valueOf(line[i]);
if (max < prefixNum[i])
max = prefixNum[i];
}
if (max == 0)
max = len;
sb1 = new StringBuilder();
sb2 = new StringBuilder();
String prevStr = null;
for (int i = 0 ; i <= len ; i++) {
if (i == 0) {
for (int j = 0 ; j < max ; j++)
sb1.append(data.charAt(j%26));
//System.out.println(sb1.toString());
continue;
}
for (int j = 0 ; j < prefixNum[i-1] ; j++) {
if (sb1.length() - 1 < j) {
sb1.append(data.charAt((i+j)%26));
if (sb1.toString().equals(prevStr))
sb1.setCharAt(sb1.length() - 1, data.charAt((i+j+1)%26));
}
sb2.append(sb1.charAt(j));
}
if (prefixNum[i-1] == 0) {
for (int j = 0 ; j < max ; j++)
sb2.append(data.charAt((i+j)%26));
}
System.out.println(sb1.toString());
prevStr = new String(sb1);
sb1 = new StringBuilder(sb2);
sb2.setLength(0);
}
System.out.println(sb1.toString());
}
}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | 363494d5befd4e15503695bb88799f4d | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | //package A;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A659Div2 {
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());
StringTokenizer st= new StringTokenizer(br.readLine());
char ch[]= new char[51];
Arrays.fill(ch,'a');
System.out.println(ch);
for (int i=0;i<n;i++){
int x=Integer.parseInt(st.nextToken());
if (ch[x]=='a'){
ch[x]='b';
}else {
ch[x]='a';
}
System.out.println(ch);
}
}
}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | 77fea26a8bd1255b8d29fcbf35aca507 | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.util.*;
public class Solution
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
outer:
while(t-- > 0)
{
long n = sc.nextLong();
long A[] = new long[(int)n];
long max = Long.MIN_VALUE;
for(int i=0;i<n;i++)
{
A[i] = sc.nextLong();
max = Math.max(max, A[i]);
}
char b = 'a';
if(max == 0)
{
for(long i=0;i<=n;i++)
{
if(b == 'z')
{
b = 'a';
}
System.out.println(b++);
}
continue outer;
}
String prev = "";
char c = 'a';
for(long i=0;i<max;i++)
{
if(c == 'z')
prev += 'a';
else
prev += c++;
}
System.out.println(prev);
for(int i=0;i<n;i++)
{
String cur = prev.substring(0, (int)A[i]);
for(int j=(int)A[i];j<max;j++)
{
c = prev.charAt(j);
if(c == 'z')
{
cur += 'a';
}
else
cur += ++c;
}
System.out.println(cur);
prev = cur;
}
}
}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | 5fc781f9471bac5dcbdcf5f3996dc23a | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.util.*;
import java.text.*;
import java.io.*;
public final class Solve {
static void solve(int[] arr, int n) {
int max = max(arr);
String p = "" , next = "";
char s = 'b';
for(int i = 0;i<=max;i++) {
p('a');
p += 'a';
}
p("\n");
for(int i = 0;i<n;i++) {
for(int j = 0;j<=max;j++) {
if(j == arr[i]) {
if(s > 'z') {
s = 'b';
}
p(s);
next += s;
s++;
}
else {
p(p.charAt(j));
next += p.charAt(j);
}
}
p = next;
next = "";
p("\n");
}
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for(int i : a) {
max = Math.max(max, i);
}
return max;
}
public static void main(String args[]) throws IOException {
FastReader sc = new FastReader();
long s1 = System.currentTimeMillis();
int t = sc.nextInt();
while(t-- > 0 ) {
int n = sc.nextInt();
int[] arr = sc.readIntArray(n);
solve(arr, n);
}
long e1 = System.currentTimeMillis();
// run(s1,e1);
}
static void p(Object p){System.out.print(p);}
static void pn(Object p){System.out.println(p);}
static class FastReader {
static void run(long s, long e) {
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.print("Execution time is " + formatter.format((e - s) / 1000d) + " seconds");}
static BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));}
static boolean isPalindrome(String str1, String str2) {
String str3 = str1+str2;
int i = 0, j = str3.length()-1;
while(i < j) {
char a = str3.charAt(i), b = str3.charAt(j);
if(a != b) return false;
i++;j--;}
return true;}
static boolean isPalindrome(String str) {
int i = 0, j = str.length()-1;
while(i < j) {
char a = str.charAt(i), b = str.charAt(j);
if(a != b) return false;
i++;j--;}
return true;}
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());}
static int fact(int n) {
if(n == 1) return 1;
return n * fact(n-1);}
public int[] readIntArray(int n) {
int[] arr = new int[n];
for(int i=0; i<n; ++i)
arr[i]=nextInt();
return arr;}
public long[] readLongArray(int n) {
long[] arr = new long[n];
for(int i=0; i<n; ++i)
arr[i]=nextLong();
return arr;}
public int[][] readIntArray(int m, int n){
int[][] arr = new int[m][n];
for(int i = 0;i<m;i++)
for(int j = 0;j<n;j++)
arr[i][j] = nextInt();
return arr;}
public String[] readStringArray(int n) {
String[] arr = new String[n];
for(int i=0; i<n; ++i)
arr[i]= nextLine();
return arr;}
double nextDouble() {return Double.parseDouble(next());}
String nextLine() {
String str = "";
try{str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | d85efbdd150ad711fece94a9ded8e04c | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.util.Scanner;
public class StringTransformation {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-->0){
int n = sc.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
char[] s = new char[200];
for(int i = 0; i < 200; i++) {
s[i] = 'a';
}
System.out.println(s);
for(int i = 0; i < n; i++) {
s[a[i]] = (s[a[i]] == 'a' ? 'b' : 'a');
System.out.println(s);
}
}
}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | 7a8980d3791fe82a9491bbea21946a23 | train_001.jsonl | 1595601300 | The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class CommonPrefixes {
public static void main(String[] args) {
byte[] mas;
Scanner sc = new Scanner(System.in);
byte t = sc.nextByte();
for (int i = 0; i < t; i++) {
byte max = 1;
byte n = sc.nextByte();
mas = new byte[n];
for (int j = 0; j < n; j++) {
byte temp = sc.nextByte();
if (temp>max){
max=temp;
}
mas[j] = temp;
}
StringBuilder temp = new StringBuilder("");
for (int j = -1; j < n; j++) {
if (j==-1){
for (int l = 0; l < max; l++) {
temp.append("a");
}
}
else{
for (int l = mas[j]; l < max; l++) {
if (temp.charAt(l)=='a'){
temp.setCharAt(l, 'b');
}
else {
temp.setCharAt(l, 'a');
}
}
}
System.out.println(temp);
}
}
}
}
| Java | ["4\n4\n1 2 4 2\n2\n5 3\n3\n1 3 1\n3\n0 0 0"] | 1 second | ["aeren\nari\narousal\naround\nari\nmonogon\nmonogamy\nmonthly\nkevinvu\nkuroni\nkurioni\nkorone\nanton\nloves\nadhoc\nproblems"] | NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are: Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$ Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$ Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$ Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$ | Java 8 | standard input | [
"constructive algorithms",
"greedy",
"strings"
] | 6983823efdc512f8759203460cd6bb4c | Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$. | 1,200 | For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints. | standard output | |
PASSED | 3a0fe571d7b62da4953d505d5a9ad025 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.util.Random;
import java.util.StringTokenizer;
public class Main {
long b = 31;
String fileName = "";
////////////////////// SOLUTION SOLUTION SOLUTION //////////////////////////////
int INF = Integer.MAX_VALUE / 10;
long MODULO = 1000*1000*1000+7;
void solve() throws IOException {
int n = readInt();
int k = readInt();
int[][] field = new int[4][n];
for (int i=0; i<4; ++i){
for (int j=0; j<n; ++j){
field[i][j] = readInt();
}
}
Move[] moves = new Move[60000];
int curMove = 0;
for (int q=0; q<2*n+20; ++q){
boolean wasCar = false;
boolean wasEmpty = false;
int emptyI = 0;
int emptyJ = 0;
for (int i=0; i<n; ++i){
if (field[1][i] == 0) {
wasEmpty = true;
emptyI = 1;
emptyJ = i;
}
else {
wasCar = true;
if (field[1][i] == field[0][i]){
wasEmpty = true;
emptyI = 1;
emptyJ = i;
moves[curMove++] = new Move(field[1][i], 0, i);
field[1][i] = 0;
}
}
if (field[2][i] == 0) {
wasEmpty = true;
emptyI = 2;
emptyJ = i;
}
else {
wasCar = true;
if (field[2][i] == field[3][i]){
wasEmpty = true;
emptyI = 2;
emptyJ = i;
moves[curMove++] = new Move(field[2][i], 3, i);
field[2][i] = 0;
}
}
}
if (wasCar && !wasEmpty) {
out.println(-1);
return;
}
for (int i=0; i<2*n - 1; ++i){
if (emptyI == 1){
if (emptyJ == 0){
if (field[emptyI + 1][emptyJ] != 0){
moves[curMove++] = new Move(field[emptyI + 1][emptyJ], emptyI, emptyJ);
field[emptyI][emptyJ] = field[emptyI + 1][emptyJ];
field[emptyI + 1][emptyJ] = 0;
}
emptyI = 2;
continue;
}
if (field[emptyI][emptyJ-1] != 0){
moves[curMove++] = new Move(field[emptyI][emptyJ-1], emptyI, emptyJ);
field[emptyI][emptyJ] = field[emptyI][emptyJ-1];
field[emptyI][emptyJ-1] = 0;
}
emptyJ--;
}
if (emptyI == 2){
if (emptyJ == n-1){
if (field[emptyI - 1][emptyJ] != 0){
moves[curMove++] = new Move(field[emptyI - 1][emptyJ], emptyI, emptyJ);
field[emptyI][emptyJ] = field[emptyI - 1][emptyJ];
field[emptyI - 1][emptyJ] = 0;
}
emptyI = 1;
continue;
}
if (field[emptyI][emptyJ+1] != 0){
moves[curMove++] = new Move(field[emptyI][emptyJ+1], emptyI, emptyJ);
field[emptyI][emptyJ] = field[emptyI][emptyJ+1];
field[emptyI][emptyJ+1] = 0;
}
emptyJ++;
}
}
}
out.println(curMove);
/*for (int i=0; i<4; ++i){
for (int j=0; j<n; ++j)
out.print(field[i][j] +" ");
out.println();
}*/
for (int i=0; i<curMove; ++i){
Move m = moves[i];
out.println(m.car + " " + (m.x+1) +" "+(m.y+1));
}
}
class Move{
int car, x, y;
Move(int car, int x, int y){
this.x = x;
this.y = y;
this.car = car;
}
}
class Point{
int x, y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
class Vertex implements Comparable<Vertex>{
int dist, from;
Vertex(int b, int c){
this.dist = c;
this.from = b;
}
@Override
public int compareTo(Vertex o) {
return this.dist-o.dist;
}
}
///////////////////////////////////////////////////////////////////////////////////////////
class Edge{
int from, to, dist;
Edge(int from, int to, int dist){
this.from = from;
this.to = to;
this.dist = dist;
}
}
void readUndirectedGraph (int n, int m, int[][] graph) throws IOException{
Edge[] edges = new Edge[n-1];
int[] countEdges = new int[n];
graph = new int[n][];
for (int i=0; i<n-1; ++i){
int from = readInt() - 1;
int to = readInt() - 1;
countEdges[from]++;
countEdges[to]++;
edges[i] = new Edge(from, to, 0);
}
for (int i=0; i<n; ++i) graph[i] = new int[countEdges[i]];
for (int i=0; i<n-1; ++i){
graph[edges[i].to][--countEdges[edges[i].to]] = edges[i].dist;
graph[edges[i].dist][-- countEdges[edges[i].dist]] = edges[i].to;
}
}
class SparseTable{
int[][] rmq;
int[] logTable;
int n;
SparseTable(int[] a){
n = a.length;
logTable = new int[n+1];
for(int i = 2; i <= n; ++i){
logTable[i] = logTable[i >> 1] + 1;
}
rmq = new int[logTable[n] + 1][n];
for(int i=0; i<n; ++i){
rmq[0][i] = a[i];
}
for(int k=1; (1 << k) < n; ++k){
for(int i=0; i + (1 << k) <= n; ++i){
int max1 = rmq[k - 1][i];
int max2 = rmq[k-1][i + (1 << (k-1))];
rmq[k][i] = Math.max(max1, max2);
}
}
}
int max(int l, int r){
int k = logTable[r - l];
int max1 = rmq[k][l];
int max2 = rmq[k][r - (1 << k) + 1];
return Math.max(max1, max2);
}
}
long checkBit(long mask, int bit){
return (mask >> bit) & 1;
}
class Dsu{
int[] parent;
int countSets;
Dsu(int n){
countSets = n;
parent = new int[n];
for(int i=0; i<n; ++i){
parent[i] = i;
}
}
int findSet(int a){
if(parent[a] == a) return a;
parent[a] = findSet(parent[a]);
return parent[a];
}
void unionSets(int a, int b){
a = findSet(a);
b = findSet(b);
if(a!=b){
countSets--;
parent[a] = b;
}
}
}
static int checkBit(int mask, int bit) {
return (mask >> bit) & 1;
}
boolean isLower(char c){
return c >= 'a' && c <= 'z';
}
////////////////////////////////////////////////////////////
class SegmentTree{
int[] t;
int n;
SegmentTree(int n){
t = new int[4*n];
build(new int[n+1], 1, 1, n);
}
void build (int a[], int v, int tl, int tr) {
if (tl == tr)
t[v] = a[tl];
else {
int tm = (tl + tr) / 2;
build (a, v*2, tl, tm);
build (a, v*2+1, tm+1, tr);
}
}
void update (int v, int tl, int tr, int l, int r, int add) {
if (l > r)
return;
if (l == tl && tr == r)
t[v] += add;
else {
int tm = (tl + tr) / 2;
update (v*2, tl, tm, l, Math.min(r,tm), add);
update (v*2+1, tm+1, tr, Math.max(l,tm+1), r, add);
}
}
int get (int v, int tl, int tr, int pos) {
if (tl == tr)
return t[v];
int tm = (tl + tr) / 2;
if (pos <= tm)
return t[v] + get (v*2, tl, tm, pos);
else
return t[v] + get (v*2+1, tm+1, tr, pos);
}
}
class Fenwik {
long[] t;
int length;
Fenwik(int[] a) {
length = a.length + 100;
t = new long[length];
for (int i = 0; i < a.length; ++i) {
inc(i, a[i]);
}
}
void inc(int ind, int delta) {
for (; ind < length; ind = ind | (ind + 1)) {
t[ind] = Math.max(delta, t[ind]);
}
}
long getMax(int r) {
long sum = 0;
for (; r >= 0; r = (r & (r + 1)) - 1) {
sum = Math.max(sum, t[r]);
}
return sum;
}
}
int gcd(int a, int b){
return b == 0 ? a : gcd(b, a%b);
}
long gcd(long a, long b){
return b == 0 ? a : gcd(b, a%b);
}
long binPow(long a, long b, long m) {
if (b == 0) {
return 1;
}
if (b % 2 == 1) {
return ((a % m) * (binPow(a, b - 1, m) % m)) % m;
} else {
long c = binPow(a, b / 2, m);
return (c * c) % m;
}
}
int minInt(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) min = Math.min(min, value);
return min;
}
int maxInt(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) max = Math.max(max, value);
return max;
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
new Main().run();
}
void run() throws NumberFormatException, IOException {
solve();
out.close();
};
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
String delim = " ";
Random rnd = new Random();
Main() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
if (fileName.isEmpty()) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader(fileName + ".in"));
out = new PrintWriter(fileName + ".out");
}
}
tok = new StringTokenizer("");
}
String readLine() throws IOException {
return in.readLine();
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine) {
return null;
}
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt() throws NumberFormatException, IOException {
return Integer.parseInt(readString());
}
byte readByte() throws NumberFormatException, IOException {
return Byte.parseByte(readString());
}
int[] readIntArray (int n) throws NumberFormatException, IOException {
int[] a = new int[n];
for(int i=0; i<n; ++i){
a[i] = readInt();
}
return a;
}
Integer[] readIntegerArray (int n) throws NumberFormatException, IOException {
Integer[] a = new Integer[n];
for(int i=0; i<n; ++i){
a[i] = readInt();
}
return a;
}
long readLong() throws NumberFormatException, IOException {
return Long.parseLong(readString());
}
double readDouble() throws NumberFormatException, IOException {
return Double.parseDouble(readString());
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 5aa271f2e2c1050dc3e37411a8c197c5 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Solution {
private static final boolean DEBUG = false;
private static class Move {
final int car;
final int y;
final int x;
public Move(int car, int y, int x) {
this.car = car;
this.y = y;
this.x = x;
}
@Override
public String toString() {
return "Move{" + "car=" + car + ", y=" + y + ", x=" + x + '}';
}
}
public static void main(String[] args) throws FileNotFoundException {
long beginTime = System.nanoTime();
InputStream is = DEBUG ? new FileInputStream("resources/codeforces/ProblemC-1.in") : System.in;
try (Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(is)))) {
int columnCount = scanner.nextInt();
int carCount = scanner.nextInt();
int[][] carGrid = new int[2][columnCount];
int[][] parkGrid = new int[2][columnCount];
for (int i = 0; i < columnCount; i++) parkGrid[0][i] = scanner.nextInt();
for (int i = 0; i < columnCount; i++) carGrid[0][i] = scanner.nextInt();
for (int i = 0; i < columnCount; i++) carGrid[1][i] = scanner.nextInt();
for (int i = 0; i < columnCount; i++) parkGrid[1][i] = scanner.nextInt();
Move[] froms = new Move[columnCount * 2];
Move[] tos = new Move[columnCount * 2];
for (int x = 0; x < columnCount; x++) {
froms[x] = new Move(0, 0, x);
tos[x] = new Move(0, 0, x + 1);
}
tos[columnCount - 1] = new Move(0, 1, columnCount - 1);
for (int x = columnCount - 1; x >= 0; x--) {
froms[columnCount + columnCount - 1 - x] = new Move(0, 1, x);
tos[columnCount + columnCount - 1 - x] = new Move(0, 1, x - 1);
}
tos[2 * columnCount - 1] = new Move(0, 0, 0);
List<Move> moves = new ArrayList<>();
// Park any possible car
for (int y = 0; y < 2; y++) {
for (int x = 0; x < columnCount; x++) {
int car = carGrid[y][x];
if (car != 0 && car == parkGrid[y][x]) {
moves.add(new Move(car, y == 0 ? 1 : 4, x + 1));
carCount--;
carGrid[y][x] = 0;
}
}
}
int pos = -1;
for (int i = 0; i < froms.length; i++) {
Move from = froms[i];
Move to = tos[i];
if (carGrid[from.y][from.x] != 0 && carGrid[to.y][to.x] == 0) {
pos = i;
break;
}
}
if (carCount > 0 && pos < 0) {
System.out.println(-1);
} else {
while (carCount > 0) {
Move from = froms[pos];
int car = carGrid[from.y][from.x];
if (car == 0)
assert car != 0;
Move to = tos[pos];
moves.add(new Move(car, to.y + 2, to.x + 1));
carGrid[from.y][from.x] = 0;
carGrid[to.y][to.x] = car;
if (car == parkGrid[to.y][to.x]) {
moves.add(new Move(car, to.y == 0 ? 1 : 4, to.x + 1));
carCount--;
carGrid[to.y][to.x] = 0;
}
for (int i = 0; i < froms.length; i++) {
from = froms[i];
to = tos[i];
if (carGrid[from.y][from.x] != 0 && carGrid[to.y][to.x] == 0) {
pos = i;
break;
}
}
}
StringBuilder sb = new StringBuilder();
for (Move m : moves) {
sb.append(m.car).append(' ').append(m.y).append(' ').append(m.x).append('\n');
}
System.out.println(moves.size());
System.out.println(sb);
}
}
System.err.println( "Done in " + ((System.nanoTime() - beginTime) / 1e9) + " seconds.");
}
} | Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 385daf1bd2a0fa951a56963b333a0c3b | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | /**
* @author Finn Lidbetter
*/
import java.util.*;
import java.io.*;
import java.awt.geom.*;
public class TaskC {
static int n;
static int nLeft;
static int[][] park;
static int[][] move;
static int spaceRow;
static int spaceCol;
static StringBuilder sb;
static int totalMoves = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
sb = new StringBuilder();
String[] s = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
int k = Integer.parseInt(s[1]);
park = new int[2][n];
move = new int[2][n];
nLeft = k;
s = br.readLine().split(" ");
for (int i=0; i<n; i++) {
park[0][i] = Integer.parseInt(s[i]);
}
s = br.readLine().split(" ");
for (int i=0; i<n; i++) {
move[0][i] = Integer.parseInt(s[i]);
}
s = br.readLine().split(" ");
for (int i=0; i<n; i++) {
move[1][i] = Integer.parseInt(s[i]);
}
s = br.readLine().split(" ");
for (int i=0; i<n; i++) {
park[1][i] = Integer.parseInt(s[i]);
}
int[][] firstPark = parkCars();
if (nLeft==2*n) {
System.out.println(-1);
return;
}
spaceRow = -1;
spaceCol = -1;
for (int i=0; i<n; i++) {
if (move[0][i]==0) {
spaceRow = 0;
spaceCol = i;
break;
} else if(move[1][i]==0) {
spaceRow = 1;
spaceCol = i;
break;
}
}
addMove(firstPark);
while (nLeft>0) {
//System.out.println(Arrays.toString(move[0]));
//System.out.println(Arrays.toString(move[1]));
//System.out.println(nLeft);
//System.out.println();
addMove(rotate());
addMove(parkCars());
}
System.out.println(totalMoves);
System.out.print(sb);
}
static void addMove(int[][] cMoves) {
if (cMoves==null)
return;
for (int i=0; i<cMoves.length; i++) {
totalMoves++;
sb.append(cMoves[i][0]+" "+cMoves[i][1]+" "+cMoves[i][2]+"\n");
}
}
static int[][] parkCars() {
int count = 0;
for (int i=0; i<n; i++) {
if (move[0][i]!=0 && move[0][i]==park[0][i]) {
count++;
}
if (move[1][i]!=0 && move[1][i]==park[1][i]) {
count++;
}
}
if (count==0)
return null;
int[][] cMoves = new int[count][3];
int index = 0;
for (int i=0; i<n; i++) {
if (move[0][i]!=0 && move[0][i]==park[0][i]) {
cMoves[index] = new int[]{park[0][i], 1, i+1};
move[0][i] = 0;
index++;
}
if (move[1][i]!=0 && move[1][i]==park[1][i]) {
cMoves[index] = new int[]{park[1][i], 4, i+1};
move[1][i] = 0;
index++;
}
}
nLeft -= count;
return cMoves;
}
static int[][] rotate() {
int moveCount = 0;
int[][] carMoves = new int[nLeft][3];
int index = 0;
while (moveCount<2*n-1) {
int[] cMove = rotateOne();
if (cMove!=null) {
//System.out.println(Arrays.toString(cMove));
//System.out.println("index: "+index+", nLeft: "+nLeft);
carMoves[index][0] = cMove[0];
carMoves[index][1] = cMove[1];
carMoves[index][2] = cMove[2];
index++;
}
if (spaceRow==0) {
if (spaceCol<n-1) {
spaceCol++;
} else {
spaceRow++;
}
} else {
if (spaceCol>0) {
spaceCol--;
} else {
spaceRow--;
}
}
moveCount++;
}
return carMoves;
}
static int[] rotateOne() {
if (spaceRow==0) {
// moveLeft
if (spaceCol==n-1) {
if (move[1][n-1]>0) {
move[0][n-1] = move[1][n-1];
move[1][n-1] = 0;
return new int[]{move[spaceRow][spaceCol], 2, n};
} else {
return null;
}
} else {
if (move[0][spaceCol+1]>0) {
move[spaceRow][spaceCol] = move[spaceRow][spaceCol+1];
move[spaceRow][spaceCol+1] = 0;
return new int[]{move[spaceRow][spaceCol], 2, spaceCol+1};
} else {
return null;
}
}
} else {
if (spaceCol==0) {
if (move[0][0]>0) {
move[spaceRow][spaceCol] = move[0][spaceCol];
move[0][0] = 0;
return new int[]{move[spaceRow][spaceCol], 3, 1};
} else {
return null;
}
} else {
if (move[1][spaceCol-1]>0) {
move[spaceRow][spaceCol] = move[spaceRow][spaceCol-1];
move[spaceRow][spaceCol-1] = 0;
return new int[]{move[spaceRow][spaceCol], 3, spaceCol+1};
} else {
return null;
}
}
}
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 2ca789cee43a2565d8130230d596d35c | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.*;
import java.util.Iterator;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyBufferedReader in = new MyBufferedReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int numMoves;
StringBuilder s;
public void solve(int testNumber, MyBufferedReader in, PrintWriter out) {
numMoves = 0;
s = new StringBuilder();
int[] d = in.getALineOfInts(2);
int n = d[0];
int k = d[1];
int[][] a = in.readMatrix(4, n);
if (k == 2 * n) {
boolean allInFrontOfDifferent = true;
for (int i = 0; i < n; i++) {
if (a[1][i] == a[0][i] || a[2][i] == a[3][i]) {
allInFrontOfDifferent = false;
break;
}
}
if(allInFrontOfDifferent) {
out.println(-1);
return;
}
}
k -= parkAdj(a, n);
while (k > 0) {
movePiece(a, n);
k -= parkAdj(a, n);
}
out.println(numMoves);
out.println(s);
}
private void movePiece(int[][] a, int n) {
CyclingIterator it = new CyclingIterator(1, 0, true, 1, 2, 0, n - 1);
int currRow;
int currCol;
int nextRow = 1;
int nextCol = 0;
do {
currRow = nextRow;
currCol = nextCol;
int[] next = it.next();
nextRow = next[0];
nextCol = next[1];
} while (a[currRow][currCol] == 0 || a[nextRow][nextCol] != 0);
move(currRow, currCol, nextRow, nextCol, a);
}
private int parkAdj(int[][] a, int n) {
int numParked = 0;
for (int i = 0; i < n; i++) {
if (a[1][i] != 0 && a[1][i] == a[0][i]) {
move(1, i, 0, i, a);
numParked++;
}
if (a[2][i] != 0 && a[2][i] == a[3][i]) {
move(2, i, 3, i, a);
numParked++;
}
}
return numParked;
}
private void move(int srcRow, int srcCol, int targetRow, int targetCol, int[][] a) {
numMoves++;
s.append(a[srcRow][srcCol] + " " + (targetRow + 1) + " " + (targetCol + 1));
s.append('\n');
a[targetRow][targetCol] = a[srcRow][srcCol];
a[srcRow][srcCol] = 0;
}
static class CyclingIterator implements Iterator<int[]> {
private int currRow;
private int currCol;
private boolean clockwise;
private final int rowLow;
private final int rowHigh;
private final int colLow;
private final int colHigh;
public CyclingIterator(int startRow, int startCol, boolean clockwise, int rowLow, int
rowHigh, int colLow, int colHigh) {
this.currRow = startRow;
this.currCol = startCol;
this.clockwise = clockwise;
this.rowLow = rowLow;
this.rowHigh = rowHigh;
this.colLow = colLow;
this.colHigh = colHigh;
}
int getCurrDir(int start, int otherStart, int low, int high, int otherLow, int
otherHigh, boolean clockwise) {
int currDir = 0;
if (low == high) {
//will not move in this dim
return 0;
}
if (start == low && otherStart == otherLow && !clockwise) {
currDir = 1;
} else if (start == high && otherStart == otherLow && clockwise) {
currDir = -1;
} else if (start == low && otherStart == otherHigh && clockwise) {
currDir = 1;
} else if (start == high && otherStart == otherHigh && !clockwise) {
currDir = -1;
} else if (start != low && start != high) {
//not a corner
int clockwiseInt = clockwise ? 1 : -1;
currDir = otherStart == otherLow ? -clockwiseInt : clockwiseInt;
}
return currDir;
}
public int[] next(int stepsRem) {
while (stepsRem > 0) {
int currRowDir = getCurrDir(currRow, currCol, rowLow, rowHigh, colLow, colHigh,
clockwise);
int currColDir = getCurrDir(currCol, currRow, colLow, colHigh, rowLow, rowHigh,
!clockwise);
int nextRow = currRow + currRowDir * stepsRem;
nextRow = Math.min(nextRow, rowHigh);
nextRow = Math.max(nextRow, rowLow);
int nextCol = currCol + currColDir * stepsRem;
nextCol = Math.min(nextCol, colHigh);
nextCol = Math.max(nextCol, colLow);
int stepsMade = Math.abs(nextRow - currRow) + Math.abs(nextCol - currCol);
if (stepsMade == 0) {
break;
}
stepsRem -= stepsMade;
currRow = nextRow;
currCol = nextCol;
}
return new int[]{currRow, currCol};
}
@Override
public boolean hasNext() {
return colHigh >= colLow && rowHigh >= rowLow;
}
@Override
public int[] next() {
return next(1);
}
}
}
static class MyBufferedReader {
BufferedReader in;
public MyBufferedReader(InputStream s) {
this.in = new BufferedReader(new InputStreamReader(s));
}
public MyBufferedReader(BufferedReader in) {
this.in = in;
}
public int[] getALineOfInts(int numExpected) {
if (numExpected == 0) {
try {
in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return new int[0];
}
int[] res = new int[numExpected];
StringTokenizer st = null;
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < numExpected; i++)
res[i] = Integer.parseInt(st.nextToken());
return res;
}
public int[][] readMatrix(int nrows, int ncols) {
int[][] res = new int[nrows][ncols];
StringTokenizer st = new StringTokenizer("");
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
if (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
res[i][j] = Integer.parseInt(st.nextToken());
}
}
return res;
}
}
} | Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | f7c34dfcbfffb64f1058f32e7858926e | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | //package baobab;
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
int n;
int k;
int[][] g;
int emptyX;
int emptyY;
List<String> ans;
void solve() {
n = io.nextInt();
k = io.nextInt();
g = new int[4][n];
for (int y=0; y<4; y++) {
for (int x=0; x<n; x++) {
g[y][x] = io.nextInt();
}
}
ans = new ArrayList<>(10200);
emptyX = -1;
emptyY = -1;
checkIfAnythingIsNextToGoal();
if (emptyX < 0) done(-1); // all full and nothing can move
while (moveEverythingAround()) {
checkIfAnythingIsNextToGoal();
}
io.println(ans.size());
for (String line : ans) io.println(line);
}
boolean moveEverythingAround() {
int moves = 0;
int y = emptyY;
int x = emptyX;
for (int count=0; count<2*n; count++) {
if (g[y][x] != 0) {
// move car
int car = g[y][x];
if (y == 1 && x > 0) {
g[1][x-1] = car;
ans.add(car + " " + (1+1) + " " + ((x-1)+1));
}
else if (y == 1 && x == 0) {
g[2][0] = car;
ans.add(car + " " + (2+1) + " " + (0+1));
}
else if (y == 2 && x < n-1) {
g[2][x+1] = car;
ans.add(car + " " + (2+1) + " " + (x+1+1));
}
else if (y == 2 && x == n-1) {
g[1][n-1] = car;
ans.add(car + " " + (1+1) + " " + (n-1+1));
}
g[y][x] = 0;
moves++;
}
// set next step coordinates
if (y == 1 && x == n-1) y = 2;
else if (y == 2 && x == 0) y = 1;
else if (y == 1) x++;
else x--;
}
return moves > 0;
}
void checkIfAnythingIsNextToGoal() {
for (int x=0; x<n; x++) {
if (g[1][x] == 0) {
emptyX = x;
emptyY = 1;
} else if (g[0][x] == g[1][x]) {
ans.add(g[0][x] + " 1 " + (x+1));
emptyX = x;
emptyY = 1;
g[1][x] = 0;
g[0][x] = 0;
}
}
for (int x=0; x<n; x++) {
if (g[2][x] == 0) {
emptyX = x;
emptyY = 2;
} else if (g[3][x] == g[2][x]) {
ans.add(g[3][x] + " 4 " + (x+1));
emptyX = x;
emptyY = 2;
g[3][x] = 0;
g[2][x] = 0;
}
}
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000000001;
}
class DrawGrid {
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/** Query sums with log(n) modifyRange */
int N;
long[] p;
public SegmentTree(int n) {
/* TODO: Test that this works. */
for (N=2; N<n; N++) N *= 2;
p = new long[2*N];
}
public void modifyRange(int a, int b, long change) {
muuta(a, change);
muuta(b+1, -change);
}
void muuta(int k, long muutos) {
k += N;
p[k] += muutos;
for (k /= 2; k >= 1; k /= 2) {
p[k] = p[2*k] + p[2*k+1];
}
}
public long get(int k) {
int a = N;
int b = k+N;
long s = 0;
while (a <= b) {
if (a%2 == 1) s += p[a++];
if (b%2 == 0) s += p[b--];
a /= 2;
b /= 2;
}
return s;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
HashMap<Long, List<Long>> edges;
public Graph() {
edges = new HashMap<>();
}
List<Long> getSetNeighbors(Long node) {
List<Long> neighbors = edges.get(node);
if (neighbors == null) {
neighbors = new ArrayList<>();
edges.put(node, neighbors);
}
return neighbors;
}
void addBiEdge(Long a, Long b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(Long from, Long to) {
getSetNeighbors(to); // make sure all have initialized lists
List<Long> neighbors = getSetNeighbors(from);
neighbors.add(to);
}
// topoSort variables
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
HashMap<Long, Integer> vis;
List<Long> topoAns;
List<Long> failDueToCycle = new ArrayList<Long>() {{ add(-1L); }};
List<Long> topoSort() {
topoAns = new ArrayList<>();
vis = new HashMap<>();
for (Long a : edges.keySet()) {
if (!topoDFS(a)) return failDueToCycle;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(long curr) {
Integer status = vis.get(curr);
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis.put(curr, INPROGRESS);
for (long next : edges.get(curr)) {
if (!topoDFS(next)) return false;
}
vis.put(curr, FINISHED);
topoAns.add(curr);
return true;
}
}
public class StronglyConnectedComponents {
/** Kosaraju's algorithm */
ArrayList<Integer>[] forw;
ArrayList<Integer>[] bacw;
/** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
public int getCount(int n, int[] mista, int[] minne) {
forw = new ArrayList[n+1];
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
forw[i] = new ArrayList<Integer>();
bacw[i] = new ArrayList<Integer>();
}
for (int i=0; i<mista.length; i++) {
int a = mista[i];
int b = minne[i];
forw[a].add(b);
bacw[b].add(a);
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
public void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : forw[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
public void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return false;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long pow(long base, int exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
if (exp % 2 != 0) ans *= base;
return ans;
}
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 03ee70e8f66b83669aef1a79ac026ed2 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.BufferedReader;
// import java.io.FileInputStream;
// import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.round;
import static java.lang.Math.sqrt;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.fill;
import static java.util.Arrays.sort;
import static java.util.Collections.reverseOrder;
import static java.util.Collections.sort;
import static java.util.Comparator.comparingInt;
import static java.util.Comparator.comparingLong;
public class Main {
FastScanner in;
PrintWriter out;
private void solve() throws IOException {
int n = in.nextInt(), k = in.nextInt();
int[][] a = new int[4][n];
for (int i = 0; i < 4; i++)
for (int j = 0; j < n; j++)
a[i][j] = in.nextInt() - 1;
ArrayList<String> ans = new ArrayList<>();
for (int i = 1; i < 3; i++)
for (int j = 0; j < n; j++)
if (a[i][j] != -1 && a[i / 2 * 3][j] == a[i][j]) {
ans.add((a[i][j] + 1) + " " + (i / 2 * 3 + 1) + " " + (j + 1));
k--;
a[i / 2 * 3][j] = a[i][j] = -1;
}
if (k == 2 * n) {
out.println(-1);
return;
}
int i = 1, j = 0, ni, nj;
while (k > 0) {
ni = i;
nj = i == 1 ? j + 1 : j - 1;
if (nj == n) {
ni = 2;
nj = n - 1;
} else if (nj == -1) {
ni = 1;
nj = 0;
}
if (a[ni][nj] != -1 && a[i][j] == -1) {
ans.add((a[ni][nj] + 1) + " " + (i + 1) + " " + (j + 1));
a[i][j] = a[ni][nj];
a[ni][nj] = -1;
}
if (a[i][j] != -1 && a[i / 2 * 3][j] == a[i][j]) {
ans.add((a[i][j] + 1) + " " + (i / 2 * 3 + 1) + " " + (j + 1));
k--;
a[i / 2 * 3][j] = a[i][j] = -1;
}
i = ni;
j = nj;
}
out.println(ans.size());
for(String s : ans)
out.println(s);
}
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();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | f76e98e88374ed8f05d04fa0bc756d5b | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ProblemCTesla solver = new ProblemCTesla();
solver.solve(1, in, out);
out.close();
}
static class ProblemCTesla {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[][] a = in.nextIntArrayArray(4, n);
List<String> list = new ArrayList<>();
boolean can = false;
int[] idx = new int[2];
for (int i = 0; i < n; i++) {
if (a[1][i] == 0) {
can = true;
idx = new int[]{1, i};
} else if (a[1][i] == a[0][i]) {
can = true;
idx = new int[]{1, i};
list.add(a[1][i] + " 1 " + (i + 1));
a[1][i] = 0;
}
}
for (int i = 0; i < n; i++) {
if (a[2][i] == 0) {
can = true;
idx = new int[]{2, i};
} else if (a[2][i] == a[3][i]) {
can = true;
idx = new int[]{2, i};
list.add(a[2][i] + " 4 " + (i + 1));
a[2][i] = 0;
}
}
if (!can) {
out.println(-1);
return;
}
for (int i = 0; i < 2 * n; i++) {
for (int j = 0; j < 2 * n; j++) {
int[] next;
if (idx[0] == 1) {
if (idx[1] == 0) {
next = new int[]{2, 0};
} else {
next = new int[]{idx[0], idx[1] - 1};
}
} else {
if (idx[1] == n - 1) {
next = new int[]{1, n - 1};
} else {
next = new int[]{idx[0], idx[1] + 1};
}
}
if (a[next[0]][next[1]] != 0) {
a[idx[0]][idx[1]] = a[next[0]][next[1]];
a[next[0]][next[1]] = 0;
list.add(a[idx[0]][idx[1]] + " " + (idx[0] + 1) + " " + (idx[1] + 1));
if (a[idx[0]][idx[1]] == a[(idx[0] - 1) * 3][idx[1]]) {
list.add(a[idx[0]][idx[1]] + " " + ((idx[0] - 1) * 3 + 1) + " " + (idx[1] + 1));
a[idx[0]][idx[1]] = 0;
}
}
idx = next;
}
}
out.println(list.size());
for (int i = 0; i < list.size(); i++) {
out.println(list.get(i));
}
}
}
static class InputReader {
private BufferedReader br;
private StringTokenizer st;
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
st = new StringTokenizer("");
}
public String nextString() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine(), " ");
} catch (IOException e) {
throw new InputMismatchException();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public int[][] nextIntArrayArray(int n, int m) {
int[][] res = new int[n][m];
for (int i = 0; i < n; i++) {
res[i] = nextIntArray(m);
}
return res;
}
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | fdbc34bd8fe13d143bdc5f743d658010 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Solution1 {
private void solve() throws IOException {
int n = in.nextInt();
int k = in.nextInt();
int[][] parking = new int[4][n];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
parking[i][j] = in.nextInt();
}
}
int turns = 0;
StringBuilder sequence = new StringBuilder("");
while (turns <= 20000) {
int ras = 0;
for (int i = 0; i < n - 1; i++) {
if (parking[1][i] != 0) {
if (parking[0][i] == parking[1][i]) {
sequence.append(parking[1][i]).append(' ').append(1).append(' ').append(i + 1).append('\n');
parking[1][i] = 0;
turns++;
ras++;
k--;
}
else if (parking[1][i + 1] == 0) {
sequence.append(parking[1][i]).append(' ').append(2).append(' ').append(i + 2).append('\n');
parking[1][i + 1] = parking[1][i];
parking[1][i] = 0;
turns++;
ras++;
}
}
}
if (parking[1][n - 1] != 0) {
if (parking[0][n - 1] == parking[1][n - 1]) {
sequence.append(parking[1][n - 1]).append(' ').append(1).append(' ').append(n).append('\n');
parking[1][n - 1] = 0;
turns++;
ras++;
k--;
}
else if (parking[2][n - 1] == 0) {
sequence.append(parking[1][n - 1]).append(' ').append(3).append(' ').append(n).append('\n');
parking[2][n - 1] = parking[1][n - 1];
parking[1][n - 1] = 0;
turns++;
ras++;
}
}
for (int i = n - 1; i > 0; i--) {
if (parking[2][i] != 0) {
if (parking[3][i] == parking[2][i]) {
sequence.append(parking[2][i]).append(' ').append(4).append(' ').append(i + 1).append('\n');
parking[2][i] = 0;
turns++;
ras++;
k--;
} else if (parking[2][i - 1] == 0) {
sequence.append(parking[2][i]).append(' ').append(3).append(' ').append(i).append('\n');
parking[2][i - 1] = parking[2][i];
parking[2][i] = 0;
turns++;
ras++;
}
}
}
if (parking[2][0] != 0) {
if (parking[3][0] == parking[2][0]) {
sequence.append(parking[2][0]).append(' ').append(4).append(' ').append(1).append('\n');
parking[2][0] = 0;
turns++;
ras++;
k--;
}
else if (parking[1][0] == 0) {
sequence.append(parking[2][0]).append(' ').append(2).append(' ').append(1).append('\n');
parking[1][0] = parking[2][0];
parking[2][0] = 0;
turns++;
ras++;
}
}
if (ras == 0) break;
}
if (k == 0) {
System.out.println(turns);
System.out.println(sequence);
}
else {
System.out.println(-1);
}
}
private PrintWriter out;
private MyScanner in;
private void run() throws IOException {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
private class MyScanner {
private BufferedReader br;
private StringTokenizer st;
public MyScanner() throws IOException {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileTitle) throws IOException {
this.br = new BufferedReader(new FileReader(fileTitle));
}
public String nextLine() throws IOException {
String s = br.readLine();
return s == null ? "-1" : s;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return "-1";
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public Integer nextInt() throws IOException {
return Integer.parseInt(this.next());
}
public Long nextLong() throws IOException {
return Long.parseLong(this.next());
}
public Double nextDouble() throws IOException {
return Double.parseDouble(this.next());
}
public void close() throws IOException {
this.br.close();
}
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Solution1().run();
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 26408decf67b5d2a1768cbe0d33d6c56 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.*;
import java.util.*;
public class C implements Runnable{
public static void main (String[] args) {new Thread(null, new C(), "fuuuuuuuuck", 1 << 28).start();}
int done = 0;
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("Go!");
int n = fs.nextInt(), m = 4;
int k = fs.nextInt();
int[][] g = new int[m][n];
for(int i = 0; i < m; i++)
g[i] = fs.nextIntArray(n);
ArrayList<String> res = new ArrayList<>();
while(done < k) {
// for(int[] d : g) System.out.println(Arrays.toString(d));
// System.out.println();
for(int i = 1; i < m - 1; i++) {
for(int j = 0; j < n; j++) {
if(g[i][j] == 0) continue;
if(i == 1 && g[i-1][j] == g[i][j]) {
res.add(g[i][j] + " " + 1 + " " + (j + 1));
done++;
g[i][j] = 0;
}
else if(i == 2 && g[i+1][j] == g[i][j]) {
res.add(g[i][j] + " " + 4 + " " + (j + 1));
done++;
g[i][j] = 0;
}
}
}
if(done == k) break;
boolean x = shift(g, res, k);
if(!x) {
System.out.println(-1);
return;
}
}
out.println(res.size());
for(String str : res) out.println(str);
out.close();
}
boolean shift(int[][] g, ArrayList<String> res, int k) {
boolean[] done = new boolean[k+1];
int n = g[0].length;
boolean go = true;
int iter = 0;
while(go) {
go = false;
iter++;
for(int i = 1; i < 3; i++) {
for(int j = 0; j < n; j++) {
if(g[i][j] == 0) continue;
if(i == 1 && g[i-1][j] == g[i][j]) {
res.add(g[i][j] + " " + 1 + " " + (j + 1));
g[i][j] = 0;
this.done++;
continue;
}
else if(i == 2 && g[i+1][j] == g[i][j]) {
res.add(g[i][j] + " " + 4 + " " + (j + 1));
g[i][j] = 0;
this.done++;
continue;
}
if(done[g[i][j]]) continue;
if(i == 1) {
if(j == n - 1 && g[i+1][n-1] == 0) {
res.add(g[i][j] + " " + 3 + " " + n);
done[g[i][j]] = true;
g[i+1][j] = g[i][j];
g[i][j] = 0;
go = true;
}
else if(j < n - 1 && g[i][j+1] == 0) {
res.add(g[i][j] + " " + 2 + " " + (j + 2));
done[g[i][j]] = true;
g[i][j+1] = g[i][j];
g[i][j] = 0;
go = true;
}
}
else if(i == 2) {
if(j == 0 && g[i-1][j] == 0) {
res.add(g[i][j] + " " + 2 + " " + 1);
done[g[i][j]] = true;
g[i-1][j] = g[i][j];
g[i][j] = 0;
go = true;
}
else if(j > 0 && g[i][j-1] == 0) {
res.add(g[i][j] + " " + 3 + " " + j);
done[g[i][j]] = true;
g[i][j-1] = g[i][j];
g[i][j] = 0;
go = true;
}
}
}
}
}
return iter > 1;
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | bf5d6b7f1fe95742ff4f1cff75142438 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
new Solver().run(1);
}
}
class Solver {
private BufferedReader reader = null;
private StringTokenizer st = null;
private static final int MAXSTEPS = 20000;
private int[][] parking;
private int[] carMove, colMove, rowMove;
private int n, k, moveCnt, carAmount;
private int spotRow, spotCol;
public void run(int inputType) throws Exception {
if (inputType == 0)
reader = new BufferedReader(new FileReader("input.txt"));
else
reader = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(reader.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
parking = new int[4][n];
carMove = new int[MAXSTEPS];
colMove = new int[MAXSTEPS];
rowMove = new int[MAXSTEPS];
for (int i = 0; i < 4; ++i) {
st = new StringTokenizer(reader.readLine());
for (int j = 0; j < n; ++j) {
parking[i][j] = Integer.parseInt(st.nextToken());
if ((i == 1 || i == 2) && parking[i][j] > 0) {
carAmount++;
}
}
}
reader.close();
moveCnt = 0;
checkState();
if (carAmount == 2*n) {
System.out.println(-1);
return;
}
while(carAmount > 0) {
findEmptySpot();
makeMove();
checkState();
}
System.out.println(moveCnt);
for (int i = 0; i < moveCnt; ++i) {
System.out.printf("%d %d %d%n", carMove[i], rowMove[i], colMove[i]);
}
}
void findEmptySpot() {
spotCol = -1;
spotRow = -1;
for (int i = 1; i < 3; ++i) {
for (int j = 0; j < n; ++j) {
if (parking[i][j] == 0) {
spotRow = i;
spotCol = j;
return;
}
}
}
}
void makeMove() {
int curRow = spotRow;
int curCol = (spotRow == 1) ? spotCol - 1 : spotCol + 1;
if (curCol < 0) {
curRow = 2;
curCol = 0;
} else if (curCol >= n) {
curRow = 1;
curCol = n - 1;
}
while(curRow != spotRow || curCol != spotCol) {
if (parking[curRow][curCol] > 0) {
int nextRow = curRow;
int nextCol = (curRow == 1) ? curCol + 1 : curCol - 1;
if (nextCol < 0) {
nextRow = 1;
nextCol = 0;
} else if (nextCol >= n) {
nextRow = 2;
nextCol = n - 1;
}
carMove[moveCnt] = parking[curRow][curCol];
colMove[moveCnt] = nextCol + 1;
rowMove[moveCnt++] = nextRow + 1;
parking[nextRow][nextCol] = parking[curRow][curCol];
parking[curRow][curCol] = 0;
}
curCol = (curRow == 1) ? curCol - 1 : curCol + 1;
if (curCol < 0) {
curCol = 0;
curRow = 2;
} else if (curCol >= n) {
curCol = n - 1;
curRow = 1;
}
}
}
void checkState() {
for (int i = 0; i < n; ++i) {
if (parking[1][i] > 0 && parking[0][i] == parking[1][i]) {
carMove[moveCnt] = parking[1][i];
colMove[moveCnt] = i + 1;
rowMove[moveCnt++] = 1;
parking[1][i] = 0;
carAmount--;
}
if (parking[2][i] > 0 && parking[2][i] == parking[3][i]) {
carMove[moveCnt] = parking[2][i];
colMove[moveCnt] = i + 1;
rowMove[moveCnt++] = 4;
parking[2][i] = 0;
carAmount--;
}
}
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | ea9d1640989d5efd4306deca26a163e3 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000 * 1000 * 1000 + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
int n;
int k;
int[][] mat;
List<String> res = new ArrayList<>();
int idx0;
int[] ix;
int[] iy;
void solve() throws IOException {
n = nextInt();
k = nextInt();
mat = new int[4][];
for (int i = 0; i < 4; i++) {
mat[i] = nextIntArr(n);
}
moveMat();
if (findCnt() == 2 * n) {
outln(-1);
return;
}
ix = new int[2 * n];
iy = new int[2 * n];
for (int i = 0; i < n; i++) {
ix[i] = 1;
ix[i + n] = 2;
iy[i] = i;
iy[i + n] = n - 1 - i;
}
for (int i = 0; i < 2 * n; i++) {
int r = ix[i];
int c = iy[i];
if (mat[r][c] == 0) {
idx0 = i;
break;
}
}
while (true) {
if (findCnt() == 0) {
break;
}
rotate();
moveMat();
}
outln(res.size());
for (int i = 0; i < res.size(); i++) {
outln(res.get(i));
}
}
void rotate() {
if (n == 1) {
if (mat[1][0] != 0) {
res.add(mat[1][0] + " " + 3 + " " + 1);
swap(1, 0, 2, 0);
}
else {
res.add(mat[2][0] + " " + 2 + " " + 1);
swap(1, 0, 2, 0);
}
return;
}
int start = idx0 - 1;
if (start < 0) {
start += 2 * n;
}
int iter = start;
while (iter != idx0) {
move(iter, iter + 1);
iter--;
if (iter < 0) {
iter += 2 * n;
}
}
idx0++;
if (idx0 == 2 * n) {
idx0 = 0;
}
}
void move(int from, int to) {
from = from % (2 * n);
to = to % (2 * n);
if (mat[ix[from]][iy[from]] != 0) {
res.add(mat[ix[from]][iy[from]] + " " + (1 + ix[to]) + " " + (1 + iy[to]));
}
mat[ix[to]][iy[to]] = mat[ix[from]][iy[from]];
}
void swap(int r1, int c1, int r2, int c2) {
int tmp = mat[r1][c1];
mat[r1][c1] = mat[r2][c2];
mat[r2][c2] = tmp;
}
void moveMat() {
for (int i = 0; i < n; i++) {
if (mat[0][i] == mat[1][i] && mat[0][i] != 0) {
res.add(mat[0][i] + " " + 1 + " " + (1 + i));
mat[1][i] = 0;
}
}
for (int i = 0; i < n; i++) {
if (mat[2][i] == mat[3][i] && mat[2][i] != 0) {
res.add(mat[2][i] + " " + 4 + " " + (1 + i));
mat[2][i] = 0;
}
}
}
int findCnt() {
int cnt = 0;
for (int i = 0; i < n; i++) {
if (mat[1][i] != 0) {
cnt++;
}
if (mat[2][i] != 0) {
cnt++;
}
}
return cnt;
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() 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 CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 5c5d0e6c8c4ed2fa3cde8e758fbaecd1 | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author pili
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int numColumns = in.nextInt();
int numCars = in.nextInt();
// Start rotating suckers
// Always move out of the way
int[] topSpot = in.nextIntArray(numColumns);
int[] topRoad = in.nextIntArray(numColumns);
int[] bottomRoad = in.nextIntArray(numColumns);
int[] bottomSpots = in.nextIntArray(numColumns);
ArrayList<String> output = new ArrayList<>();
// start by moving stuff into the spots
while (moveIntoSpot(topSpot, bottomSpots, topRoad, bottomRoad, output)) ;
while (!isValid(topRoad, bottomRoad)) {
// if we can't rotate, end the program
if (!rotate(topRoad, bottomRoad, output)) {
out.println(-1);
return;
}
while (moveIntoSpot(topSpot, bottomSpots, topRoad, bottomRoad, output)) ;
}
out.println(output.size());
for (String s : output) {
out.println(s);
}
}
public boolean rotate(int[] topRoad, int[] bottomRoad, ArrayList<String> output) {
// Find anything with a empty space in the counter-clockwise direction and then rotate
// Is there anything in the left of our topRoad?
for (int i = 1; i < topRoad.length; i++) {
if (topRoad[i - 1] == 0 && topRoad[i] != 0) {
topRoad[i - 1] = topRoad[i];
topRoad[i] = 0;
output.add(topRoad[i - 1] + " " + 2 + " " + (i));
return true;
}
}
for (int i = 0; i < bottomRoad.length - 1; i++) {
if (bottomRoad[i + 1] == 0 && bottomRoad[i] != 0) {
bottomRoad[i + 1] = bottomRoad[i];
bottomRoad[i] = 0;
output.add(bottomRoad[i + 1] + " " + 3 + " " + (i + 2));
return true;
}
}
// handle the corners
if (bottomRoad[bottomRoad.length - 1] != 0 && topRoad[topRoad.length - 1] == 0) {
topRoad[topRoad.length - 1] = bottomRoad[bottomRoad.length - 1];
bottomRoad[bottomRoad.length - 1] = 0;
output.add(topRoad[topRoad.length - 1] + " " + 2 + " " + (topRoad.length));
return true;
}
// handle the corners
if (bottomRoad[0] == 0 && topRoad[0] != 0) {
bottomRoad[0] = topRoad[0];
topRoad[0] = 0;
output.add(bottomRoad[0] + " " + 3 + " " + 1);
return true;
}
return false;
}
public boolean isValid(int[] topRoad, int[] bottomRoad) {
for (int i : topRoad) {
if (i != 0) {
return false;
}
}
for (int i : bottomRoad) {
if (i != 0) {
return false;
}
}
return true;
}
public boolean moveIntoSpot(int[] topSlot, int[] bottomSlot, int[] topRoad, int[] bottomRoad, ArrayList<String> output) {
for (int i = 0; i < topRoad.length; i++) {
if (topRoad[i] != 0 && topRoad[i] == topSlot[i]) {
topSlot[i] = topRoad[i];
topRoad[i] = 0;
output.add(topSlot[i] + " " + 1 + " " + (i + 1));
return true;
}
}
for (int i = 0; i < topRoad.length; i++) {
if (bottomRoad[i] != 0 && bottomRoad[i] == bottomSlot[i]) {
bottomSlot[i] = bottomRoad[i];
bottomRoad[i] = 0;
output.add(bottomSlot[i] + " " + 4 + " " + (i + 1));
return true;
}
}
return false;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void 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();
}
public void println(int i) {
writer.println(i);
}
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 648427fd31c9b24f2958c1f88f13f44e | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Map.Entry;
import static java.lang.Math.*;
public class C extends PrintWriter {
void move(int id, int fx, int fy, int tx, int ty, int m, int[][] b, List<String> ans) {
while (fy < ty) {
int nx = fx;
int ny = fy + 1;
int cx = -1, cy = -1, cd = 10000;
for (int x = 1; x <= 2; x++) {
for (int y = 0; y < m; y++) {
if (b[x][y] == 0) {
int d = abs(nx - x) + abs(ny - y);
if (d < cd) {
cx = x;
cy = y;
cd = d;
}
}
}
}
if (cy < fy && cx == fx) { //
int sx = 3 - cx;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy < ny) { // [>]
int sx = cx;
int sy = cy + 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy > ny) { // [<]
int sx = cx;
int sy = cy - 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cx < nx) { // [v]
int sx = cx + 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cx > nx) { // [^]
int sx = cx - 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
ans.add(id + " " + (nx + 1) + " " + (ny + 1));
b[nx][ny] = id;
b[fx][fy] = 0;
fx = nx;
fy = ny;
}
while (fy > ty) {
int nx = fx;
int ny = fy - 1;
int cx = -1, cy = -1, cd = 10000;
for (int x = 1; x <= 2; x++) {
for (int y = 0; y < m; y++) {
if (b[x][y] == 0) {
int d = abs(nx - x) + abs(ny - y);
if (d < cd) {
cx = x;
cy = y;
cd = d;
}
}
}
}
if (cy > fy && cx == fx) { //
int sx = 3 - cx;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy < ny) { // [>]
int sx = cx;
int sy = cy + 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy > ny) { // [<]
int sx = cx;
int sy = cy - 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cx < nx) { // [v]
int sx = cx + 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cx > nx) { // [^]
int sx = cx - 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
ans.add(id + " " + (nx + 1) + " " + (ny + 1));
b[nx][ny] = id;
b[fx][fy] = 0;
fx = nx;
fy = ny;
}
if (fx < tx) {
if (tx - fx == 2) {
int nx = fx + 1;
int ny = fy;
int cx = -1, cy = -1, cd = 10000;
for (int x = 1; x <= 2; x++) {
for (int y = 0; y < m; y++) {
if (b[x][y] == 0) {
int d = abs(nx - x) + abs(ny - y);
if (d < cd) {
cx = x;
cy = y;
cd = d;
}
}
}
}
while (cx < nx) { // [v]
int sx = cx + 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cx > nx) { // [^]
int sx = cx - 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy < ny) { // [>]
int sx = cx;
int sy = cy + 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy > ny) { // [<]
int sx = cx;
int sy = cy - 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
ans.add(id + " " + (nx + 1) + " " + (ny + 1));
b[nx][ny] = id;
b[fx][fy] = 0;
fx = nx;
fy = ny;
}
b[fx][fy] = 0;
ans.add(id + " " + (tx + 1) + " " + (ty + 1));
}
if (fx > tx) {
if (fx - tx == 2) {
int nx = fx - 1;
int ny = fy;
int cx = -1, cy = -1, cd = 10000;
for (int x = 1; x <= 2; x++) {
for (int y = 0; y < m; y++) {
if (b[x][y] == 0) {
int d = abs(nx - x) + abs(ny - y);
if (d < cd) {
cx = x;
cy = y;
cd = d;
}
}
}
}
while (cx < nx) { // [v]
int sx = cx + 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cx > nx) { // [^]
int sx = cx - 1;
int sy = cy;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy < ny) { // [>]
int sx = cx;
int sy = cy + 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
while (cy > ny) { // [<]
int sx = cx;
int sy = cy - 1;
if (b[sx][sy] != 0) {
ans.add(b[sx][sy] + " " + (cx + 1) + " " + (cy + 1));
b[cx][cy] = b[sx][sy];
b[sx][sy] = 0;
}
cx = sx;
cy = sy;
}
ans.add(id + " " + (nx + 1) + " " + (ny + 1));
b[nx][ny] = id;
b[fx][fy] = 0;
fx = nx;
fy = ny;
}
b[fx][fy] = 0;
ans.add(id + " " + (tx + 1) + " " + (ty + 1));
}
}
void run() {
int n = 4;
int m = nextInt();
int k = nextInt();
int[][] b = nextMatrix(n, m);
List<String> ans = new ArrayList<>();
for (int j = 0; j < m; j++) {
if (b[0][j] == b[1][j] && b[1][j] != 0) {
ans.add(b[1][j] + " " + (0 + 1) + " " + (j + 1));
b[0][j] = 0;
b[1][j] = 0;
--k;
}
}
for (int j = 0; j < m; j++) {
if (b[2][j] == b[3][j] && b[3][j] != 0) {
ans.add(b[3][j] + " " + (3 + 1) + " " + (j + 1));
b[2][j] = 0;
b[3][j] = 0;
--k;
}
}
if (k == 2 * m) {
println(-1);
return;
}
int[] tx = new int[256];
int[] ty = new int[256];
for (int j = 0; j < m; j++) {
if (b[0][j] > 0) {
tx[b[0][j]] = 0;
ty[b[0][j]] = j;
}
if (b[3][j] > 0) {
tx[b[3][j]] = 3;
ty[b[3][j]] = j;
}
}
while (k > 0) {
for (int fx = 1; fx <= 2; fx++) {
for (int fy = 0; fy < m; fy++) {
int id = b[fx][fy];
if (id != 0) {
move(id, fx, fy, tx[id], ty[id], m, b, ans);
--k;
}
}
}
}
println(ans.size());
for (String str : ans) {
println(str);
}
}
boolean skip() {
while (hasNext()) {
next();
}
return true;
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
String next() {
while (!tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String line = nextLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
}
int[] nextArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException err) {
return null;
}
}
public C(OutputStream outputStream) {
super(outputStream);
}
static BufferedReader reader;
static StringTokenizer tokenizer = new StringTokenizer("");
static Random rnd = new Random();
static boolean OJ;
public static void main(String[] args) throws IOException {
OJ = System.getProperty("ONLINE_JUDGE") != null;
C solution = new C(System.out);
if (OJ) {
reader = new BufferedReader(new InputStreamReader(System.in));
solution.run();
} else {
reader = new BufferedReader(new FileReader(new File(C.class.getName() + ".txt")));
long timeout = System.currentTimeMillis();
while (solution.hasNext()) {
solution.run();
solution.println();
solution.println("----------------------------------");
}
solution.println("time: " + (System.currentTimeMillis() - timeout));
}
solution.close();
reader.close();
}
} | Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | dbb643f03f07034cfde8aa95529b382f | train_001.jsonl | 1529858100 | Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with $$$4$$$ rows and $$$n$$$ ($$$n \le 50$$$) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having $$$k$$$ ($$$k \le 2n$$$) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most $$$20000$$$ times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class GC {
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 (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]) {
FastReader reader = new FastReader();
//long n = reader.nextLong();
int n = reader.nextInt();
int cars = reader.nextInt();
// if(cars >= 2*n) {
// System.out.println(-1);
// return ;
// }
List<String> ans = new ArrayList<>();
int r = 4;
int c = n;
int[][] inp = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
inp[i][j] = reader.nextInt();
}
}
boolean hasMoved = true;
while(hasMoved) {
hasMoved = false;
hasMoved = hasMoved || consume(inp, ans);
hasMoved = hasMoved || move2(inp, ans);
}
if(!solved(inp)) {
System.out.println(-1);
return ;
}
System.out.println(ans.size());
for(String aa : ans) {
System.out.println(aa);
}
}
private static boolean solved(int[][] inp) {
for (int i = 1; i < 3; i++) {
for (int j = 0; j < inp[0].length; j++) {
if(inp[i][j] != 0) return false;
}
}
return true;
}
private static boolean consume(int[][] inp, List<String> ans) {
boolean ret = false;
for (int i = 0; i < inp[0].length; i++) {
if(inp[1][i] != 0 && inp[0][i] == inp[1][i]) {
ans.add(inp[1][i] + " " + 1 + " " + (i+1));
inp[1][i] = 0;
ret = true;
}
}
for (int i = 0; i < inp[0].length; i++) {
if(inp[2][i] != 0 && inp[3][i] == inp[2][i]) {
ans.add(inp[2][i] + " " + 4 + " " + (i+1));
inp[2][i] = 0;
ret = true;
}
}
return ret;
}
private static boolean move2(int[][] inp, List<String> ans) {
for (int i = 0; i < inp[0].length - 1; i++) {
if(inp[1][i] != 0 && inp[1][i+1] == 0) {
ans.add(inp[1][i] + " " + 2 + " " + (i+2));
inp[1][i+1] = inp[1][i];
inp[1][i] = 0;
return true;
}
}
if(inp[1][inp[0].length - 1] != 0 && inp[2][inp[0].length - 1] == 0) {
ans.add(inp[1][inp[0].length - 1] + " " + 3 + " " + (inp[0].length));
inp[2][inp[0].length - 1] = inp[1][inp[0].length - 1];
inp[1][inp[0].length - 1] = 0;
return true;
}
if(inp[1][0] == 0 && inp[2][0] != 0) {
ans.add(inp[2][0] + " " + 2 + " " + 1);
inp[1][0] = inp[2][0];
inp[2][0] = 0;
return true;
}
for (int i = 0; i < inp[0].length - 1; i++) {
if(inp[2][i] == 0 && inp[2][i+1] != 0) {
ans.add(inp[2][i+1] + " " + 3 + " " + (i+1));
inp[2][i] = inp[2][i+1];
inp[2][i+1] = 0;
return true;
}
}
return false;
}
}
| Java | ["4 5\n1 2 0 4\n1 2 0 4\n5 0 0 3\n0 5 0 3", "1 2\n1\n2\n1\n2", "1 2\n1\n1\n2\n2"] | 3 seconds | ["6\n1 1 1\n2 1 2\n4 1 4\n3 4 4\n5 3 2\n5 4 2", "-1", "2\n1 1 1\n2 4 1"] | NoteIn the first sample test case, all cars are in front of their spots except car $$$5$$$, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most $$$20000$$$ will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Java 8 | standard input | [] | a8d1a78ae2093d2e0de8e4efcbf940c7 | The first line of the input contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 50$$$, $$$1 \le k \le 2n$$$), representing the number of columns and the number of cars, respectively. The next four lines will contain $$$n$$$ integers each between $$$0$$$ and $$$k$$$ inclusive, representing the initial state of the parking lot. The rows are numbered $$$1$$$ to $$$4$$$ from top to bottom and the columns are numbered $$$1$$$ to $$$n$$$ from left to right. In the first and last line, an integer $$$1 \le x \le k$$$ represents a parking spot assigned to car $$$x$$$ (you can only move this car to this place), while the integer $$$0$$$ represents a empty space (you can't move any car to this place). In the second and third line, an integer $$$1 \le x \le k$$$ represents initial position of car $$$x$$$, while the integer $$$0$$$ represents an empty space (you can move any car to this place). Each $$$x$$$ between $$$1$$$ and $$$k$$$ appears exactly once in the second and third line, and exactly once in the first and fourth line. | 2,100 | If there is a sequence of moves that brings all of the cars to their parking spaces, with at most $$$20000$$$ car moves, then print $$$m$$$, the number of moves, on the first line. On the following $$$m$$$ lines, print the moves (one move per line) in the format $$$i$$$ $$$r$$$ $$$c$$$, which corresponds to Allen moving car $$$i$$$ to the neighboring space at row $$$r$$$ and column $$$c$$$. If it is not possible for Allen to move all the cars to the correct spaces with at most $$$20000$$$ car moves, print a single line with the integer $$$-1$$$. | standard output | |
PASSED | 7cb6e36ba68dd47d5acb40fd654aae8c | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.math.BigInteger;
import java.io.*;
import java.util.*;
public class Main {
int n, k;
String wall[] = new String[2];
int mark[][] = new int[2][100001];
boolean calc() {
TreeSet<Pair<Pair<Integer, Integer>, Integer> > set = new TreeSet<Pair<Pair<Integer, Integer>, Integer>>();
set.add(new Pair<Pair<Integer, Integer>, Integer>(new Pair<Integer, Integer>(0, 0), -1));
while (!set.isEmpty()) {
int y =-set.first().x.x;
int x = set.first().x.y;
int d = set.first().y;
set.remove(set.first());
if (y <= d)
continue;
if (y == n || y + k >= n)
return true;
if (wall[x].charAt(y + 1) == '-' && mark[x][y + 1] == 0) {
mark[x][y + 1] = 1;
set.add(new Pair<Pair<Integer, Integer>, Integer>(new Pair<Integer, Integer>(-(y + 1), x), d + 1));
}
if (y - 1 >= 0 && wall[x].charAt(y - 1) == '-' && mark[x][y - 1] == 0) {
mark[x][y - 1] = 1;
set.add(new Pair<Pair<Integer, Integer>, Integer>(new Pair<Integer, Integer>(-(y - 1), x), d + 1));
}
if (wall[(x + 1)%2].charAt(y + k) == '-' && mark[(x + 1)%2][y + k] == 0) {
mark[(x + 1)%2][y + k] = 1;
set.add(new Pair<Pair<Integer, Integer>, Integer>(new Pair<Integer, Integer>(-(y + k), (x + 1)%2), d + 1));
}
}
return false;
}
public void solve()throws Exception {
n = nextInt();
k = nextInt();
wall[0] = nextString();
wall[1] = nextString();
System.out.println(calc() ? "YES" : "NO");
}
/*
***********************************************************************
*/
PrintWriter writer;
BufferedReader reader;
StringTokenizer stk;
void run()throws Exception {
stk = null;
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt()throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong()throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble()throws Exception {
return Double.parseDouble(nextToken());
}
String nextString()throws Exception {
return nextToken();
}
String nextLine()throws Exception {
return reader.readLine();
}
String nextToken()throws Exception {
if(stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public class Pair<T, U> implements Comparable<Pair<T, U>> {
T x;
U y;
public Pair (){}
public Pair (T x, U y) {
this.x = x;
this.y = y;
}
public Pair<T, U> makePair(T x, U y) {
this.x = x;
this.y = y;
return this;
}
@Override
public int compareTo(Pair<T, U> o) {
int cmp = compare(this.x, o.x);
return (cmp == 0) ? compare(this.y, o.y) : cmp;
}
private int compare(Object o1, Object o2) {
return (o1 == null) ? (o2 == null) ? 0 : -1 : (o2 == null) ? +1 : ((Comparable) o1).compareTo(o2);
}
@Override
public String toString() {
return this.x.toString() + " " + this.y.toString();
}
};
public static void main(String[]args) throws Exception {
new Main().run();
}
} | Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | f0f644eeef85bd00beaabeec4b25dab0 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.StringTokenizer;
public class cf198b {
public static void main(String[] args) {
FastIO in = new FastIO(), out = in;
int n = in.nextInt();
int k = in.nextInt();
char[][] v = new char[2][];
for(int i=0; i<2; i++)
v[i] = in.next().trim().toCharArray();
int[][] dist = new int[2][n];
int oo = 987654321;
for(int[] x : dist) Arrays.fill(x, oo);
dist[0][0] = 0;
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(0); q.add(0);
int[] dx = {0,0,1}, dy = {-1,1,k};
int ans = oo;
while(!q.isEmpty()) {
int cx = q.poll();
int cy = q.poll();
for(int i=0; i<dx.length; i++) {
int nx = (cx+dx[i])%2;
int ny = cy+dy[i];
int nd = dist[cx][cy]+1;
if(ny < nd) continue;
if(ny >= n) {
ans = Math.min(ans,nd);
continue;
}
if(v[nx][ny] == 'X') continue;
if(dist[nx][ny] <= nd) continue;
dist[nx][ny] = nd;
q.add(nx);
q.add(ny);
}
}
if(ans >= oo) out.println("NO");
else out.println("YES");
out.close();
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
this(System.in,System.out);
}
public FastIO(InputStream in, OutputStream out) {
super(new BufferedWriter(new OutputStreamWriter(out)));
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if(!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if(!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 9b961d6d455f05279db33762f522475d | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Yaski
*/
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 {
Cell[] left;
Cell[] right;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
left = new Cell[n];
right = new Cell[n];
String leftS = in.nextLine();
String rightS = in.nextLine();
for (int i = 0; i < n; i++) {
left[i] = (leftS.charAt(i) == '-') ? new Cell(i, 0) : null;
right[i] = (rightS.charAt(i) == '-') ? new Cell(i, 1) : null;
}
// search exit
Queue<Cell> stack = new LinkedList<Cell>();
int index;
Cell child;
Cell element = left[0];
element.used = true;
stack.add(element);
while ((element = stack.poll()) != null) {
// check children
// move up
int water = element.water + 1;
index = element.index + 1;
if (index >= n) {
if (element.water <= element.index) {
out.println("YES");
return;
}
} else {
child = (element.side == 0) ? left[index] : right[index];
if (child != null) {
if (child.used) {
if (water < child.water) {
child.water = water;
stack.add(child);
}
} else {
child.used = true;
child.water = water;
stack.add(child);
}
}
}
// jump
index = element.index + k;
if (index >= n) {
if (element.water <= element.index) {
out.println("YES");
return;
}
} else {
child = (element.side == 0) ? right[index] : left[index];
if (child != null) {
if (child.used) {
if (water < child.water) {
child.water = water;
stack.add(child);
}
} else {
child.used = true;
child.water = water;
stack.add(child);
}
}
}
// move down
index = element.index - 1;
if (index >= 0 && water <= index) {
child = (element.side == 0) ? left[index] : right[index];
if (child != null) {
if (child.used) {
if (water < child.water) {
child.water = water;
stack.add(child);
}
} else {
child.used = true;
child.water = water;
stack.add(child);
}
}
}
}
out.println("NO");
}
}
class Cell {
public int index;
public int side = 0;
public int water = 0;
public boolean used = false;
public Cell(int index, int side) {
this.index = index;
this.side = side;
}
}
class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
tokenizer = null;
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
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 | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 7449cbb6e2a50d1e8705e4ff2a37d2d6 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args) {
long time_beg = -1;
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
if (args.length > 0 && args[0].equals("outside")) {
time_beg = System.currentTimeMillis();
try {
inputStream = new FileInputStream("io/in.txt");
// outputStream = new FileOutputStream("io/out.txt");
} catch (Exception e) {
System.err.println(e);
System.exit(1);
}
} else {
// try {
// inputStream = new FileInputStream("file_name");
// outputStream = new FileOutputStream("file_name");
// } catch (Exception e) {
// System.err.println(e);
// System.exit(1);
// }
}
Solver s = new Solver();
s.in = new InputReader(inputStream);
s.out = new OutputWriter(outputStream);
s.solve();
s.out.close();
if (args.length > 0 && args[0].equals("outside")) {
System.err.printf("*** Total time: %.3f ***\n", (System.currentTimeMillis() - time_beg) / 1000.0);
}
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void printLine(char[] array) {
writer.println(array);
}
public void printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
}
class Solver {
InputReader in;
OutputWriter out;
void solve() {
n = in.readInt();
k = in.readInt();
W = new String[2];
W[0] = in.readLine();
W[1] = in.readLine();
Q = new Vertex[2 * n + 10];
was = new int[2][2 * n + 10];
for (int j = 0; j < 2; ++j)
for (int i = 0; i < n + 10; ++i)
was[j][i] = -1;
if (bfs(new Vertex(0, 0))) out.printLine("YES");
else out.printLine("NO");
}
int n, k;
String[] W;
Vertex[] Q;
int[][] was;
boolean bfs(Vertex v) {
was[v.f][v.p] = 0;
int lo = 0, hi = 0;
Q[hi++] = v;
while (lo < hi) {
v = Q[lo++];
if (was[v.f][v.p] >= v.p + 1) continue;
if (v.p + k >= n) return true;
if (was[v.f][v.p + 1] == -1 && W[v.f].charAt(v.p + 1) == '-') {
was[v.f][v.p + 1] = was[v.f][v.p] + 1;
Q[hi++] = new Vertex(v.f, v.p + 1);
}
if (v.p > 0 && was[v.f][v.p - 1] == -1 && W[v.f].charAt(v.p - 1) == '-') {
was[v.f][v.p - 1] = was[v.f][v.p] + 1;
Q[hi++] = new Vertex(v.f, v.p - 1);
}
if (was[v.f ^ 1][v.p + k] == -1 && W[v.f ^ 1].charAt(v.p + k) == '-') {
was[v.f ^ 1][v.p + k] = was[v.f][v.p] + 1;
Q[hi++] = new Vertex(v.f ^ 1, v.p + k);
}
}
return false;
}
class Vertex {
int f, p;
Vertex(int f, int p) {
this.f = f;
this.p = p;
}
}
} | Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | f36dd7dd634c109f601fc23e3472c74f | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class JumpingOnWalls {
static Scanner in = new Scanner(System.in);
public static void main(String[] args){
new JumpingOnWalls().DFS();
}
private void DFS(){
int n = in.nextInt();
int k = in.nextInt();
char[] left = new char[n];
char[] right = new char[n];
left = in.next().toCharArray();
right = in.next().toCharArray();
char[][] wall = new char[2][n];
wall[0] = left;
wall[1] = right;
int[][] visited = new int[2][n];
for(int i=0;i<2;i++){
for(int j=0;j<n;j++){
visited[i][j] = 0;
}
}
Queue<Position> q = new LinkedList<JumpingOnWalls.Position>();
q.add(new Position(0, 0, 0));
while(!q.isEmpty()){
Position p = q.poll();
int s = p.side;
int po = p.pos;
int b = p.bottom;
if(po >= n){
System.out.println("YES");
return;
}
if(wall[s][po]=='X' || visited[s][po]==1 || po<b){
continue;
}
visited[s][po] = 1;
if(po>0){
q.add(new Position(s, po-1, b+1));
}
q.add(new Position(s, po+1, b+1));
q.add(new Position(1-s, po+k, b+1));
}
System.out.println("NO");
}
class Position{
int side;
int pos;
int bottom;
public Position(int side, int pos, int bottom){
this.side = side;
this.pos = pos;
this.bottom = bottom;
}
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | ff3ffded32935e5648e29f83965deff5 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | //package com.yaroslav.shlapak;
import java.util.Scanner;
/**
* Created by y.shlapak on Apr 05, 2016.
*/
/*
7 3
---X--X
-X--XX-
*/
public class JumpingOnWalls {
static int n, k;
static int[][] tunnel;
static int[][] tunnelClone;
static int waterLevel = 0;
static boolean done = false;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
k = scanner.nextInt();
tunnel = new int[n + k + 1][2];
tunnelClone = new int[n + k + 1][2];
String leftString = scanner.next();
String rightString = scanner.next();
for(int i = 0; i < leftString.length(); i++) {
tunnel[i][0] = leftString.charAt(i) == 'X' ? 1 : 0;
tunnel[i][1] = rightString.charAt(i) == 'X' ? 1 : 0;
//tunnelClone[i][0] = n + 1;
//tunnelClone[i][1] = n + 1;
}
/*
for(int i = 0; i < n; i++) {
System.out.print("" + tunnel[i][0]);
}
System.out.println();
for(int i = 0; i < n; i++) {
System.out.print("" + tunnel[i][1]);
}
System.out.println();
*/
int level = 0;
int waterLevel = 0;
int side = 0; //left
/*int[] temp;
Queue queue = new Queue(n * 2);
moveQueue(level, waterLevel, side, queue);
while(!queue.isEmpty()) {
if(done) {
break;
}
temp = queue.pop();
level = temp[0];
side = temp[1];
waterLevel = temp[2];
moveQueue(level, side, waterLevel, queue);
}*/
move(level, side, waterLevel);
if(done) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
private static void moveQueue(int level, int side, int waterLevel, Queue queue) {
//System.out.println("" + level + " " + side);
if(done) {
return;
}
if(level + k > n ) {
done = true;
return;
}
if(tunnel[level + k][side == 0 ? 1 : 0] == 0 && tunnelClone[level + k][side == 0 ? 1 : 0] == 0) {
tunnelClone[level + k][side == 0 ? 1 : 0] = 1;
queue.push(level + k, side == 0 ? 1 : 0, waterLevel + 1);
}
if(tunnel[level + 1][side] == 0 && tunnelClone[level + 1][side] == 0) {
tunnelClone[level + 1][side] = 1;
queue.push(level + 1, side, waterLevel + 1);
}
if(level > 0 && tunnel[level - 1][side] == 0 && waterLevel + 1 <= level - 1 && tunnelClone[level - 1][side] == 0) {
tunnelClone[level - 1][side] = 1;
queue.push(level - 1, side, waterLevel + 1);
}
}
private static void move(int level, int side, int waterLevel) {
//System.out.println("" + level + " " + side);
if(done) {
return;
}
if(level + k > n ) {
done = true;
return;
}
if(tunnel[level + k][side == 0 ? 1 : 0] == 0 && tunnelClone[level + k][side == 0 ? 1 : 0] == 0) {
tunnelClone[level + k][side == 0 ? 1 : 0] = 1;
move(level + k, side == 0 ? 1 : 0, waterLevel + 1);
}
if(tunnel[level + 1][side] == 0 && tunnelClone[level + 1][side] == 0) {
tunnelClone[level + 1][side] = 1;
move(level + 1, side, waterLevel + 1);
}
if(level > 0 && tunnel[level - 1][side] == 0 && waterLevel + 1 <= level - 1 && tunnelClone[level - 1][side] == 0) {
tunnelClone[level - 1][side] = 1;
move(level - 1, side, waterLevel + 1);
}
}
private static class Queue {
private int size;
private int front;
private int back;
private int[][] queue;
public Queue(int size) {
this.size = size;
queue = new int[size][3];
front = back = 0;
}
public void push(int level, int side, int waterLevel) {
if(back < size) {
queue[back][0] = level;
queue[back][1] = side;
queue[back][2] = waterLevel;
back++;
}
}
public int[] pop() {
if(front <= back) {
return queue[front++];
} else {
return new int[]{-1, -1, -1};
}
}
public int getSize() {
return this.size;
}
public boolean isEmpty() {
return front == back;
}
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | ad042a1b822c0c6e22a862661957d4b1 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | //package com.yaroslav.shlapak;
import java.util.Scanner;
/**
* Created by y.shlapak on Apr 05, 2016.
*/
/*
7 3
---X--X
-X--XX-
*/
public class JumpingOnWalls {
static int n, k;
static int[][] tunnel;
static int[][] tunnelClone;
static int waterLevel = 0;
static boolean done = false;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
k = scanner.nextInt();
tunnel = new int[n + k + 1][2];
tunnelClone = new int[n + k + 1][2];
String leftString = scanner.next();
String rightString = scanner.next();
for(int i = 0; i < leftString.length(); i++) {
tunnel[i][0] = leftString.charAt(i) == 'X' ? 1 : 0;
tunnel[i][1] = rightString.charAt(i) == 'X' ? 1 : 0;
//tunnelClone[i][0] = n + 1;
//tunnelClone[i][1] = n + 1;
}
/*
for(int i = 0; i < n; i++) {
System.out.print("" + tunnel[i][0]);
}
System.out.println();
for(int i = 0; i < n; i++) {
System.out.print("" + tunnel[i][1]);
}
System.out.println();
*/
int level = 0;
int waterLevel = 0;
int side = 0; //left
int[] temp;
Queue queue = new Queue(n * 2);
moveQueue(level, waterLevel, side, queue);
while(!queue.isEmpty()) {
if(done) {
break;
}
temp = queue.pop();
level = temp[0];
side = temp[1];
waterLevel = temp[2];
moveQueue(level, side, waterLevel, queue);
}
//move(level, side, waterLevel);
if(done) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
private static void moveQueue(int level, int side, int waterLevel, Queue queue) {
//System.out.println("" + level + " " + side);
if(done) {
return;
}
if(level + k > n ) {
done = true;
return;
}
if(tunnel[level + k][side == 0 ? 1 : 0] == 0 && tunnelClone[level + k][side == 0 ? 1 : 0] == 0) {
tunnelClone[level + k][side == 0 ? 1 : 0] = 1;
queue.push(level + k, side == 0 ? 1 : 0, waterLevel + 1);
}
if(tunnel[level + 1][side] == 0 && tunnelClone[level + 1][side] == 0) {
tunnelClone[level + 1][side] = 1;
queue.push(level + 1, side, waterLevel + 1);
}
if(level > 0 && tunnel[level - 1][side] == 0 && waterLevel + 1 <= level - 1 && tunnelClone[level - 1][side] == 0) {
tunnelClone[level - 1][side] = 1;
queue.push(level - 1, side, waterLevel + 1);
}
}
private static void move(int level, int side, int waterLevel) {
//System.out.println("" + level + " " + side);
if(done) {
return;
}
if(level + k > n ) {
done = true;
return;
}
if(tunnel[level + k][side == 0 ? 1 : 0] == 0 && tunnelClone[level + k][side == 0 ? 1 : 0] >= waterLevel + 1) {
tunnelClone[level + k][side == 0 ? 1 : 0] = waterLevel + 1;
move(level + k, side == 0 ? 1 : 0, waterLevel + 1);
}
if(tunnel[level + 1][side] == 0 && tunnelClone[level + 1][side] >= waterLevel + 1) {
tunnelClone[level + 1][side] = waterLevel + 1;
move(level + 1, side, waterLevel + 1);
}
if((tunnel[level + k][side == 0 ? 1 : 0] != 0 && tunnel[level + 1][side] != 0) && level > 0 && tunnel[level - 1][side] == 0 && waterLevel + 1 <= level - 1 && tunnelClone[level - 1][side] >= waterLevel + 1) {
tunnelClone[level - 1][side] = waterLevel + 1;
move(level - 1, side, waterLevel + 1);
}
}
private static class Queue {
private int size;
private int front;
private int back;
private int[][] queue;
public Queue(int size) {
this.size = size;
queue = new int[size][3];
front = back = 0;
}
public void push(int level, int side, int waterLevel) {
if(back < size) {
queue[back][0] = level;
queue[back][1] = side;
queue[back][2] = waterLevel;
back++;
}
}
public int[] pop() {
if(front <= back) {
return queue[front++];
} else {
return new int[]{-1, -1, -1};
}
}
public int getSize() {
return this.size;
}
public boolean isEmpty() {
return front == back;
}
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 7d44c58cd2c448ffac358e101e98995c | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.util.*;
import java.io.*;
public class B125 {
public static void main(String[] args) throws IOException
{
input.init(System.in);
int n = 2, m = input.nextInt(), x = input.nextInt();
char[][] grid = new char[n][m];
for(int i = 0; i<n; i++) grid[i] = input.next().toCharArray();
boolean res = false;
Queue<Integer> qi = new LinkedList<Integer>(), qj = new LinkedList<Integer>();
qi.add(0);
qj.add(0);
int[] di = new int[]{0, 0, 1, -1};
int[] dj = new int[]{1, -1, x, x};
int[][] ds = new int[n][m];
for(int[] A : ds) Arrays.fill(A, 987654321);
ds[0][0] = 0;
while(!qi.isEmpty())
{
int ati = qi.poll(), atj = qj.poll();
//System.out.println(ati+" "+atj);
for(int k = 0; k<4; k++)
{
int ni = ati + di[k], nj = atj + dj[k];
if(ni < 0 | ni >= n || nj < 0) continue;
if(nj >= m)
{
res = true;
break;
}
//System.out.println(ni+" "+nj);
int nd = ds[ati][atj] + 1;
if(nd >= ds[ni][nj] || nd > nj || grid[ni][nj] == 'X') continue;
ds[ni][nj] = nd;
qi.add(ni);
qj.add(nj);
}
}
System.out.println(res ? "YES" : "NO");
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 68b363d191a7a72b71c1645428b6cb55 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.Closeable;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collection;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.Queue;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
ExtendedPrintWriter out = new ExtendedPrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, QuickScanner in, ExtendedPrintWriter out) {
int height = in.nextInt();
int jumpHeight = in.nextInt();
char[][] wall = in.next2DCharArray(2);
int[][] firstVisitedTime = new int[2][height];
ArrayUtils.fill(firstVisitedTime, -1);
Queue<Pair<Integer, Integer>> queue = new ArrayDeque<Pair<Integer, Integer>>();
queue.offer(Pair.makePair(0, 0));
firstVisitedTime[0][0] = 0;
while (!queue.isEmpty()) {
int side = queue.peek().first;
int position = queue.poll().second;
int currentTime = firstVisitedTime[side][position];
{
int nextSide = side;
int nextPosition = position + 1;
if (nextPosition >= currentTime + 1) {
if (nextPosition >= height) {
out.println("YES");
return;
}
if (wall[nextSide][nextPosition] == '-') {
if (firstVisitedTime[nextSide][nextPosition] == -1) {
firstVisitedTime[nextSide][nextPosition] = currentTime + 1;
queue.offer(Pair.makePair(nextSide, nextPosition));
}
}
}
}
{
int nextSide = side;
int nextPosition = position - 1;
if (nextPosition >= currentTime + 1) {
if (nextPosition >= height) {
out.println("YES");
return;
}
if (wall[nextSide][nextPosition] == '-') {
if (firstVisitedTime[nextSide][nextPosition] == -1) {
firstVisitedTime[nextSide][nextPosition] = currentTime + 1;
queue.offer(Pair.makePair(nextSide, nextPosition));
}
}
}
}
{
int nextSide = 1 - side;
int nextPosition = position + jumpHeight;
if (nextPosition >= currentTime + 1) {
if (nextPosition >= height) {
out.println("YES");
return;
}
if (wall[nextSide][nextPosition] == '-') {
if (firstVisitedTime[nextSide][nextPosition] == -1) {
firstVisitedTime[nextSide][nextPosition] = currentTime + 1;
queue.offer(Pair.makePair(nextSide, nextPosition));
}
}
}
}
}
out.println("NO");
}
}
class QuickScanner implements Iterator<String>, Closeable {
BufferedReader reader;
StringTokenizer tokenizer;
boolean endOfFile = false;
public QuickScanner(InputStream inputStream){
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = null;
}
public boolean hasNext() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
checkNext();
} catch (NoSuchElementException ignored) {
}
}
return !endOfFile;
}
private void checkNext() {
if (endOfFile) {
throw new NoSuchElementException();
}
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
endOfFile = true;
throw new NoSuchElementException();
}
}
public String next() {
checkNext();
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
public int nextInt() {
return Integer.parseInt(next());
}
public char[] nextCharArray() {
return next().toCharArray();
}
public char[][] next2DCharArray(int n) {
char[][] result = new char[n][];
for (int i = 0; i < n; i++) {
result[i] = nextCharArray();
}
return result;
}
public void close() {
try {
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class ExtendedPrintWriter extends PrintWriter {
public ExtendedPrintWriter(Writer out) {
super(out);
}
public ExtendedPrintWriter(OutputStream out) {
super(out);
}
}
class ArrayUtils {
private ArrayUtils() {
}
public static void fill(int[][] array, int val) {
for (int[] subArray : array) {
Arrays.fill(subArray, val);
}
}
}
class Pair<A,B> implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A, B> Pair<A, B> makePair(A first, B second) {
return new Pair<A, B>(first, second);
}
public int compareTo(Pair<A, B> anotherPair) {
int result = ((Comparable<A>)first).compareTo(anotherPair.first);
if (result != 0) {
return result;
}
return ((Comparable<B>)second).compareTo(anotherPair.second);
}
public int hashCode() {
int result = 17;
if (first != null) {
result = 37 * result + first.hashCode();
}
if (second != null) {
result = 37 * result + second.hashCode();
}
return result;
}
public String toString() {
return "(" + first + ", " + second + ")";
}
public boolean equals(Object obj) {
try {
return this.first.equals(((Pair<A, B>) obj).first) &&
this.second.equals(((Pair<A, B>) obj).second);
} catch (ClassCastException e) {
return false;
}
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 38534fdebe1af5b4f2a4d0a3d4ca121c | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class B implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
Random rnd;
String[] walls = new String[2];
int[][] distances = new int[2][];
final int inf = Integer.MAX_VALUE / 2;
Queue<State> q = new ArrayDeque<B.State>();
final int[] dxs = {1, -1};
class State {
int wall, x;
public State(int wall, int x) {
this.wall = wall;
this.x = x;
}
}
void solve() throws IOException {
int n = nextInt(), k = nextInt();
for(int i = 0; i < 2; i++) {
walls[i] = nextToken();
distances[i] = new int[n];
Arrays.fill(distances[i], inf);
}
distances[0][0] = 0;
q.add(new State(0, 0));
boolean ok = false;
while(q.size() > 0) {
State cur = q.poll();
int nd = distances[cur.wall][cur.x] + 1;
for(int dx : dxs) {
int nwall = cur.wall, nx = cur.x + dx;
if(nx >= n) {
ok = true;
} else if(nx >= 0 && nx < n && nx >= nd && distances[nwall][nx] > nd && walls[nwall].charAt(nx) == '-') {
distances[nwall][nx] = nd;
q.add(new State(nwall, nx));
}
}
{
int nwall = 1 - cur.wall, nx = cur.x + k;
if(nx >= n) {
ok = true;
} else if(nx >= 0 && nx < n && nx >= nd && distances[nwall][nx] > nd && walls[nwall].charAt(nx) == '-') {
distances[nwall][nx] = nd;
q.add(new State(nwall, nx));
}
}
}
out.println(ok ? "YES" : "NO");
}
public static void main(String[] args) {
new B().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
rnd = new Random();
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(42);
}
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 2e1b67449b7d7b730ba5df7747cc6c31 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 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.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class JumpingonWalls {
static int n, k;
static char[][] s;
static String bfs() {
int[][] d = new int[2][n];
for (int[] a : d)
Arrays.fill(a, -1);
d[0][0] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(0);
q.add(0);
while (!q.isEmpty()) {
int x = q.poll();
int y = q.poll();
if (y + k >= n)
return "YES";
if (d[x][y] > y)
return "NO";
if (s[1 - x][y + k] == '-' && 1 + d[x][y] <= y + k
&& d[1 - x][y + k] == -1) {
d[1 - x][y + k] = 1 + d[x][y];
q.add(1 - x);
q.add(y + k);
}
if (s[x][y + 1] == '-' && 1 + d[x][y] <= y + 1 && d[x][y + 1] == -1) {
d[x][y + 1] = 1 + d[x][y];
q.add(x);
q.add(y + 1);
}
if (y - 1 > -1 && s[x][y - 1] == '-' && 1 + d[x][y] <= y - 1
&& d[x][y - 1] == -1) {
d[x][y - 1] = 1 + d[x][y];
q.add(x);
q.add(y - 1);
}
}
return "NO";
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new StringTokenizer("");
n = nxtInt();
k = nxtInt();
s = new char[2][n];
for (int i = 0; i < 2; i++)
s[i] = nxtCharArr();
out.println(bfs());
br.close();
out.close();
}
static BufferedReader br;
static StringTokenizer sc;
static PrintWriter out;
static String nxtTok() throws IOException {
while (!sc.hasMoreTokens()) {
String s = br.readLine();
if (s == null)
return null;
sc = new StringTokenizer(s.trim());
}
return sc.nextToken();
}
static int nxtInt() throws IOException {
return Integer.parseInt(nxtTok());
}
static long nxtLng() throws IOException {
return Long.parseLong(nxtTok());
}
static double nxtDbl() throws IOException {
return Double.parseDouble(nxtTok());
}
static int[] nxtIntArr(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nxtInt();
return a;
}
static long[] nxtLngArr(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nxtLng();
return a;
}
static char[] nxtCharArr() throws IOException {
return nxtTok().toCharArray();
}
} | Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | c5aa5b1ccc8ea49c9951cab209d7a9cc | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.*;
import java.util.*;
public class BFS_2 {
public static void main(String[] args) {
Scanner util = new Scanner(System.in);
int n = util.nextInt();
int k = util.nextInt();
util.nextLine();
boolean[][] walls = new boolean[2][n];
for(int i = 0; i < 2; i++) {
String in = util.nextLine();
for(int j = 0; j < n; j++)
if(in.charAt(j) == '-')
walls[i][j] = true;
else
walls[i][j] = false;
}
boolean check = false;
Queue<Pair> queue = new LinkedList<Pair>();
HashSet<Pair> visited = new HashSet<Pair>();
Pair origin = new Pair(0, 0);
queue.add(origin);
while(!queue.isEmpty()) {
Pair out = queue.remove();
if(out.y < 0)
continue;
else if(out.y >= n) {
check = true;
break;
}
else if(visited.contains(out))
continue;
// System.out.println(out.x + " " + out.y + " " + out.height);
visited.add(out);
if(!visited.contains(new Pair(out.x, out.y + 1, out.height + 1))) {
Pair toAdd = new Pair(out.x, out.y + 1, out.height + 1);
if(toAdd.y >= n ||
(toAdd.y < n && walls[toAdd.x][toAdd.y] &&
!visited.contains(toAdd)))
queue.add(toAdd);
}
if(out.y > 0 && !visited.contains(new Pair(out.x, out.y - 1, out.height + 1))) {
Pair toAdd = new Pair(out.x, out.y - 1, out.height + 1);
if(walls[toAdd.x][toAdd.y] && !visited.contains(toAdd) &&
toAdd.height < toAdd.y)
queue.add(toAdd);
}
if(out.x == 1) {
if(!visited.contains(new Pair(0, out.y + k, out.height + 1))) {
Pair toAdd = new Pair(0, out.y + k, out.height + 1);
if(toAdd.y >= n ||
(toAdd.y < n && walls[toAdd.x][toAdd.y] &&
!visited.contains(toAdd)))
queue.add(toAdd);
}
}
else {
if(!visited.contains(new Pair(1, out.y + k, out.height + 1))) {
Pair toAdd = new Pair(1, out.y + k, out.height + 1);
if(toAdd.y >= n ||
(toAdd.y < n && walls[toAdd.x][toAdd.y] &&
!visited.contains(toAdd)))
queue.add(toAdd);
}
}
}
if(check)
System.out.println("YES");
else
System.out.println("NO");
}
}
class Pair {
public int x, y, height;
public Pair (int x, int y) {
this.x = x;
this.y = y;
height = -1;
}
public Pair (int x, int y, int z) {
this.x = x;
this.y = y;
height = z;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Pair))
return false;
Pair other = (Pair)obj;
if(other.x == x && other.y == y)
return true;
return false;
}
@Override
public int hashCode() {
String nah = (this.x) + " " + (this.y);
return nah.hashCode();
}
} | Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 1c1e0884cf4f1edb58a0e2be96fce0e8 | train_001.jsonl | 1340379000 | Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question. | 256 megabytes | import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class Point {
public int x,y,step;
public Point(int x, int y, int step) {
this.x = x;
this.y = y;
this.step = step;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), k =in.nextInt();in.nextLine();
char[][] way = new char[2][];
way[0] = in.nextLine().toCharArray();
way[1] = in.nextLine().toCharArray();
boolean[][] used = new boolean[2][n];
//used[0] = new boolean[]
Queue<Point> q = new LinkedList<Point>();
Point current;
q.add(new Point(0, 0, 0));
boolean find = false;
while (!q.isEmpty()) {
current = q.poll();
if (current.y+k>=n) {
find = true;
break;
} else {
if (way[current.x][current.y+1]=='-') {
if (!used[current.x][current.y+1]) {
used[current.x][current.y+1] = true;
q.add(new Point(current.x, current.y+1, current.step+1));
}
}
if (current.y+k<n &&
way[(current.x+1)%2][current.y+k]=='-') {
if (!used[(current.x+1)%2][current.y+k]) {
used[(current.x+1)%2][current.y+k] = true;
q.add(new Point((current.x+1)%2, current.y+k, current.step+1));
}
}
if (current.y-1>-1 &&
way[current.x][current.y-1]=='-' &&
current.step<current.y-1)
{
if (!used[current.x][current.y-1]) {
used[current.x][current.y-1]=true;
q.add(new Point(current.x, current.y-1, current.step+1));
}
}
}
}
out.println(find?"YES":"NO");
in.close();
out.close();
}
}
| Java | ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"] | 2 seconds | ["YES", "NO"] | NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon. | Java 7 | standard input | [
"dfs and similar",
"shortest paths"
] | e95bde11483e05751ee7da91a6b4ede1 | The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous. | 1,400 | Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes). | standard output | |
PASSED | 679119e187e882e42e94c0287f12a431 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.util.Scanner;
public class Main {
FastScanner in;
PrintWriter out;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
if (st == null || !st.hasMoreTokens())
return br.readLine();
StringBuilder result = new StringBuilder(st.nextToken());
while (st.hasMoreTokens()) {
result.append(" ");
result.append(st.nextToken());
}
return result.toString();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
void run() throws IOException {
in = new FastScanner(System.in);
out = new PrintWriter(System.out, false);
solve();
out.close();
}
public static void main(String[] args) throws IOException{
new Main().run();
}
public void solve() throws IOException{
int n = in.nextInt();
int[] primes = new int[1000001];
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
int p = 2;
while(p != 1000001){
while(p != 1000001 && primes[p] == 1) p++;
if(p == 1000001) break;
map.put( new Long(p) * new Long(p), 1);
int fac = 1;
while(p * fac <= 1000000){
primes[p * fac] = 1;
fac++;
}
p++;
}
for(int i = 0; i < n; i++){
String str = in.next();
long num = Long.parseLong(str);
if(map.containsKey(num)){
out.println("YES");
}else{
out.println("NO");
}
}
return;
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 65dd9b0fe49c7bc5c58276a2139a1fab | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class SNT_3 {
static int n;
static int nMAX = 1000006;
static boolean[] f = new boolean[nMAX+1];
static void sNT() {
for (int i = 0; i <= nMAX; i++) {
f[i] = true;
}
f[0] = false;
f[1] = false;
for (int i = 2; i <= nMAX; i++) {
if (f[i]) {
for (int j = 2 * i; j <= nMAX ; j+=i) {
f[j] = false;
}
}
}
}
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
sNT();
n = sc.nextInt();
for(int i = 0 ; i < n ; i++){
long b = sc.nextLong();
double c = Math.sqrt(b);
int d = (int)Math.sqrt(b);
if(f[d] && c - d == 0){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 707ce35780e8ed3a3708607496b99b7f | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.io.*;
import java.util.*;
public class main {
static StringBuilder out=new StringBuilder();
static FastReader in=new FastReader();
static boolean primes[];
public static void getArrPrimes(int n){
primes=new boolean[n+1];
Arrays.fill(primes, true);
primes[1]=false;
for(int i=2;i*i<n;i++){
if(!primes[i])continue;
for(int j=i*i;j<=n;j+=i){
primes[j]=false;
}
}
}
public static void main(String []args){
getArrPrimes(1000000);
int t=in.nextInt();
while(t-->0){
long n=in.nextLong();
long r=(long)Math.sqrt(n);
boolean dec=false;
if(r*r==n)dec=primes[(int)r];
out.append(dec?"YES\n":"NO\n");
}
System.out.println(out);
}
public static boolean isPrime(long n){
long i=2;
while(i<=(long)Math.sqrt(n)){
if(n%i==0)return false;
i++;
}
return true;
}
public static int[] getIntArray(int n){
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=in.nextInt();
}
return arr;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | fa8134539ca394aa24f8942c347b93ad | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.Scanner;
public class Tprimes {
private static Scanner s = new Scanner(System.in);
static long LIMIT =1000001;
static long i,j;
static long[] prime= new long[1000001];
private static void primelist(){
prime[0]=1; prime[1]=1;
for( i = 2; i< LIMIT; i++){
if(prime[(int) i]==0){
for( j = i*i; j< LIMIT; j+=i){
prime[(int) j]=1;
}
}
}
}
private static boolean perfectsquare(long n){
double sq = Math.sqrt(n);
if( sq - Math.floor(sq) == 0)
return true;
return false;
}
public static void main(String[] args) {
primelist();
long n = s.nextLong();
for (int m = 0; m < n; m++) {
long x = s.nextLong();
if(x==4){
System.out.println("YES");
}else if(x%2 == 0){
System.out.println("NO");
}else if ( perfectsquare(x) && prime[(int) Math.sqrt(x)] == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 89bae4babea536e26936c350b34f2187 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Tprime {
public static void isprime(boolean[] dp) {
for (int p = 2; p * p < 1000001; p++) {
if (dp[p] == true) {
for (int i = p * p; i < 1000001; i += p) {
dp[i] = false;
}
}
}
}
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]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException {
Reader in = new Reader();
int n = in.nextInt();
boolean[] dp = new boolean[1000001];
Arrays.fill(dp, Boolean.TRUE);
isprime(dp);
for (int i = 0; i < n; i++) {
Long a = in.nextLong();
if (a == 1) {
System.out.println("NO");
continue;
}
double root = Math.sqrt(a);
if ((root == (int) root)) {
if ((dp[(int)root] == true)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}else{
System.out.println("NO");
}
}
}
}
| Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 427d630b95ea13fdc4db3809c67eedb9 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.*;
import java.io.*;
public class TPrimesB{
public static boolean[] sieveOfEratosthenes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
int limit = (int)Math.sqrt(n);
for (int p = 2; p <= limit; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
prime[1] = false;
return prime;
}
public static boolean[] primes;
public static String algorithm(long k){
double checkOne = Math.sqrt(k);
if ((int)checkOne == checkOne){
int l = (int)checkOne;
if (primes[l]){
return "YES";
}else{
return "NO";
}
}else{
return "NO";
}
}
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
Random rd = new Random();
out = new PrintWriter(new BufferedOutputStream(System.out));
//long startTime = System.nanoTime();
primes = sieveOfEratosthenes(1000000);
//String output = "";
while (n > 0){
out.println(algorithm(sc.nextLong()));
//out.println(algorithm(rd.nextInt()));
//output += algorithm(rd.nextInt()) + "\n";
//output += algorithm(sc.nextLong()) + "\n";
n--;
}
// out.println(output.substring(0,output.length()-1));
//long newTime = System.nanoTime() - startTime;
//out.println("Total execution time in ms: " + (double)newTime/1000000);
out.close();
}
//DO NOT TOUCH!!! QUIK INPUT / OUTPUT AREA ONLY:
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 390782a4fbb0aa7823d01b132ee2b770 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | /*input
3
4 5 6
*/
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class problem230b{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(in.readLine());
String[] input = in.readLine().split(" ");
boolean[] pr = new boolean[10000005];
for(int i=2;i<=1000;i++){
for (int j=i*i;j<=1000000;j+=i){
pr[j] = true;
}
}
for(int i=0;i<a;++i){
double n = Double.parseDouble(input[i]);
boolean z = true;
if(n == 1){
System.out.println("NO");
continue;
}
double p = Math.sqrt(n);
if((int) p == p && !pr[(int) p])
System.out.println("YES");
else
System.out.println("NO");
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | c12c0aa5baf2d984c29c4eecd6a56da1 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{ static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main(String args[]) throws java.lang.Exception
{
Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
long x=sc.nextLong();
long root=(long)Math.sqrt(x);
if(root*root==x)
{
if(prime(root))
out.println("YES");
else
out.println("NO");
}
else
out.println("NO");
out.flush();
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 96fd3a26b05157a30d97d5f7d8af13ef | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.*;
import java.io.*;
public class Code230 {
public static void main(String[] args) {
FastReader sc = new FastReader();
boolean[] prime = gneratePrime(1000000);
int t = sc.nextInt();
while(t-->0){
double n = sc.nextDouble();
System.out.println(isTprime(n, prime));
}
}
public static String isTprime(double n, boolean[] prime){
double sr = Math.sqrt(n);
if((sr - Math.floor(sr)) != 0)
return "NO";
else if(prime[(int)sr])
return "YES";
return "NO";
}
public static boolean[] gneratePrime(int n){
boolean[] prime = new boolean[n+1];
for (int i = 2; i <= n; i++){
prime[i] = true;
}
for (int i = 2; i <= Math.sqrt(n); i++){
if(prime[i] == true){
for (int j = i*i ; j <= n; j += i){
prime[j] = false;
}
}
}
return prime;
}
public static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 1d4433bcc2d2d9647de954c56971cb22 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.*;
public class Tprime{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
long[] arr = new long[n];
for(int i = 0;i<n;i++){
arr[i] = scan.nextLong();
}
boolean[] prime = new boolean[1000001];
for(int i = 2;i<=1000000;i++){
prime[i] = true;
}
prime[0] = prime[1] = false;
for(int i = 2;i<=1000000;i++){
if(prime[i]){
long j = i;
while(j*i<=1000000){
prime[(int)j*i] = false;
j++;
}
}
}
for(int i = 0;i<n;i++){
long num = arr[i];
long sq = (long)Math.sqrt(num);
if((long)Math.pow(sq,2) == num){
if(prime[(int)sq]){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
else{
System.out.println("NO");
}
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | deecc17fc3a9014986c78b3905ecf3e7 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.Scanner;
public class CodeForces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean[] arr = new boolean[1000000];
for (int j = 0; j < arr.length; j++) {
arr[j] = true;
}
for (int k = 2; k < Math.sqrt(arr.length); k++) {
if (arr[k]) {
for (int j = k * k; j < arr.length; j += k) {
arr[j] = false;
}
}
}
long[] array = new long[n];
for (int i = 0; i < array.length; i++) {
array[i] = sc.nextLong();
}
for (int i = 0; i < n; i++) {
if (array[i] == 1) {
System.out.println("NO");
continue;
}
double sqrt = Math.sqrt(array[i]);
if (sqrt == (int) sqrt && (int) sqrt < arr.length && arr[(int) sqrt]) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 2333366256a73c6e643f7fffe6c90b82 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class CodeForces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean[] arr = new boolean[1000000];
for (int j = 0; j < arr.length; j++) {
arr[j] = true;
}
for (int k = 2; k < Math.sqrt(arr.length); k++) {
if (arr[k]) {
for (int j = k * k; j < arr.length; j += k) {
arr[j] = false;
}
}
}
long[] array = new long[n];
for (int i = 0; i < array.length; i++) {
array[i] = sc.nextLong();
}
for (int i = 0; i < n; i++) {
if (array[i] == 1) {
System.out.println("NO");
continue;
}
double sqrt = Math.sqrt(array[i]);
if (sqrt == (int) sqrt && (int) sqrt < arr.length && arr[(int) sqrt]) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | a0ca77aa20023a6a31230c64c90b9b86 | train_001.jsonl | 1349105400 | We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class CodeForces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean[] arr = new boolean[1000000];
for (int j = 0; j < arr.length; j++) {
arr[j] = true;
}
for (int k = 2; k < Math.sqrt(arr.length); k++) {
if (arr[k]) {
for (int j = k * k; j < arr.length; j += k) {
arr[j] = false;
}
}
}
long[] array = new long[n];
for (int i = 0; i < array.length; i++) {
array[i] = sc.nextLong();
}
for (int i = 0; i < n; i++) {
//long a = sc.nextLong();
if (array[i] == 1) {
System.out.println("NO");
continue;
}
double sqrt = Math.sqrt(array[i]);
if (sqrt == (int) sqrt && (int) sqrt < arr.length && arr[(int) sqrt]) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | Java | ["3\n4 5 6"] | 2 seconds | ["YES\nNO\nNO"] | NoteThe given test has three numbers. The first number 4 has exactly three divisors — 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO". | Java 11 | standard input | [
"binary search",
"number theory",
"implementation",
"math"
] | 6cebf9af5cfbb949f22e8b336bf07044 | The first line contains a single positive integer, n (1 ≤ n ≤ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≤ xi ≤ 1012). Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is advised to use the cin, cout streams or the %I64d specifier. | 1,300 | Print n lines: the i-th line should contain "YES" (without the quotes), if number xi is Т-prime, and "NO" (without the quotes), if it isn't. | standard output | |
PASSED | 17ff8d71296f0cada2b60f5a3db6ef9f | train_001.jsonl | 1318919400 | Three sons inherited from their father a rectangular corn fiend divided into n × m squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, which is why he bequeathed to divide his field into three parts containing A, B and C tons of corn.The field should be divided by two parallel lines. The lines should be parallel to one side of the field and to each other. The lines should go strictly between the squares of the field. Each resulting part of the field should consist of at least one square. Your task is to find the number of ways to divide the field as is described above, that is, to mark two lines, dividing the field in three parts so that on one of the resulting parts grew A tons of corn, B on another one and C on the remaining one. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static boolean FROM_FILE = true;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
if (FROM_FILE) {
try {
br = new BufferedReader(new FileReader("input.txt"));
} catch (IOException error) {
}
} else {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int countArray (int[] arr, int a, int b) {
int len = arr.length - 1, cnt = 0;
for (int i = 1; i <= len - 2; i += 1) {
for (int j = i + 1; j <= len - 1; j += 1) {
if (arr[i] == a && arr[j] - arr[i] == b) {
cnt += 1;
}
}
}
return cnt;
}
public static void main(String[] args) {
FastReader fr = new FastReader();
PrintWriter out = null;
if (FROM_FILE) {
try {
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException error) {
}
} else {
out = new PrintWriter(new OutputStreamWriter(System.out));
}
int n = fr.nextInt(), m = fr.nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i += 1) {
for (int j = 0; j < m; j += 1) {
matrix[i][j] = fr.nextInt();
}
}
int a = fr.nextInt(), b = fr.nextInt(), c = fr.nextInt();
int[] rows = new int[m + 1];
for (int j = 0; j < m; j += 1) {
rows[j + 1] = rows[j];
for (int i = 0; i < n; i += 1) {
rows[j + 1] += matrix[i][j];
}
}
if (rows[m] != a + b + c) {
out.println(0); out.flush();
return;
}
int[] cols = new int[n + 1];
for (int i = 0; i < n; i += 1) {
cols[i + 1] = cols[i];
for (int j = 0; j < m; j += 1) {
cols[i + 1] += matrix[i][j];
}
}
int cnt = 0;
if (a == b && b == c) {
cnt += countArray(rows, a, b) + countArray(cols, a, b);
} else {
if (a == b) {
cnt += countArray(rows, a, b) + countArray(cols, a, b);
cnt += countArray(rows, a, c) + countArray(cols, a, c);
cnt += countArray(rows, c, a) + countArray(cols, c, a);
} else if (b == c) {
cnt += countArray(rows, b, c) + countArray(cols, b, c);
cnt += countArray(rows, a, b) + countArray(cols, a, b);
cnt += countArray(rows, b, a) + countArray(cols, b, a);
} else if (a == c) {
cnt += countArray(rows, a, c) + countArray(cols, a, c);
cnt += countArray(rows, a, b) + countArray(cols, a, b);
cnt += countArray(rows, b, a) + countArray(cols, b, a);
} else {
cnt += countArray(rows, a, b) + countArray(cols, a, b);
cnt += countArray(rows, b, a) + countArray(cols, b, a);
cnt += countArray(rows, a, c) + countArray(cols, a, c);
cnt += countArray(rows, c, a) + countArray(cols, c, a);
cnt += countArray(rows, b, c) + countArray(cols, b, c);
cnt += countArray(rows, c, b) + countArray(cols, c, b);
}
}
out.println(cnt);
out.flush();
}
} | Java | ["3 3\n1 1 1\n1 1 1\n1 1 1\n3 3 3", "2 5\n1 1 1 1 1\n2 2 2 2 2\n3 6 6", "3 3\n1 2 3\n3 1 2\n2 3 1\n5 6 7"] | 1 second | ["2", "3", "0"] | NoteThe lines dividing the field can be horizontal or vertical, but they should be parallel to each other. | Java 11 | input.txt | [
"brute force"
] | ef162ba7ca860369cf950d9a3686ddc8 | The first line contains space-separated integers n and m — the sizes of the original (1 ≤ n, m ≤ 50, max(n, m) ≥ 3). Then the field's description follows: n lines, each containing m space-separated integers cij, (0 ≤ cij ≤ 100) — the number of tons of corn each square contains. The last line contains space-separated integers A, B, C (0 ≤ A, B, C ≤ 106). | 1,400 | Print the answer to the problem: the number of ways to divide the father's field so that one of the resulting parts contained A tons of corn, another one contained B tons, and the remaining one contained C tons. If no such way exists, print 0. | output.txt | |
PASSED | 677f0b9f1a9f75d5efd51fc1b81340b1 | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes |
import java.util.HashMap;
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int no = 0;
for (int i = 0; i < n; i++) {
if (a[i] == i) no++;
else map.put(i, a[i]);
}
boolean flag = false;
for (int k : map.keySet()) {
if (k == map.get(map.get(k))) flag = true;
}
if (no == n) System.out.println(n);
else if (!flag) System.out.println(no + 1);
else System.out.println(no + 2);
}
}
| Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | bd6efa86c7c5c94f077a29b7311f77fc | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] nums = new int[N];
for (int i = 0; i < N; i++)
nums[i] = Integer.parseInt(st.nextToken());
int cnt = 0;
boolean ok = false;
for (int i = 0; i < N; i++)
if (nums[i] == i)
cnt++;
else if (nums[nums[i]] == i)
ok = true;
if (cnt < N) {
if (ok)
cnt += 2;
else
cnt++;
}
System.out.println(cnt);
}
}
| Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | 3b5962eb14f379bb14c90d5ebc4089c6 | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes | import java.util.LinkedList;
import java.util.Scanner;
public class Contest201_div2_B
{
public static void main(String ... args)
{
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int[] n = new int[row];
LinkedList<Integer> fn = new LinkedList<Integer>();
int noOfFp = 0;
for(int i=0; i<row; ++i)
{
n[i] = in.nextInt();
if(n[i]==i) ++noOfFp;
else fn.add(i);
}
if(!fn.isEmpty()) ++noOfFp;
for(int f : fn)
{
if(n[n[f]]==f)
{
++noOfFp;
break;
}
}
System.out.println(noOfFp);
}
}
| Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | e0f9d114e656d59935334c875bf9c883 | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class B {
static BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws Exception {
int n = readInt();
int[] perm = new int[n];
int[] pos = new int[n];
for (int i = 0; i < n; i++) {
int val = readInt();
perm[i] = val;
pos[val] = i;
}
int fixpoints = 0;
int best = 0;
for (int i = 0; i < n; i++) {
int val = perm[i];
if (val == i) {
fixpoints++;
}
else if (perm[val] == i) {
best = 2;
}
else {
best = Math.max(best, 1);
}
}
System.out.println(fixpoints + best);
}
static String readString() throws Exception {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(stdin.readLine());
}
return st.nextToken();
}
static int readInt() throws Exception {
return Integer.parseInt(readString());
}
static long readLong() throws Exception {
return Long.parseLong(readString());
}
static double readDouble() throws Exception {
return Double.parseDouble(readString());
}
} | Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | 28b1f3075b865293f7d1257d73b51419 | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes |
import java.util.Scanner;
public class B {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int a[] = new int[n];
for(int i = 0;i < n;i++){
a[i] = input.nextInt();
}
int flag = 0;
int fixedCount = 0;
for(int i = 0;i < n;i++){
if(a[i] == i){
fixedCount ++;
}else{
if(flag == 2){
continue;
}
if(a[a[i]] == i){
flag = 2;
}else{
flag = 1;
}
}
}
fixedCount += flag;
System.out.println(fixedCount);
}
}
| Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | baf6dbd196f848a110d7f6f79488b351 | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes | //package pack;
import java.util.Scanner;
public class Training {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] v = new int[100009];
int cont = 0;
for(int i = 0 ;i < n ; i++)
{
v[i] = sc.nextInt();
if (v[i] == i) cont ++;
}
int flag = 0;
for (int j = 0; j < n;j++)
{
if (v[j] != j && v[v[j]] == j )
{
cont += 2;
flag = 1;
break;
}
}
if (flag == 0)
{
for (int j = 0; j < n;j++)
{
if (v[j] != j && v[v[j]] != v[j] )
{
cont += 1;
flag = 1;
break;
}
}
}
System.out.println(cont);
}
}
| Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | cdd4497bd248a6f3994565ce4dee42f5 | train_001.jsonl | 1379691000 | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class B {
private static BufferedReader in;
private static StringTokenizer st;
private static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int a[] = new int[n];
int ans = 0;
boolean used[] = new boolean[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
if(a[i] == i){
ans++;
}
}
for (int i = 0; i < n; i++) {
if(a[i] != i){
if(a[a[i]]==i){
ans+=2;
System.out.println(ans);
return;
}
}
}
if(ans < n)
ans++;
System.out.println(ans);
}
static String next() throws IOException{
while(!st.hasMoreTokens()){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
static int nextInt() throws NumberFormatException, IOException{
return Integer.parseInt(next());
}
static long nextLong() throws NumberFormatException, IOException{
return Long.parseLong(next());
}
static double nextDouble() throws NumberFormatException, IOException{
return Double.parseDouble(next());
}
}
| Java | ["5\n0 1 3 4 2"] | 2 seconds | ["3"] | null | Java 6 | standard input | [
"implementation",
"brute force",
"math"
] | e63de0fffd00b2da103545a7f1e405be | The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation. | 1,100 | Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation. | standard output | |
PASSED | 557cbdf1f8cd38816ffff05a2d00d691 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader();
public static void main(String[] args) throws Exception {
int n = in.nextInt();
long[] a = new long[n];
for(int i=0;i<n;i++) a[i] = in.nextLong();
Arrays.sort(a);
long[] b = new long[n];
long[] c = new long[n];
int cidx = 0;
for(int i=0;i<n;i+=2) b[i] = a[cidx++];
for(int i=1;i<n;i+=2) b[i] = a[cidx++];
cidx = 0;
for(int i=1;i<n;i+=2) c[i] = a[cidx++];
for(int i=0;i<n;i+=2) c[i] = a[cidx++];
int bc = 0, cc = 0;
for(int i=1;i<n-1;i++) {
if(b[i]<b[i-1]&&b[i]<b[i+1])++bc;
if(c[i]<c[i-1]&&c[i]<c[i+1])++cc;
}
if(bc > cc) {
System.out.println(bc);
for(long i:b) System.out.print(i+" ");
System.out.println();
} else {
System.out.println(cc);
for(long i:c) System.out.print(i+" ");
System.out.println();
}
}
}
interface Input {
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String nextLine() throws IOException;
String next() throws IOException;
int nextInt() throws IOException;
long nextLong() throws IOException;
}
class InputReader implements Input {
StringTokenizer zer = null;
public String nextLine() throws IOException {
return br.readLine();
}
public String next() throws IOException {
while(zer == null || !zer.hasMoreTokens()) zer = new StringTokenizer(br.readLine());
return zer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 65657a80c5829f4e9573ccb7b6806d5d | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.*;
import java.util.*;
public class D_671_1 {
static int p=1000000007;
public static void main(String[] args) throws Exception{
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);
FastReader sc=new FastReader();
// long k = sc.nextLong();
int n=sc.nextInt();
String inp[]=sc.nextLine().split(" ");
Integer ar[]=new Integer[n];
HashMap<Integer,Integer> h1=new HashMap<>();
for(int i=0;i<n;i++)
{
ar[i]=Integer.parseInt(inp[i]);
h1.put(ar[i],h1.getOrDefault(ar[i],0)+1);
}
Arrays.sort(ar);
int sm=-1,lm=-1;
int res[]=new int[n];
int i=0;
int j=n/2;
StringBuilder sb=new StringBuilder();
for(int k=0;k<n;k++)
{
if(k%2==0)
res[k]=ar[j+i];
else
res[k]=ar[i++];
sb.append(res[k]+" ");
}
int c=0;
for(i=1;i+1<n;i++)
{
if(res[i-1]>res[i]&&res[i+1]>res[i])
c++;
}
System.out.println(c);
System.out.println(sb.toString());
// out.write(sb.toString());
out.flush();
}
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | f0655d3262f675e117a2a4f607be9e92 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;import java.io.*;import java.math.*;
public class Birthday
{
public static void process()throws IOException
{
int n = ni();
int[] a = nai(n);
ruffleSort(a);
int c = 0, total = 0;
int[] ans = new int[n];
for(int i = 1; i < n-1; i+=2){
ans[i] = a[c];
a[c] = -1;
c++;
}
if(n%2 == 0){
ans[n-1] = a[c];
a[c] = -1;
}
c = 0;
for(int i = 0; i < n; i++){
if(a[i] != -1){
ans[c] = a[i];
c += 2;
if(c == n)
c--;
}
}
for(int i = 1; i < n-1; i++){
if(ans[i] < ans[i-1] && ans[i] < ans[i+1])
total++;
}
pn(total);
for(int i : ans)
p(i+" ");
pn("");
}
static AnotherReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
long s = System.currentTimeMillis();
int t=1;
//t=ni();
while(t-->0) {process();}
out.flush();
System.err.println(System.currentTimeMillis()-s+"ms");
out.close();
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);out.flush();}
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static double nd()throws IOException{return sc.nextDouble();}
static String nln()throws IOException{return sc.nextLine();}
static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
static long power(long k, long c, long mod){
long y = 1;
while(c > 0){
if(c%2 == 1)
y = y * k % mod;
c = c/2;
k = k * k % mod;
}
return y;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class AnotherReader{BufferedReader br; StringTokenizer st;
AnotherReader()throws FileNotFoundException{
br=new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(int a)throws FileNotFoundException{
br = new BufferedReader(new FileReader("input.txt"));}
String next()throws IOException{
while (st == null || !st.hasMoreElements()) {try{
st = new StringTokenizer(br.readLine());}
catch (IOException e){ e.printStackTrace(); }}
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{ String str = ""; try{
str = br.readLine();} catch (IOException e){
e.printStackTrace();} return str;}}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | d35803e1de9e24e187a180c9b0ecde10 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.io.*;
public class D2
{
public static void main(String args[]) throws IOException
{
// BufferedReader br = new BufferedReader(new FileReader("input.txt"));
// BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n, a[], i, o, e, c, p[];
String inp[];
n = Integer.parseInt(br.readLine());
inp = br.readLine().split(" ");
a = new int[n];
p = new int[n];
for(i = 0; i < n; i++)
a[i] = Integer.parseInt(inp[i]);
Arrays.sort(a);
o = n/2;
c = 0;
for(i = 0, e = 0; i < n; i++)
{
if(i%2 == 0)
{
p[i] = a[o];
o++;
}
else
{
p[i] = a[e];
if(o != n && a[o] > a[e] && a[o-1] > a[e])
c++;
e++;
}
}
bw.write(c + "\n");
for(i = 0; i < n; i++)
bw.write(p[i] + " ");
bw.flush();
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 4c252722f9b69e39d4eccef1cfe91761 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<n;i++)
list.add(sc.nextInt());
Collections.sort(list);
int arr[]=new int[n];
int in=-1;
for(int i=0,j=list.size()/2,k=0;k<list.size();k++)
{
if(k%2!=0)
arr[++in]=list.get(i++);
else
arr[++in]=list.get(j++);
}
int cntr=0;
for(int i=1;i<n-1;i++)
{
if(arr[i]<arr[i-1]&&arr[i]<arr[i+1])
cntr++;
}
System.out.println(cntr);
for(int i:arr)
System.out.print(i+" ");
/*int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int k=sc.nextInt();
int arr[]=new int[n];
int cnt=0,neg=0,pos=0;
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
if(arr[i]==k)
cnt++;
else if(arr[i]>k)
neg+=arr[i]-k;
else
pos+=k-arr[i];
}
if(cnt==n)
System.out.println(0);
else if(pos==neg)
System.out.println(1);
else
{
System.out.println(pos);
if((pos+neg)%2==0)
System.out.println(2);
else
System.out.println(3);
}
}*/
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | c51d0bc16c5ef7ecd171ee26e1d91f77 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
long[] x = new long[n];
for(int i=0;i<n;i++)
x[i] = sc.nextLong();
Arrays.sort(x);
long[] ans = new long[n];
int j=0;
for(int i=1;i<n;i+=2)
ans[i] = x[j++];
for(int i=0;i<n;i+=2)
ans[i] = x[j++];
long a=0;
for(int i=1;i<n-1;i++){
if(ans[i-1]>ans[i]&& ans[i]<ans[i+1])
a++;
}
System.out.println(a);
for(int i=0;i<n;i++)
System.out.print(ans[i]+" ");
System.out.println();
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 2e799db950208272f82ed12b8e3b326b | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;
public class Hellojava
{
public static void main(String[] args)
{
FastScanner fs=new FastScanner();
int n=fs.nextInt();
int[] ar=fs.readArray(n);
int[] res=new int[n];
Arrays.sort(ar);
int indx=0;
for(int i=1;i<n;i+=2)
res[i]=ar[indx++];
for(int i=0;i<n;i+=2)
res[i]=ar[indx++];
int ans=0;
for(int i=1;i<n;i+=2)
{
if(i+1<n && res[i-1]>res[i] && res[i+1]>res[i])
ans++;
}
System.out.println(ans);
for(int i=0;i<n;i++)
System.out.print(res[i]+" ");
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | ac76ee68bfa8d07bca73ff82e3f14ebd | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static ArrayList<Integer> adj[];
// static PrintWriter out = new PrintWriter(System.out);
static int[][] notmemo;
static int k;
static int[] a;
static int b[];
static int m;
static class Pair implements Comparable<Pair> {
int c;
int d;
public Pair(int b, int l) {
c = b;
d = l;
}
@Override
public int compareTo(Pair o) {
return o.d-this.d;
}
}
static Pair s1[];
static ArrayList<Pair> adjlist[];
// static char c[];
public static long mod = (long) (1e9 + 7);
static int V;
static long INF = (long) 1E16;
static int n;
static char c[];
static int d[];
static int z;
static Pair p[];
static int R;
static int C;
static int K;
static long grid[][];
static Scanner sc = new Scanner(System.in);
static int x[];
static int y[];
static PrintWriter out = new PrintWriter(System.out);
public static void main(String args[]) throws Exception {
int n=sc.nextInt();
int a[]=readarray(n);
sortarray(a);
int hi=(int) (n);
int low=0;
int ans=0;
if(n>2)
while(hi>=low) {
int mid=(hi+low)>>1;
PriorityQueue<Integer> small=new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue<Integer> big=new PriorityQueue(Collections.reverseOrder());
for (int i = 0; i <mid; i++) {
small.add(a[i]);
}
for (int i = mid; i < a.length; i++) {
big.add(a[i]);
}
boolean f=true;
int count=0;
int c=big.poll();
while(!small.isEmpty()&&!big.isEmpty()) {
int a1=small.poll();
int b=big.poll();
if(a1<b&&a1<c) {
count++;
}
c=b;
}
if(count==mid) {
low=mid+1;
ans=mid;
}
else
hi=mid-1;
}
out.println(ans);
PriorityQueue<Integer> small=new PriorityQueue<Integer>(Collections.reverseOrder());
PriorityQueue<Integer> big=new PriorityQueue(Collections.reverseOrder());
for (int i = 0; i <ans; i++) {
small.add(a[i]);
}
for (int i = ans; i < a.length; i++) {
big.add(a[i]);
}
boolean f=true;
out.print(big.poll()+" ");
while(!small.isEmpty()||big.size()>0) {
if(!small.isEmpty()) {
int a1=small.poll();
int b=big.poll();
out.print(a1+" "+b+" ");
}
else
out.print(big.poll()+" ");
}
out.flush();
}
static long div4[];
static int s[];
static long dp(int sum) {
if(sum==n)
return 1;
if(sum>n)
return 0;
if(div4[sum]!=-1)
return div4[sum];
long ans=0;
for (int i = 0; i < s.length; i++) {
if(sum+s[i]>n)
break;
ans+=(dp(sum+s[i])%998244353);
ans%=998244353;
}
return div4[sum]=ans;
}
static TreeSet<Integer> ts=new TreeSet();
static HashMap<Integer, Integer> compress(int a[]) {
ts = new TreeSet<>();
HashMap<Integer, Integer> hm = new HashMap<>();
for (int x : a)
ts.add(x);
for (int x : ts) {
hm.put(x, hm.size() + 1);
}
return hm;
}
static class FenwickTree { // one-based DS
int n;
int[] ft;
FenwickTree(int size) { n = size; ft = new int[n+1]; }
int rsq(int b) //O(log n)
{
int sum = 0;
while(b > 0) { sum += ft[b]; b -= b & -b;} //min?
return sum;
}
int rsq(int a, int b) { return rsq(b) - rsq(a-1); }
void point_update(int k, int val) //O(log n), update = increment
{
while(k <= n) { ft[k] += val; k += k & -k; } //min?
}
}
static ArrayList<Integer> euler=new ArrayList<>();
static ArrayList<Integer> arr;
static int[] total;
static TreeMap<Integer,Integer> map1;
static int zz;
//static int dp(int idx,int left,int state) {
//if(idx>=k-((zz-left)*2)||idx+1==n) {
// return 0;
//}
//if(memo[idx][left][state]!=-1) {
// return memo[idx][left][state];
//}
//int ans=a[idx+1]+dp(idx+1,left,0);
//if(left>0&&state==0&&idx>0) {
// ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1));
//}
//return memo[idx][left][state]=ans;
//}21
static HashMap<Integer,Integer> map;
static int maxa=0;
static int ff=123123;
static long[][] memo;
static long modmod=998244353;
static int dx[]= {1,-1,0,0};
static int dy[]= {0,0,1,-1};
static class BBOOK implements Comparable<BBOOK>{
int t;
int alice;
int bob;
public BBOOK(int x,int y,int z) {
t=x;
alice=y;
bob=z;
}
@Override
public int compareTo(BBOOK o) {
return this.t-o.t;
}
}
private static long lcm(long a2, long b2) {
return (a2*b2)/gcd(a2,b2);
}
static class Edge implements Comparable<Edge>
{
int node;long cost ; long time;
Edge(int a, long b,long c) { node = a; cost = b; time=c; }
public int compareTo(Edge e){ return Long.compare(time,e.time); }
}
static void sieve(int N) // O(N log log N)
{
isComposite = new int[N+1];
isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number
primes = new ArrayList<Integer>();
for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N))
if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance
{
primes.add(i);
if(1l * i * i <= N)
for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve
isComposite[j] = 1;
}
}
static TreeSet<Integer> factors;
static ArrayList<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N))
{
ArrayList<Integer> factors = new ArrayList<Integer>(); //take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while(1l*p * p <= N)
{
while(N % p == 0) { factors.add(p); N /= p; }
p = primes.get(++idx);
}
if(N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static class UnionFind {
int[] p, rank, setSize;
int numSets;
int max[];
public UnionFind(int N) {
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
}
public int findSet(int i) {
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public int chunion(int i,int j, int x2) {
if (isSameSet(i, j))
return 0;
numSets--;
int x = findSet(i), y = findSet(j);
int z=findSet(x2);
p[x]=z;;
p[y]=z;
return x;
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
setSize[x] += setSize[y];
} else {
p[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y])
rank[y]++;
}
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
static class Quad implements Comparable<Quad> {
int u;
int v;
char state;
int turns;
public Quad(int i, int j, char c, int k) {
u = i;
v = j;
state = c;
turns = k;
}
public int compareTo(Quad e) {
return (int) (turns - e.turns);
}
}
static long manhatandistance(long x, long x2, long y, long y2) {
return Math.abs(x - x2) + Math.abs(y - y2);
}
static long fib[];
static long fib(int n) {
if (n == 1 || n == 0) {
return 1;
}
if (fib[n] != -1) {
return fib[n];
} else
return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod);
}
static class Point implements Comparable<Point>{
long x, y;
Point(long counth, long counts) {
x = counth;
y = counts;
}
@Override
public int compareTo(Point p )
{
return Long.compare(p.y*1l*x, p.x*1l*y);
}
}
static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N))
{
TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers
int idx = 0, p = primes.get(idx);
while (p * p <= N) {
while (N % p == 0) {
factors.add((long) p);
N /= p;
}
if (primes.size() > idx + 1)
p = primes.get(++idx);
else
break;
}
if (N != 1) // last prime factor may be > sqrt(N)
factors.add(N); // for integers whose largest prime factor has a power of 1
return factors;
}
static boolean visited[];
/**
* static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>();
* q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0;
* while(!q.isEmpty()) {
*
* int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) {
* maxcost=Math.max(maxcost, v.cost);
*
*
*
* if(!visited[v.v]) {
*
* visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost,
* v.cost); } }
*
* } return maxcost; }
**/
static boolean[] vis2;
static boolean f2 = false;
static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x
// r)
{
long[][] C = new long[p][r];
for (int i = 0; i < p; ++i) {
for (int j = 0; j < r; ++j) {
for (int k = 0; k < q; ++k) {
C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod;
C[i][j] %= mod;
}
}
}
return C;
}
public static int[] schuffle(int[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
int temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static boolean vis[];
static HashSet<Integer> set = new HashSet<Integer>();
static long modPow(long ways, long count, long mod) // O(log e)
{
ways %= mod;
long res = 1;
while (count > 0) {
if ((count & 1) == 1)
res = (res * ways) % mod;
ways = (ways * ways) % mod;
count >>= 1;
}
return res % mod;
}
static long gcd(long l, long o) {
if (o == 0) {
return l;
}
return gcd(o, l % o);
}
static int[] isComposite;
static int[] valid;
static ArrayList<Integer> primes;
static ArrayList<Integer> l1;
static TreeSet<Integer> primus = new TreeSet<Integer>();
static void sieveLinear(int N)
{
int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i
for(int i = 2; i <= N; ++i)
{
if(lp[i] == 0)
{
primus.add(i);
lp[i] = i;
}
int curLP = lp[i];
for(int p: primus)
if(p > curLP || p * i > N)
break;
else
lp[p * i] = i;
}
}
public static long[] schuffle(long[] a2) {
for (int i = 0; i < a2.length; i++) {
int x = (int) (Math.random() * a2.length);
long temp = a2[x];
a2[x] = a2[i];
a2[i] = temp;
}
return a2;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
public int[] nxtArr(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
}
public static int[] sortarray(int a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
public static long[] sortarray(long a[]) {
schuffle(a);
Arrays.sort(a);
return a;
}
public static int[] readarray(int n) throws IOException {
int a[]=new int[n];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextInt();
}
return a;
}
public static long[] readlarray(int n) throws IOException {
long a[]=new long[n];
for (int i = 0; i < a.length; i++) {
a[i]=sc.nextLong();
}
return a;
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 94bd1cfbdf2a03b9f4410f2d612e5d5e | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.*;
import java.util.*;
public class d2671 implements Runnable
{
private boolean console=false;
public void solve()
{
int i;
int n=in.ni();
Integer a[]=new Integer[n];
for(i=0;i<n;i++)
a[i]=in.ni();
if(n<=2)
{
out.println(0);
for(i=0;i<n;i++)
out.print(a[i]+" ");
return;
}
Arrays.sort(a);
int ans[]=new int[n];
int l=0; int last=-1;
for(i=1;i<n-1;i+=2)
{
last=i;
ans[i]=a[l++];
}
int r=n-1;
for(i=last+1;i>=0;i-=2)
{
ans[i]=a[r--];
}
for(i=0;i<n;i++)
{
if(ans[i]==0)
ans[i]=a[l++];
}
int val=0;
for(i=1;i<n-1;i++)
{
if(ans[i]<ans[i-1]&&ans[i]<ans[i+1])
val++;
}
out.println(val);
for(i=0;i<n;i++)
out.print(ans[i]+" ");
}
@Override
public void run() {
try { init(); }
catch (FileNotFoundException e) { e.printStackTrace(); }
int t= 1;
while (t-->0) {
solve();
out.flush(); }
}
private FastInput in; private PrintWriter out;
public static void main(String[] args) throws Exception { new d2671().run(); }
private void init() throws FileNotFoundException {
InputStream inputStream = System.in; OutputStream outputStream = System.out;
try { if (!console && System.getProperty("user.name").equals("sachan")) {
outputStream = new FileOutputStream("/home/sachan/Desktop/output.txt");
inputStream = new FileInputStream("/home/sachan/Desktop/input.txt"); }
} catch (Exception ignored) { }
out = new PrintWriter(outputStream); in = new FastInput(inputStream);
}
static class FastInput { InputStream obj;
public FastInput(InputStream obj) { this.obj = obj; }
byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0;
int readByte() { if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) { ptrbuffer = 0;
try { lenbuffer = obj.read(inbuffer); }
catch (IOException e) { throw new InputMismatchException(); } }
if (lenbuffer <= 0) return -1;return inbuffer[ptrbuffer++]; }
String ns() { int b = skip();StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { sb.appendCodePoint(b);b = readByte(); }return sb.toString();}
int ni() { int num = 0, b;boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') { minus = true;b = readByte(); }
while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else {
return minus ? -num : num; }b = readByte(); }}
long nl() { long num = 0;int b;boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') { minus = true;b = readByte(); }
while (true) { if (b >= '0' && b <= '9') { num = num * 10L + (b - '0'); } else {
return minus ? -num : num; }b = readByte(); } }
boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); }
int skip() { int b;while ((b = readByte()) != -1 && isSpaceChar(b)) ;return b; }
float nf() {return Float.parseFloat(ns());}
double nd() {return Double.parseDouble(ns());}
char nc() {return (char) skip();}
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 9ad1cab54bf1bc511bab343b85a5a54d | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
public class Main12{
static public void main(String args[])throws IOException{
int tt=1;
StringBuilder sb=new StringBuilder();
for(int ttt=1;ttt<=tt;ttt++){
int n=i();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=i();
}
a=sort(a);
if(n%2==1){
int mark=n/2;
int count=0;
int[] b=new int[n];
for(int i=0;i<n;i+=2){
b[i]=a[mark];
mark++;
}
mark=0;
for(int i=1;i<n;i+=2){
b[i]=a[mark];
mark++;
}
for(int i=0;i<n;i++){
if(i-1>=0 && i+1<n && b[i-1]>b[i] && b[i]<b[i+1]){
count++;
}
}
sb.append(count+"\n");
for(int i=0;i<n;i++){
sb.append(b[i]+" ");
}
sb.append("\n");
}else{
int mark=n/2;
int count=0;
int[] b=new int[n];
for(int i=0;i<n;i+=2){
b[i]=a[mark];
mark++;
}
mark=0;
for(int i=1;i<n;i+=2){
b[i]=a[mark];
mark++;
}
for(int i=0;i<n;i++){
if(i-1>=0 && i+1<n && b[i-1]>b[i] && b[i]<b[i+1]){
count++;
}
}
sb.append(count+"\n");
for(int i=0;i<n;i++){
sb.append(b[i]+" ");
}
sb.append("\n");
}
}
System.out.print(sb.toString());
}
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
static ArrayList<ArrayList<Integer>> graph;
static int mod=1000000007;
static class Pair{
int x;
int y;
Pair(int x,int y){
this.x=x;
this.y=y;
}
/*@Override
public int hashCode()
{
final int temp = 14;
int ans = 1;
ans =x*31+y*13;
return (int)ans;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
Pair other = (Pair)o;
if (this.x != other.x || this.y!=other.y) {
return false;
}
return true;
}*/
}
public static long[] sort(long[] a){
int n=a.length;
ArrayList<Long> ar=new ArrayList<>();
for(int i=0;i<a.length;i++){
ar.add(a[i]);
}
Collections.sort(ar);
for(int i=0;i<n;i++){
a[i]=ar.get(i);
}
return a;
}
public static int[] sort(int[] a){
int n=a.length;
ArrayList<Integer> ar=new ArrayList<>();
for(int i=0;i<a.length;i++){
ar.add(a[i]);
}
Collections.sort(ar);
for(int i=0;i<n;i++){
a[i]=ar.get(i);
}
return a;
}
public static long pow(long a, long b){
long result=1;
while(b>0){
if (b % 2 != 0){
result=(result*a);
b--;
}
a=(a*a);
b /= 2;
}
return result;
}
public static long gcd(long a, long b){
if (a == 0){
return b;
}
return gcd(b%a, a);
}
public static long lcm(long a, long b){
return a*(b/gcd(a,b));
}
public static long l(){
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value){
System.out.println(value);
}
public static int i(){
return in.Int();
}
public static String s(){
return in.String();
}
}
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 Int() {
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 String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 4b54bf2ec14e5020f17e5cde10e03119 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.lang.*;
public class d1 extends PrintWriter {
static BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
// static Scanner s=new Scanner(System.in);
d1 () { super(System.out); }
public static void main(String[] args) throws IOException{
d1 d1=new d1 ();d1.main();d1.flush();
}
void main() throws IOException {
BufferedReader s = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb = new StringBuffer();
StringBuffer sb1 = new StringBuffer();
PrintWriter out = new PrintWriter(System.out);
// Scanner s=new Scanner(System.in);
String[] s1=s();
int n=i(s1[0]);
String[] s2=s();
long[] a=new long[n];
for(int i=0;i<n;i++){
a[i]=i(s2[i]);
}
if(n==1){
System.out.println(0);
System.out.println(a[0]);
System.exit(0);
}
int j=0;Arrays.sort(a);
int last=n/2-1;int ans=0;
for(int i=n/2;i<n;i++){
if(j==last){
if(n%2==0){
sb.append(a[n-1]+" "+a[j]);
}else{
if(a[j]<a[i]&&a[j]<a[i+1]) ans++;
sb.append(a[i]+" "+a[j]+" ");
}
break;
}else{
if(a[j]<a[i]&&a[j]<a[i+1]){ans++;
sb.append(a[i]+" "+a[j++]+" ");
}else{
sb.append(a[i]+" "+a[last--]+" " );
}
}
}if(n%2!=0) sb.append(a[n-1]);
System.out.println(ans);
System.out.println(sb);
}
long[] st;
void buildtree(int i,int s,int e,long[] a){
if(s==e){
st[i]=a[s];
return;
}
int mid=(s+e)/2;
buildtree(2*i,s,mid,a);
buildtree(2*i+1,mid+1,e,a);
st[i]=Math.min(st[2*i],st[2*(i)+1]);
}
long query(int i,int s,int e,int qs,int qe){
if(qs>e||qe<s) return Integer.MIN_VALUE;
if(s>=qs&&e<=qe) return st[i];
int mid=(s+e)/2;
long l=query(2*i,s,mid,qs,qe);
long r=query(2*i+1,mid+1,e,qs,qe);
return Math.max(l,r);
}
void pointupdate(int i,int s,int e,int qi,long ht){
if(s==e){
st[i]=ht;return;
}
int mid=(s+e)/2;
if(qi<=mid) pointupdate(2*i,s,mid,qi,ht);
else pointupdate(2*(i)+1,mid+1,e,qi,ht);
st[i]=Math.max(st[2*i],st[2*i+1]);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static String[] s() throws IOException {
return s.readLine().trim().split("\\s+");
}
static int i(String ss) {
return Integer.parseInt(ss);
}
static long l(String ss) {
return Long.parseLong(ss);
}
}
class Student {
int l;long r;
public Student(int l, long r) {
this.l = l;
this.r = r;
}
public String toString()
{
return this.l+" ";
}
}
class Pair {
int a,b,h;
public Pair(int a,int b,int h){
this.a=a;this.b=b ;this.h=h;
}
}
class Sortbyroll implements Comparator<Student> {
public int compare(Student a, Student b){
if(a.r<b.r) return -1;
else if(a.r==b.r){
if(a.r==b.r){
return 0;
}
if(a.r<b.r) return -1;
return 1;}
return 1; }
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 3ea4ce9b84692c0d909d6d448d71f786 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args){
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static final long mxx = (long)(1e18 + 5);
static final int mxN = (int)(1e6);
static final int mxV = (int)(1e6), log = 18;
static long mod = (long)(1e9+7); //998244353;//̇
static final int INF = (int)1e9;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, k, q;
static char[]str;
static Long[]dp;
public static void solve() throws Exception {
// solve the problem here
s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
// out = new PrintWriter("output.txt");
int tc = 1;//s.nextInt();
for(int i=1; i<=tc; i++) {
// out.print("Case #" + i + ": ");
testcase();
}
out.flush();
out.close();
}
static void testcase() {
n = s.nextInt();
Integer[] a = s.nextIntegerArray(n);
Arrays.parallelSort(a);
ArrayList<Integer> small = new ArrayList<Integer>(), large = new ArrayList<Integer>();
for(int i=0; i<n/2; i++)small.add(a[i]);
for(int i=n/2; i<n; i++)large.add(a[i]);
Integer[] ans = new Integer[n];
for(int i=1; i<n; i+=2)ans[i] = small.get((i-1) / 2);
for(int i=0; i<n; i+=2)ans[i] = large.get(i/2);
int count = 0;
for(int i=1; i<n-1; i+=2) {
if(ans[i-1] > ans[i] && ans[i] < ans[i+1])count++;
}
out.println(count);
for(Integer x : ans)out.print(x + " ");
out.println();
}
public static PrintWriter out;
public static MyScanner s;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
int[] nextIntArray(int n){
int[]a = new int[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextlongArray(int n) {
long[]a = new long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
Integer[] nextIntegerArray(int n){
Integer[]a = new Integer[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[]a = new Long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
char[][] next2DCharArray(int n, int m){
char[][]arr = new char[n][m];
for(int i=0; i<n; i++) {
arr[i] = this.next().toCharArray();
}
return arr;
}
ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
return adj;
}
ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
}
return adj;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 91d380deb9480528f7bcc29b2628a61f | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.*;
import java.util.*;
public class A
{
static int n, x;
static int[] arr;
public static void main(String[] args) throws IOException
{
Flash f = new Flash();
n = f.ni(); arr = f.arr(n);
fn();
}
static void fn()
{
if(n == 1){
System.out.println("0");
System.out.println(arr[0]);
return;
}
sort(arr);
int[] ans = new int[n];
int j = 1;
for(int i = 0; i < n; i++){
ans[j] = arr[i];
if(j+2 < n) j += 2;
else j = 0;
}
int out = 0;
for(int i = 1; i < n-1; i++){
if(ans[i] < ans[i-1] && ans[i] < ans[i+1]) out++;
}
System.out.println(out);
StringBuilder sb = new StringBuilder();
for(int a : ans) sb.append(a + " ");
System.out.println(sb);
}
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static int swap(int itself, int dummy)
{
return itself;
}
//SecondThread
static class Flash
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next(){
while(!st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
//nextInt()
int ni(){
return Integer.parseInt(next());
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
//nextLong()
long nl(){
return Long.parseLong(next());
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | b8df3b133850a4bc72d44096490dc1b5 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes |
import java.io.PrintWriter;
import java.util.*;
public class D1 {
public static PrintWriter out = new PrintWriter(System.out);
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
solve();
out.flush();
}
private static void solve() {
int n = ni();
int[] a = na(n);
Arrays.sort(a);
LinkedList<Integer> first = new LinkedList<Integer>(), second = new LinkedList<Integer>();
for (int i = 0; i < n / 2; i++) {
first.add(a[i]);
}
for (int i = n / 2; i < n; i++) {
second.add(a[i]);
}
// Collections.reverse(second);
int j = 0;
while (j < n && !first.isEmpty() && !second.isEmpty()) {
a[j] = second.pollFirst();
a[j + 1] = first.pollFirst();
j += 2;
}
int c = 0;
while (!first.isEmpty()) a[j++] = first.pollFirst();
while (!second.isEmpty()) a[j++] = second.pollFirst();
for (int i = 1; i < n - 1; i++) {
if (a[i] < a[i - 1] && a[i] < a[i + 1]) c++;
}
System.out.println(c);
for (int x : a) {
System.out.print(x + " ");
}
System.out.println();
}
private static int ni() {
return in.nextInt();
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
private static long nl() {
return in.nextLong();
}
private float nf() {
return in.nextFloat();
}
private static double nd() {
return in.nextDouble();
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 8a9defcd1f1bf8a80bc66a34292158d5 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class D2 {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int[] arr = fs.nextIntArray(n);
Utils.shuffleSort(arr);
final int[] res = new int[n];
int top = n / 2;
int bot = 0;
boolean up = true;
for (int i = 0; i < n; i++) {
if (up) {
res[i] = arr[top++];
} else {
res[i] = arr[bot++];
}
up ^= true;
}
int count = 0;
for (int i = 1; i < n - 1; i++) {
if (res[i - 1] > res[i] && res[i] < res[i + 1]) {
count++;
}
}
System.out.println(count);
for (int i = 0; i < n; i++) {
System.out.print(res[i] + " ");
}
System.out.println();
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | dfa89d8f661138e426466185d739a28f | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static long mod = (int)(998244353);
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static void main(String[] args)throws IOException {
Scanner sc =new Scanner(System.in);
//FastReader sc = new FastReader();
int n =sc.nextInt();
int arr[] = new int[n+1];
for(int i=1;i<=n;i++)
arr[i] = sc.nextInt();
Arrays.sort(arr);
int ans = -1;
int r = ((n+1)/2)-1;
while(r>=1){
boolean b = check(n, r, arr);
if(b==false){
}else{
ans = r;
break;
}
r--;
}
StringBuilder sb = new StringBuilder();
ans = r;
sb.append(arr[n]+" ");
int c = n-1;
int a = ans;
for(;a>=1;){
sb.append(arr[a]+" "+arr[c]+" ");
a--;
c--;
}
for(int i=ans+1;i<=c;i++)
sb.append(arr[i]+" ");
System.out.println(ans);
System.out.println(sb.toString());
}
public static boolean check(int n, int mid, int arr[]){
int l = arr[n];
int op = n-1;
if(arr[mid]<l && arr[mid]<arr[op])
return true;
return false;
}
public static void add(TreeMap<Integer,Integer> hm, int val){
if(!hm.containsKey(val))
hm.put(val,1);
else hm.put(val, hm.get(val)+1);
}
public static void remove(TreeMap<Integer,Integer> hm, int val){
hm.put(val, hm.get(val)-1);
if(hm.get(val)==0){
hm.remove(val);
}
}
public static long power(long a, long b){
long temp = 0;
if(b==0)
return 1;
temp = power(a, b/2);
if(b%2==0)
return (temp%mod*temp%mod)%mod;
return (a%mod*(temp%mod*temp%mod)%mod)%mod;
}
public static ArrayList<Integer> primefactor(int n){
int sqrt = (int)Math.sqrt(n);
ArrayList<Integer> al = new ArrayList<>();
while(n%2==0){
al.add(2);
n/=2;
}
for(int i=3;i<=sqrt;i+=2){
while(n%i==0){
al.add(i);
n/=i;
}
}
if(n>2)
al.add(n);
return al;
}
public static long sum(long val){
long fg =0 ;
while(val!=0){
fg+=val%10;
val/=10;
}
return fg;
}
public static ArrayList<Long> factor(long n){
long sqrt = (long)Math.sqrt(n);
ArrayList<Long> al = new ArrayList<>();
for(long i=1;i<=sqrt;i++){
if(n%i!=0)
continue;
long first = i;
long second = n/i;
al.add(i);
if(first==second){
continue;
}
al.add(n/i);
}
return al;
}
public static ArrayList<Integer> comp(){
ArrayList<Integer> al = new ArrayList<>();
int n = (int)2e5;
boolean arr[] = new boolean[n+1];
int sqrt = (int)Math.sqrt(n);
for(int i=2;i<=sqrt;i++){
if(arr[i]==false){
for(int j=i*i;j<=n;j+=i){
arr[j]=true;
}
}
}
for(int i=2;i<=n;i++){
if(arr[i]==false)
al.add(i);
}
return al;
}
public static class pair{
int x;
int y;
pair(int a, int b){
x=a;
y=b;
}
}
public static class comp implements Comparator<pair>{
public int compare(pair o1, pair o2){
return o1.x-o2.x;
}
}
static class Node{
int node;
int d;
ArrayList<Integer> al = new ArrayList<>();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static class FastReader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(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]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | ff2ec69c6be0d8c847c30077fc1220e7 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader fs = new FastReader();
long n=0;
n = fs.nextLong();
List<Long> ar = new ArrayList<>();
for (int i = 0; i < n; i++) {
long t = fs.nextLong();
ar.add(t);
}
Collections.sort(ar);
if(n>2){
int l =0;
int r = (int) n/2;
List<Long> temp = new ArrayList<>();
for (long i = 0; i < n; i++) {
if(i%2==0){
temp.add(ar.get(r));
r++;
}else{
temp.add(ar.get(l));
l++;
}
}
int c =0;
for(int i=1;i<n-1;i++){
if(temp.get(i) < temp.get(i+1) && temp.get(i) < temp.get(i-1)){
c++;
}
}
System.out.println(c);
for (Long long1 : temp) {
System.out.print(long1 + " ");
}
System.out.println();
}else{
System.out.println(0);
for (Long long1 : ar) {
System.out.print(long1 + " ");
}
System.out.println();
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | b3aa1272b4080e9ac65629cc5365a9b5 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class bdday
{
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) throws IOException
{
FastReader s=new FastReader();
int n = s.nextInt();
String s1 = s.nextLine();
String[] tk = s1.split(" ");
int[] a = new int [n];
for (int i=0; i<n; i++)
a[i] = Integer.parseInt(tk[i]);
Arrays.sort(a);
int[] b = new int [n];
int p=n/2,c=0;
for (int i=0; i<n; i+=2){
b[i] = a[p];
p++;}
p=0;
if (n%2==0){
for (int i=1; i<n-1; i+=2){
b[i] = a[p];
if (b[i]<b[i-1] && b[i]<b[i+1])
c++;
p++;}
b[n-1] = a[p];
}
else{
for (int i=1; i<n; i+=2){
b[i] = a[p];
if (b[i]<b[i-1] && b[i]<b[i+1])
c++;
p++;}
}
System.out.println(c);
for (int i=0; i<n; i++)
System.out.print(b[i]+" ");
System.out.println();
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 7de92271e0e6281bbd3f3a018e70f0d4 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.io.*;
public class birthday {
public static void main(String[] args) throws java.io.IOException {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int prices = input.nextInt();
int[] price = new int[prices];
for (int i = 0; i < prices; i++) {
price[i] = input.nextInt();
}
int[] answers = new int[prices];
int s1 = (prices / 2) - 1;
int s2 = prices - 1;
int position = 0;
Arrays.sort(price);
if (prices % 2 == 0) {
for (int i = 0; i < prices; i++) {
if (position % 2 == 0) {
answers[position] = price[s1];
s1--;
position++;
} else {
answers[position] = price[s2];
s2--;
position++;
}
}
} else {
for (int i = 0; i < prices; i++) {
if (position % 2 == 0) {
answers[position] = price[s2];
s2--;
position++;
} else {
answers[position] = price[s1];
s1--;
position++;
}
}
}
int counter = 0;
for (int i = 1; i < prices - 1; i++) {
if (answers[i] < answers[i+1] && answers[i] < answers[i-1]) {
counter++;
}
}
System.out.println(counter);
for (int i = 0; i < prices; i++) {
System.out.print(answers[i] + " ");
}
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 38d3f450fd2fc448ffc72a2c049bd32d | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
public class P3{
public static void main(String[] args) {
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();
Arrays.sort(arr);
int b[]=new int[n];
int p=0;
for(int i=1;i<n;i+=2){
b[i]=arr[p];p++;}
for(int i=0;i<n;i+=2){
b[i]=arr[p];p++;}
p=0;
for(int i=1;i<n-1;i++)
{
if(b[i]<b[i-1]&&b[i]<b[i+1])
p++;
}
System.out.println(p);
for(int i:b)
System.out.print(i+" ");
System.out.println();
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | ccc9777e36745b42b3327d874a5bc8ec | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class jav{
public static void main(String[] args) throws IOException{
Reader sc=new Reader();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
int a[]=sc.nextIntArray(n);
int ans[]=new int[n];
int j=0;
Arrays.sort(a);
int an=0;
for(int i=1;i<n;i+=2){
ans[i]=a[j++];
}
for(int i=0;i<n;i+=2){
ans[i]=a[j++];
}
for(int i=1;i<n-1;i+=2){
if(ans[i]<ans[i-1]&&ans[i+1]>ans[i]){
an++;
}
}
pw.println(an);
for(int e:ans){
pw.print(e+" ");
}
pw.flush();
pw.close();
}
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]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
public int[] nextIntArray(int size)throws IOException {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int size) throws IOException {
long[] arr = new long[size];
for (int i = 0; i < size; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int size) throws IOException{
double[] arr = new double[size];
for (int i = 0; i < size; i++) {
arr[i] = nextDouble();
}
return arr;
}
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | ae41ddd1986b7a117b39f4a55d177810 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static int[] spheres;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
spheres = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i=0; i<n; i++) {
spheres[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(spheres);
// for (int i=0; i<n; i++) {
// System.out.print(spheres[i]+" ");
// }
// System.out.println();
int l = 0; int r = n;
while (l<r) {
if (r==l+1) {
break;
}
int mid = (l+r)/2;
if (can_buy(mid)) {
l = mid;
} else {
r = mid-1;
}
}
if (can_buy(r)) {
System.out.println(r);
int[] ans = new int[n];
for (int i=0; i<=r; i++) {
ans[2*i] = spheres[spheres.length-r-1+i];
}
for (int i=0; i<r; i++) {
ans[2*i+1] = spheres[i];
}
for (int i=0; i<2*r+1; i++) {
System.out.print(ans[i]+" ");
}
for (int i=r; i<spheres.length-r-1; i++) {
System.out.print(spheres[i]+" ");
}
} else {
System.out.println(l);
int[] ans = new int[n];
for (int i=0; i<=l; i++) {
ans[2*i] = spheres[spheres.length-l-1+i];
}
for (int i=0; i<l; i++) {
ans[2*i+1] = spheres[i];
}
for (int i=0; i<2*l+1; i++) {
System.out.print(ans[i]+" ");
}
for (int i=l; i<spheres.length-l-1; i++) {
System.out.print(spheres[i]+" ");
}
}
}
public static boolean can_buy(int num) {
int[] other = new int[num+1];
if (2*num+1>spheres.length) {
return false;
}
for (int i=spheres.length-1; i>=spheres.length-num-1; i--) {
other[i-spheres.length+num+1] = spheres[i];
}
for (int i=0; i<num+1; i++) {
if (i==0) {
if (other[i]<=spheres[i]) {
return false;
}
} else if (i==num) {
if (other[i]<=spheres[i-1]) {
return false;
}
} else {
if (other[i]<=spheres[i-1] || other[i]<=spheres[i]) {
return false;
}
}
}
return true;
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 4a7176150d6708af3ca8503fc507627f | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.*;
import java.util.*;
public class current {
public static void main(String[] args) {
FastReader fr = new FastReader();
int l = fr.nextInt();
solve(longList(fr.nextLine().split(" ")), l);
}
public static void solve(List<Long> list, int l) {
Collections.sort(list);
List<String> ans = new ArrayList<>();
if (l == 2 || l == 1) {
for (long i : list) {
ans.add(String.valueOf(i));
}
System.out.println(0);
System.out.println(String.join(" ", ans));
return;
}
for (int i = 0; i < l/2; i++) {
ans.add(String.valueOf(list.get(i+l/2)));
ans.add(String.valueOf(list.get(i)));
}
if (l % 2 == 1) {
ans.add(String.valueOf(list.get(l-1)));
}
int count = 0;
for (int i = 1; i < l; i += 2) {
try {
if (toInt(ans.get(i)) < toInt(ans.get(i - 1)) && toInt(ans.get(i)) < toInt(ans.get(i + 1))) {
count++;
}
} catch (IndexOutOfBoundsException e) {
break;
}
}
System.out.println(count);
System.out.println(String.join(" ", ans));
}
public static List<Integer> intList(String[] arr) {
List<Integer> a = new ArrayList<>();
for (String i : arr) {
a.add(Integer.parseInt(i));
}
return a;
}
public static List<Double> doubleList(String[] arr) {
List<Double> a = new ArrayList<>();
for (String i : arr) {
a.add(Double.parseDouble(i));
}
return a;
}
public static List<Long> longList(String[] arr) {
List<Long> a = new ArrayList<>();
for (String i : arr) {
a.add(Long.parseLong(i));
}
return a;
}
public static int toInt(String n) {
return Integer.parseInt(n);
}
public static double toDouble(String n) {
return Double.parseDouble(n);
}
public static long toLong(String n) {
return Long.parseLong(n);
}
static class FastReader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
// Initialize so that even if there is nothing in the line, we still return ""
String a = "";
try {
a = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | a3be2576c19ef713b36a41ef6ab04f61 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main
{
public static void main (String[] args) {
// your code goes here
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] a = new int[n];
for(int i=0; i<n; i++)
a[i] = s.nextInt();
Arrays.sort(a);
int c = n/2;
// if(n%2==1)
// c = n/2;
// else
// c = n/2-1;
int[] a1 = new int[c];
int a2[] = new int[n-c];
for(int j=0; j<n/2; j++)
a1[j] = a[j];
for(int j=n/2; j<n; j++)
a2[j-n/2] = a[j];
for(int j=0; j<n; j++)
{
if(j%2==0)
a[j] = a2[j/2];
else
a[j] = a1[j/2];
// System.out.print(a[j]+" ");
}
int x = 0;
for(int j=1; j<n-1; j+=2)
{
if(a[j]<a[j-1]&&a[j]<a[j+1])
x++;
}
System.out.println(x);
for(int j=0; j<n; j++)
System.out.print(a[j]+" ");
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | e77a409acdd7de56162bbbe3b9590dd7 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | /*
Written by Kabir Kanha Arora
@kabirkanha
*/
import java.util.*;
public class Main {
static long MOD = 1000000007;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; ++i) {
arr[i] = scanner.nextInt();
}
shuffle(arr);
Arrays.sort(arr);
int[] out = new int[n];
int mark = 0;
for (int i = 1; i < n; i += 2) {
out[i] = arr[mark];
mark++;
}
for (int i = 0; i < n; i += 2) {
out[i] = arr[mark];
mark++;
}
int ans = 0;
for (int i = 1; i < n - 1; i += 2) {
if (out[i] < out[i - 1] && out[i] < out[i + 1])
ans++;
}
System.out.println(ans);
for (int i = 0; i < n; ++i) {
System.out.print(out[i] + " ");
}
}
static void shuffle(int[] arr) {
for (int i = 0; i < arr.length; ++i) {
int random_index = (int) (Math.random() * arr.length);
int temp = arr[i];
arr[i] = arr[random_index];
arr[random_index] = temp;
}
}
}
| Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | 2796096683fe506b0578934342a02419 | train_001.jsonl | 1600526100 | This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered. | 256 megabytes | import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.lang.reflect.Array;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Main {
public void exec() {
int n = stdin.nextInt();
int[] a = stdin.nextIntArray(n);
Arrays.sort(a);
int x = 0;
int[] b = new int[n];
for (int i = 1; i < n; i += 2) {
b[i] = a[x++];
}
for (int i = 0; i < n; i += 2) {
b[i] = a[x++];
}
int ans = 0;
for (int i = 1; i < n - 1; i++) {
if (b[i-1] > b[i] && b[i] < b[i+1]) ans++;
}
stdout.println(ans);
stdout.println(join(b, " "));
}
public String join(int[] a, String delimiter) {
return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(delimiter));
}
private static final Stdin stdin = new Stdin();
private static final Stdout stdout = new Stdout();
public static void main(String[] args) {
try {
new Main().exec();
} finally {
stdout.flush();
}
}
public static class Stdin {
private BufferedReader stdin;
private Deque<String> tokens;
private Pattern delim;
public Stdin() {
stdin = new BufferedReader(new InputStreamReader(System.in));
tokens = new ArrayDeque<>();
delim = Pattern.compile(" ");
}
public String nextString() {
try {
if (tokens.isEmpty()) {
String line = stdin.readLine();
if (line == null) {
throw new UncheckedIOException(new EOFException());
}
delim.splitAsStream(line).forEach(tokens::addLast);
}
return tokens.pollFirst();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public long nextLong() {
return Long.parseLong(nextString());
}
public String[] nextStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = nextString();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
}
public static class Stdout {
private PrintWriter stdout;
public Stdout() {
stdout = new PrintWriter(System.out, false);
}
public void printf(String format, Object ... args) {
String line = String.format(format, args);
if (line.endsWith(System.lineSeparator())) {
stdout.print(line);
} else {
stdout.println(line);
}
}
public void println(Object ... objs) {
String line = Arrays.stream(objs).map(Objects::toString).collect(Collectors.joining(" "));
stdout.println(line);
}
public void printDebug(Object ... objs) {
String line = Arrays.stream(objs).map(this::deepToString).collect(Collectors.joining(" "));
stdout.printf("DEBUG: %s%n", line);
stdout.flush();
}
private String deepToString(Object o) {
if (o == null) {
return "null";
}
// 配列の場合
if (o.getClass().isArray()) {
int len = Array.getLength(o);
String[] tokens = new String[len];
for (int i = 0; i < len; i++) {
tokens[i] = deepToString(Array.get(o, i));
}
return "{" + String.join(",", tokens) + "}";
}
return Objects.toString(o);
}
private void flush() {
stdout.flush();
}
}
} | Java | ["7\n1 3 2 2 4 5 4"] | 1 second | ["3\n3 1 4 2 4 2 5"] | NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each. | Java 11 | standard input | [
"greedy",
"constructive algorithms",
"two pointers",
"sortings",
"binary search",
"brute force"
] | 6443dffb38285b6deb74f2371d8d0cac | The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres. | 1,500 | In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them. | standard output | |
PASSED | f03f2b5ab5b5c237d8b1453b28a7c098 | train_001.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.util.Scanner;
public class TwoSubstrings {
public TwoSubstrings() {
super();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
boolean ab = false, ba = false, found = false;
String sub = s.substring(0);
if (sub.contains("AB")) {
int index = sub.indexOf("AB");
ab = true;
sub = s.substring(index + 2);
if (sub.contains("BA")) {
ba = true;
}
}
if (ab && ba) {
System.out.println("YES");
found = true;
}
if (!found) {
sub = s.substring(0);
ab = false;
ba = false;
if (sub.contains("BA")) {
int index = sub.indexOf("BA");
ba = true;
sub = s.substring(index + 2);
if (sub.contains("AB")) {
ab = true;
}
}
if (ab && ba) {
System.out.println("YES");
}
}
if (!ab || !ba) {
System.out.println("NO");
}
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 7 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | d05213e0102785ee9b9f01eb72da094b | train_001.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class cf1 {
static String s;
static int[][][] memo;
public static boolean contains(int start, int end, int found) {
if (found == 3) {
return true;
}
if (end - start < 1) {
return false;
}
// int first = firstFound?1:0;
// int second= secondFound?1:0;
if (memo[start][end][found] != -1) {
if (memo[start][end][found] == 1) {
return true;
}
return false;
}
if (s.equals("BA")) {
int newFound = 2;
if (found == 1) {
newFound = 3;
}
return contains(0, 0, newFound);
}
if (s.equals("AB")) {
int newFound = 1;
if (found == 2) {
newFound = 3;
}
return contains(0, 0, newFound);
}
if (s.length() == 2) {
return false;
}
boolean contains = false;
if (s.substring(start, start + 2).equals("AB")) {
int newFound = 1;
if (found == 2) {
newFound = 3;
}
contains |= contains(start + 2, end, newFound);
}
if (s.substring(start, start + 2).equals("BA")) {
int newFound = 2;
if (found == 1) {
newFound = 3;
}
contains |= contains(start + 2, end, newFound);
}
contains |= contains(start + 1, end, found);
if (contains == true) {
memo[start][end][found] = 1;
} else {
memo[start][end][found] = 0;
}
return contains;
}
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
s = bf.readLine();
// memo = new int[s.length() ][s.length()][4];
// for (int i = 0; i < s.length(); i++) {
// for (int j = 0; j < s.length(); j++) {
// for (int k = 0; k < 4; k++) {
// memo[i][j][k] = -1;
// }
// }
// }
// boolean contains = contains(0, s.length()-1, 0);
boolean foundAB1 = false;
boolean foundBA1 = false;
boolean foundAB2 = false;
boolean foundBA2 = false;
int i = 0;
for (i = 0; i < s.length()-1 && !foundAB1; i++) {
if (s.substring(i, i + 2).equals("AB")) {
foundAB1 = true;
break;
}
}
if (foundAB1) {
for (i = i + 2; i < s.length()-1 && !foundBA1; i++) {
if (s.substring(i, i + 2).equals("BA")) {
foundBA1 = true;
break;
}
}
if (foundBA1) {
System.out.println("YES");
} else {
i = 0;
for (i = 0; i < s.length()-1 && !foundBA2; i++) {
if (s.substring(i, i + 2).equals("BA")) {
foundBA2 = true;
break;
}
}
if (foundBA2) {
for (i = i + 2; i < s.length()-1 && !foundAB2; i++) {
if (s.substring(i, i + 2).equals("AB")) {
foundAB2 = true;
break;
}
}
if (foundAB2) {
System.out.println("YES");
} else {
System.out.println("NO");
}
} else {
System.out.println("NO");
}
}
} else {
System.out.println("NO");
}
}
}
| Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 7 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | 55e1d854757b74ce232812711730e42f | train_001.jsonl | 1433435400 | You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). | 256 megabytes | import java.util.Scanner;
public class Test{
public static boolean reemplazar(StringBuilder s, String str){
int index = s.toString().indexOf(str);
if(index < 0){
return false;
}
s.replace(index, index+2,"__");
return true;
}
public static boolean isValid(StringBuilder sb, String s1, String s2)
{
return (reemplazar(sb,s1) && reemplazar(sb,s2));
}
public static void main(String[] args){
StringBuilder bf;
StringBuilder bf2;
Scanner sc = new Scanner(System.in);
String cadena = sc.next();
bf = new StringBuilder(cadena);
bf2 = new StringBuilder(cadena);
if(isValid(bf,"AB","BA") || isValid(bf2,"BA","AB"))
System.out.println("YES");
else
System.out.println("NO");
}
} | Java | ["ABA", "BACFAB", "AXBYBXA"] | 2 seconds | ["NO", "YES", "NO"] | NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | Java 7 | standard input | [
"dp",
"greedy",
"implementation",
"brute force",
"strings"
] | 33f7c85e47bd6c83ab694a834fa728a2 | The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. | 1,500 | Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise. | standard output | |
PASSED | deeb9e44e4aaaec418c0a6382ac54fa9 | train_001.jsonl | 1400914800 | Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.Each piece of tofu in the canteen is given a m-based number, all numbers are in the range [l, r] (l and r being m-based numbers), and for every m-based integer in the range [l, r], there exists a piece of tofu with that number.To judge what tofu is Mapo Tofu, Tachibana Kanade chose n m-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero.Tachibana Kanade considers tofu with values no more than k to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu? | 512 megabytes | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;
public class CF433E {
static final int MOD = 1000000007;
public static void main(String[] args) throws Exception {
new CF433E().solve();
}
private void solve() throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
String l = readTohu(sc);
String r = readTohu(sc);
int[] vs = new int[n];
String[] pats = new String[n];
for (int i = 0; i < n; i++) {
pats[i] = readTohu(sc);
vs[i] = sc.nextInt();
}
ahoCorasickBuild(pats, vs);
int rv = new DPState(m, k, r, l, states).rec(k, 0, r.length() - 1, false, false,
1);
System.out.println(rv);
}
static class DPState {
final int m;
final int k;
final String rs;
final String ls;
final ArrayList<CharTrie> states;
final int dp[][][];
public DPState(int m, int k, String rs, String ls, ArrayList<CharTrie> states) {
this.m = m;
this.k = k;
this.rs = rs;
this.ls = ls;
this.states = states;
dp = new int[k + 1][states.size()][rs.length()];
for (int[][] dp2 : dp) {
for (int[] dp3 : dp2) {
Arrays.fill(dp3, -1);
}
}
}
int rec(int remK, int curState, int digits, boolean digitIsArbitSup,
boolean digitIsArbitSub, int zeroLeading) {
if (remK < 0) return 0;
if (digits < 0) return 1 - zeroLeading;
if (digitIsArbitSup && digitIsArbitSub && zeroLeading == 0
&& dp[remK][curState][digits] != -1) return dp[remK][curState][digits];
int maxV = digitIsArbitSup ? m - 1 : rs.charAt(rs.length() - digits - 1);
int minV = digitIsArbitSub || digits >= ls.length() ? 0 : ls.charAt(ls
.length()
- digits - 1);
long ret = 0;
for (int v = minV; v <= maxV; v++) {
boolean nextDigitIsArbitSup = digitIsArbitSup || v != maxV;
boolean nextDigitIsArbitSub = digitIsArbitSub || v != minV;
int nextZeroLeading = (zeroLeading == 1 && v == 0) ? 1 : 0;
int nextState = curState;
int gain = 0;
if (nextZeroLeading == 0) {
CharTrie state = states.get(curState);
state = state.children[v];
gain = state.v;
nextState = state.id;
}
ret += rec(remK - gain, nextState, digits - 1, nextDigitIsArbitSup,
nextDigitIsArbitSub, nextZeroLeading);
ret %= MOD;
}
if (digitIsArbitSup && digitIsArbitSub && zeroLeading == 0) dp[remK][curState][digits] = (int) ret;
return (int) ret;
}
}
private String readTohu(Scanner sc) {
int len = sc.nextInt();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
int a = sc.nextInt();
sb.append((char) a);
}
return sb.toString();
}
static class CharTrie {
CharTrie[] children = new CharTrie[20];
CharTrie fail;
int v;
int id;
}
ArrayList<CharTrie> states = new ArrayList<CharTrie>();
CharTrie ahoCorasickBuild(String[] pats, int[] vs) {
CharTrie root = new CharTrie();
states.add(root);
for (int i = 0; i < pats.length; i++) {
CharTrie cur = root;
for (int j = 0; j < pats[i].length(); j++) {
int c = pats[i].charAt(j);
if (cur.children[c] == null) {
cur.children[c] = new CharTrie();
cur.children[c].id = states.size();
states.add(cur.children[c]);
}
cur = cur.children[c];
}
cur.v += vs[i];
}
Queue<CharTrie> queue = new ArrayDeque<CharTrie>();
for (int i = 0; i < root.children.length; i++) {
if (root.children[i] == null) root.children[i] = root;
else {
root.children[i].fail = root;
queue.add(root.children[i]);
}
}
while (!queue.isEmpty()) {
CharTrie par = queue.poll();
for (int i = 0; i < par.children.length; i++) {
CharTrie child = par.children[i];
if (child == null) continue;
queue.add(child);
CharTrie fail = par.fail;
while (fail.children[i] == null)
fail = fail.fail;
child.fail = fail.children[i];
child.v += child.fail.v;
}
// precompute failing transit
for (int i = 0; i < par.children.length; i++) {
CharTrie fail = par;
while (fail.children[i] == null)
fail = fail.fail;
par.children[i] = fail.children[i];
}
}
return root;
}
}
| Java | ["2 10 1\n1 1\n3 1 0 0\n1 1 1\n1 0 1", "2 10 12\n2 5 9\n6 6 3 5 4 9 7\n2 0 6 1\n3 6 7 2 1", "4 2 6\n6 1 0 1 1 1 0\n6 1 1 0 1 0 0\n1 1 2\n3 0 1 0 5\n4 0 1 1 0 4\n3 1 0 1 2"] | 5 seconds | ["97", "635439", "2"] | NoteIn the first sample, 10, 11 and 100 are the only three decimal numbers in [1, 100] with a value greater than 1. Here the value of 1 is 1 but not 2, since numbers cannot contain leading zeros and thus cannot be written as "01".In the second sample, no numbers in the given interval have a value greater than 12.In the third sample, 110000 and 110001 are the only two binary numbers in the given interval with a value no greater than 6. | Java 7 | standard input | [
"dp"
] | 9e83ebfda6eaa583af11b5883bfaab23 | The first line contains three integers n, m and k (1 ≤ n ≤ 200; 2 ≤ m ≤ 20; 1 ≤ k ≤ 500). Where n denotes the number of strings, m denotes the base used, and k denotes the limit of the value for Mapo Tofu. The second line represents the number l. The first integer in the line is len (1 ≤ len ≤ 200), describing the length (number of digits in base m) of l. Then follow len integers a1, a2, ..., alen (0 ≤ ai < m; a1 > 0) separated by spaces, representing the digits of l, with a1 being the highest digit and alen being the lowest digit. The third line represents the number r in the same format as l. It is guaranteed that 1 ≤ l ≤ r. Then follow n lines, each line describing a number string. The i-th line contains the i-th number string and vi — the value of the i-th string (1 ≤ vi ≤ 200). All number strings are described in almost the same format as l, the only difference is number strings may contain necessary leading zeros (see the first example). The sum of the lengths of all number strings does not exceed 200. | 2,500 | Output the number of pieces of Mapo Tofu modulo 1000000007 (109 + 7). The answer should be a decimal integer. | standard output | |
PASSED | 5ce1cc4632e17415646c68a32ca38ba7 | train_001.jsonl | 1400914800 | Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.Each piece of tofu in the canteen is given a m-based number, all numbers are in the range [l, r] (l and r being m-based numbers), and for every m-based integer in the range [l, r], there exists a piece of tofu with that number.To judge what tofu is Mapo Tofu, Tachibana Kanade chose n m-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero.Tachibana Kanade considers tofu with values no more than k to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu? | 512 megabytes | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;
public class CF433E {
static final int MOD = 1000000007;
public static void main(String[] args) throws Exception {
new CF433E().solve();
}
private void solve() throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int k = sc.nextInt();
String l = readTohu(sc);
String r = readTohu(sc);
int[] vs = new int[n];
String[] pats = new String[n];
for (int i = 0; i < n; i++) {
pats[i] = readTohu(sc);
vs[i] = sc.nextInt();
}
ahoCorasickBuild(pats, vs);
int rv = new DPState(m, k, r, l, states).rec(k, 0, r.length() - 1, false, false,
1);
System.out.println(rv);
}
static class DPState {
final int m;
final int k;
final String rs;
final String ls;
final ArrayList<CharTrie> states;
final int dp[][][];
public DPState(int m, int k, String rs, String ls, ArrayList<CharTrie> states) {
this.m = m;
this.k = k;
this.rs = rs;
this.ls = ls;
this.states = states;
dp = new int[k + 1][states.size()][rs.length()];
for (int[][] dp2 : dp) {
for (int[] dp3 : dp2) {
Arrays.fill(dp3, -1);
}
}
}
int rec(int remK, int curState, int digits, boolean digitIsArbitSup,
boolean digitIsArbitSub, int zeroLeading) {
if (remK < 0) return 0;
if (digits < 0) return 1 - zeroLeading;
if (digitIsArbitSup && digitIsArbitSub && zeroLeading == 0
&& dp[remK][curState][digits] != -1) return dp[remK][curState][digits];
int maxV = digitIsArbitSup ? m - 1 : rs.charAt(rs.length() - digits - 1);
int minV = digitIsArbitSub || digits >= ls.length() ? 0 : ls.charAt(ls
.length()
- digits - 1);
long ret = 0;
for (int v = minV; v <= maxV; v++) {
boolean nextDigitIsArbitSup = digitIsArbitSup || v != maxV;
boolean nextDigitIsArbitSub = digitIsArbitSub || v != minV;
int nextZeroLeading = (zeroLeading == 1 && v == 0) ? 1 : 0;
int nextState = curState;
int gain = 0;
if (nextZeroLeading == 0) {
CharTrie state = states.get(curState);
state = state.children[v];
gain = state.v;
nextState = state.id;
}
ret += rec(remK - gain, nextState, digits - 1, nextDigitIsArbitSup,
nextDigitIsArbitSub, nextZeroLeading);
ret %= MOD;
}
if (digitIsArbitSup && digitIsArbitSub && zeroLeading == 0) dp[remK][curState][digits] = (int) ret;
return (int) ret;
}
}
private String readTohu(Scanner sc) {
int len = sc.nextInt();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
int a = sc.nextInt();
sb.append((char) a);
}
return sb.toString();
}
static class CharTrie {
CharTrie[] children = new CharTrie[20];
CharTrie fail;
int v;
int id;
}
ArrayList<CharTrie> states = new ArrayList<CharTrie>();
CharTrie ahoCorasickBuild(String[] pats, int[] vs) {
CharTrie root = new CharTrie();
states.add(root);
for (int i = 0; i < pats.length; i++) {
CharTrie cur = root;
for (int j = 0; j < pats[i].length(); j++) {
int c = pats[i].charAt(j);
if (cur.children[c] == null) {
cur.children[c] = new CharTrie();
cur.children[c].id = states.size();
states.add(cur.children[c]);
}
cur = cur.children[c];
}
cur.v += vs[i];
}
Queue<CharTrie> queue = new ArrayDeque<CharTrie>();
for (int i = 0; i < root.children.length; i++) {
if (root.children[i] == null) root.children[i] = root;
else {
root.children[i].fail = root;
queue.add(root.children[i]);
}
}
while (!queue.isEmpty()) {
CharTrie par = queue.poll();
for (int i = 0; i < par.children.length; i++) {
CharTrie child = par.children[i];
if (child == null) continue;
queue.add(child);
CharTrie fail = par.fail;
while (fail.children[i] == null)
fail = fail.fail;
child.fail = fail.children[i];
child.v += child.fail.v;
}
// precompute failing transit
for (int i = 0; i < par.children.length; i++) {
CharTrie fail = par;
while (fail.children[i] == null)
fail = fail.fail;
par.children[i] = fail.children[i];
}
}
return root;
}
}
| Java | ["2 10 1\n1 1\n3 1 0 0\n1 1 1\n1 0 1", "2 10 12\n2 5 9\n6 6 3 5 4 9 7\n2 0 6 1\n3 6 7 2 1", "4 2 6\n6 1 0 1 1 1 0\n6 1 1 0 1 0 0\n1 1 2\n3 0 1 0 5\n4 0 1 1 0 4\n3 1 0 1 2"] | 5 seconds | ["97", "635439", "2"] | NoteIn the first sample, 10, 11 and 100 are the only three decimal numbers in [1, 100] with a value greater than 1. Here the value of 1 is 1 but not 2, since numbers cannot contain leading zeros and thus cannot be written as "01".In the second sample, no numbers in the given interval have a value greater than 12.In the third sample, 110000 and 110001 are the only two binary numbers in the given interval with a value no greater than 6. | Java 7 | standard input | [
"dp"
] | 9e83ebfda6eaa583af11b5883bfaab23 | The first line contains three integers n, m and k (1 ≤ n ≤ 200; 2 ≤ m ≤ 20; 1 ≤ k ≤ 500). Where n denotes the number of strings, m denotes the base used, and k denotes the limit of the value for Mapo Tofu. The second line represents the number l. The first integer in the line is len (1 ≤ len ≤ 200), describing the length (number of digits in base m) of l. Then follow len integers a1, a2, ..., alen (0 ≤ ai < m; a1 > 0) separated by spaces, representing the digits of l, with a1 being the highest digit and alen being the lowest digit. The third line represents the number r in the same format as l. It is guaranteed that 1 ≤ l ≤ r. Then follow n lines, each line describing a number string. The i-th line contains the i-th number string and vi — the value of the i-th string (1 ≤ vi ≤ 200). All number strings are described in almost the same format as l, the only difference is number strings may contain necessary leading zeros (see the first example). The sum of the lengths of all number strings does not exceed 200. | 2,500 | Output the number of pieces of Mapo Tofu modulo 1000000007 (109 + 7). The answer should be a decimal integer. | standard output | |
PASSED | afa4482892ba3fe98deaf1e66cae1939 | train_001.jsonl | 1516462500 | Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x = y2. | 256 megabytes | import java.util.Scanner;
public class PerfectSquares {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int out = 0;
for(int i = 0; i < n; i++) {
int a = scan.nextInt();
double sqrtA = Math.sqrt(a);
if(sqrtA != (int) sqrtA && a > out) out = a;
if (a < 0) if(a > out || out == 0) out = a;
}
System.out.println(out);
}
}
| Java | ["2\n4 2", "8\n1 2 4 8 16 32 64 576"] | 1 second | ["2", "32"] | NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d46d5f130d8c443f28b52096c384fef3 | The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — the elements of the array. It is guaranteed that at least one element of the array is not a perfect square. | 900 | Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists. | standard output | |
PASSED | 012dd0d484dd85ccf369985582f783e6 | train_001.jsonl | 1516462500 | Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x = y2. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author Home
*/
public class Hi {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;// = new StringTokenizer(input.readLine());
int n=Integer.parseInt(input.readLine());
st= new StringTokenizer(input.readLine());
int arr;
int ans=Integer.MIN_VALUE ;
int sqr;
for (int i = 0; i <n; i++) {
arr=Integer.parseInt(st.nextToken());
sqr=(int)Math.sqrt(arr);
if(arr<0||(sqr*sqr)!=arr )
ans=Math.max(ans, arr);
}
System.out.println(ans);
}} | Java | ["2\n4 2", "8\n1 2 4 8 16 32 64 576"] | 1 second | ["2", "32"] | NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d46d5f130d8c443f28b52096c384fef3 | The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second line contains n integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — the elements of the array. It is guaranteed that at least one element of the array is not a perfect square. | 900 | Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists. | standard output | |
PASSED | 64ae150f8109ff8d0b07e672ebb732dd | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author xylenox
*/
public class c {
static int MOD = 1000000007;
public static void main(String[] args) {
FS in = new FS(System.in);
int t = in.nextInt();
while(t-->0) {
int n = in.nextInt();
int T = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int[] num = new int[2];
int[] times = new int[n];
int[] diffs = new int[n];
Integer[] perm = new Integer[n];
for(int i = 0; i < n; i++) {
num[diffs[i] = in.nextInt()]++;
}
for(int i = 0; i < n; i++) {
times[i] = in.nextInt();
perm[i] = i;
}
Arrays.sort(perm, (Integer A, Integer B) -> times[A] != times[B] ? times[A]-times[B] : diffs[A]-diffs[B]);
int best = 0;
int[] count = new int[2];
int tmp = times[perm[0]]-1;
long tot = (long)a*count[0]+(long)b*count[1];
int number = count[0]+count[1];
tmp -= tot;
int numA = Math.min(num[0]-count[0], tmp/a);
tmp -= a*numA;
int numB = Math.min(num[1]-count[1], tmp/b);
best = Math.max(best, number+numA+numB);
for(int i = 0; i < n; i++) {
if(i == n-1) tmp = T;
else tmp = times[perm[i+1]]-1;
count[diffs[perm[i]]]++;
if(i != n-1 && times[perm[i]] == times[perm[i+1]]) continue;
tot = (long)a*count[0]+(long)b*count[1];
if(tot > tmp) continue;
number = count[0]+count[1];
tmp -= tot;
numA = Math.min(num[0]-count[0], tmp/a);
tmp -= a*numA;
numB = Math.min(num[1]-count[1], tmp/b);
best = Math.max(best, number+numA+numB);
}
System.out.println(best);
}
}
static class FS {
BufferedReader in;
StringTokenizer token;
public FS(InputStream st) {
in = new BufferedReader(new InputStreamReader(st));
}
public String next() {
if(token == null || !token.hasMoreElements()) {
try {
token = new StringTokenizer(in.readLine());
} catch(Exception e) {}
return next();
}
return token.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | 7651f33f7d20add30eece5c9a59fa544 | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes | import java.util.*;
import java.io.*;
public class c {
public static void main(String[] Args)
throws Exception
{
FS sc = new FS(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = sc.nextInt();
while (t-->0) {
int ans = 0;
int n = sc.nextInt();
int T = sc.nextInt();
long a = sc.nextInt();
long b = sc.nextInt();
Event[] eves = new Event[n+1];
long totA = 0;
long totB = 0;
long manA = 0;
long manB = 0;
eves[n] = new Event();
eves[n].epoc = T+1;
for (int i = 0; i < n; i++) {
eves[i] = new Event();
eves[i].isA = (sc.nextInt() == 0);
if (eves[i].isA)
totA++;
else
totB++;
}
for (int i = 0; i < n; i++)
eves[i].epoc = sc.nextInt();
Arrays.sort(eves);
for (int i = 0; i <= n; i++) {
if (manA * a + manB * b > T)
break;
long left = eves[i].epoc - 1 - (manA * a + manB * b);
if (left < 0){
if (eves[i].isA){
manA++;
totA--;
}else{
manB++;
totB--;
}
continue;
}
int tans = i;
if (left >= totA * a){
tans += totA;
left -= totA * a;
} else {
tans += left / a;
left %= a;
}
if (left >= totB * b) {
tans += totB;
left -= totB * b;
} else {
tans += left / b;
left %= b;
}
if (tans > ans)
ans = tans;
if (eves[i].isA){
manA++;
totA--;
}else{
manB++;
totB--;
}
}
out.println(ans);
}
out.close();
}
public static class Event implements Comparable<Event> {
int epoc;
boolean isA;
public int compareTo(Event o) {
return epoc - o.epoc;
}
}
public static class FS {
BufferedReader br;
StringTokenizer st;
FS(InputStream in)
throws Exception
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer(br.readLine());
}
String next()
throws Exception
{
if (st.hasMoreTokens())
return st.nextToken();
st = new StringTokenizer(br.readLine());
return next();
}
int nextInt()
throws Exception
{
return Integer.parseInt(next());
}
long nextLong()
throws Exception
{
return Long.parseLong(next());
}
}
} | Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | 7d555147cf7d9f897d66dd98c2993ca5 | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
FastScanner scanner;
PrintWriter writer;
void solve() throws IOException {
scanner = new FastScanner(System.in);
writer = new PrintWriter(System.out);
int tests = scanner.nextInt();
for (int t = 0; t < tests; t++) {
int n = scanner.nextInt();
int end = scanner.nextInt();
int a = scanner.nextInt();
int b = scanner.nextInt();
int easyNum = 0;
int hardNum = 0;
List<Problem> problems = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
problems.add(new Problem());
}
for (int i = 0; i < n; i++) {
boolean isHard = scanner.nextInt() == 1;
problems.get(i).isHard = isHard;
if (isHard)
hardNum++;
else
easyNum++;
}
for (int i = 0; i < n; i++) {
problems.get(i).t = scanner.nextInt();
}
problems.add(new Problem(false, end + 1));
problems.sort(Comparator.comparingInt(x -> x.t));
long max = 0;
long sumTime = 0;
for (int i = 0; i < problems.size(); i++) {
long timeAvail = problems.get(i).t - 1 - sumTime;
if (timeAvail >= 0) {
long solved = i;
long e = Math.min(timeAvail / a, easyNum);
timeAvail -= a * e;
long h = Math.min(timeAvail / b, hardNum);
solved += e + h;
max = Math.max(max, solved);
}
if (problems.get(i).isHard) {
sumTime += b;
hardNum--;
} else {
sumTime += a;
easyNum--;
}
}
writer.println(max);
}
writer.close();
}
static class Problem {
boolean isHard;
int t;
public Problem() {
}
public Problem(boolean isHard, int t) {
this.isHard = isHard;
this.t = t;
}
}
public static void main(String... args) throws IOException {
new D().solve();
}
static class FastScanner {
BufferedReader br;
StringTokenizer tokenizer;
FastScanner(String fileName) throws FileNotFoundException {
this(new FileInputStream(new File(fileName)));
}
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String nextLine() throws IOException {
tokenizer = null;
return br.readLine();
}
String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | b8e972e6986720a45b0fe2a7ac9f7790 | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 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.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author John Martin
*/
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);
CPetyaAndExam solver = new CPetyaAndExam();
solver.solve(1, in, out);
out.close();
}
static class CPetyaAndExam {
public void solve(int testNumber, InputReader c, OutputWriter w) {
int tc = c.readInt();
while (tc-- > 0) {
int n = c.readInt(), t = c.readInt(), aa = c.readInt(), bb = c.readInt();
int a[] = c.readIntArray(n), b[] = c.readIntArray(n);
pp p[] = new pp[n];
for (int i = 0; i < n; i++) {
p[i] = new pp(a[i], b[i]);
}
Arrays.sort(p);
TreeSet<pp> t1 = new TreeSet<>(), t2 = new TreeSet<>();
int cnt_e = 0, cnt_h = 0;
for (int i = 0; i < n; i++) {
if (p[i].a == 0) {
cnt_e++;
if (t1.contains(new pp(0, p[i].t))) {
t1.remove(new pp(0, p[i].t));
}
t1.add(new pp(cnt_e, p[i].t));
if (!t1.contains(new pp(0, p[i].t - 1))) {
t1.add(new pp(cnt_e - 1, p[i].t - 1));
}
} else {
cnt_h++;
if (!t2.contains(new pp(0, p[i].t - 1))) {
t2.add(new pp(cnt_h - 1, p[i].t - 1));
}
if (t2.contains(new pp(cnt_h, p[i].t))) {
t2.remove(new pp(cnt_h, p[i].t));
}
t2.add(new pp(cnt_h, p[i].t));
}
}
t1.add(new pp(cnt_e, t));
t2.add(new pp(cnt_h, t));
TreeSet<pp> k1 = (TreeSet<pp>) t1.clone();
int res = 0;
while (!t1.isEmpty()) {
pp k = t1.pollFirst();
pp h = new pp(0, k.t);
if (t2.floor(h) != null) {
h = t2.floor(h);
}
int can = -1;
if ((k.a * (long) aa) + (h.a * (long) (bb)) <= k.t) {
can = k.a + h.a;
long time_left = k.t - ((k.a * (long) aa) + (h.a * (long) (bb)));
int left = cnt_e - k.a;
if (time_left > left * aa) {
can += left + Math.min((time_left - left * aa) / bb, cnt_h - h.a);
} else {
can += Math.min(time_left / aa, left);
}
}
res = Math.max(res, can);
}
while (!t2.isEmpty()) {
pp k = t2.pollFirst();
pp h = new pp(0, k.t);
if (k1.floor(h) != null) {
h = k1.floor(h);
}
int can = -1;
if (k.a * (long) bb + h.a * (long) (aa) <= k.t) {
can = k.a + h.a;
long time_left = k.t - (k.a * (long) bb + h.a * (long) (aa));
int left = cnt_e - h.a;
if (time_left > left * aa) {
can += left + Math.min((time_left - left * aa) / bb, cnt_h - k.a);
} else {
can += Math.min(time_left / aa, left);
}
}
res = Math.max(res, can);
}
w.printLine(res);
}
}
}
static class pp implements Comparable<pp> {
int a;
int t;
public String toString() {
return "pp{" +
"a=" + a +
", t=" + t +
'}';
}
public pp(int a, int t) {
this.a = a;
this.t = t;
}
public int compareTo(pp o) {
return this.t - o.t;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
static 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[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | ebdb85bf979a6edbb3d8eacef121a3ac | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes | import java.io.*;
import java.util.*;
/*
───────────────■■■─────────────────────────
──█▄─▄█─▄▀▀▀▄─█──▄█─────█──▄▀─▄▀▀▀▄─▀▀█▀▀──
──█─▀─█─█───█─█─█─█─────█■█───█───█───█────
──█───█─▀▄▄▄▀─█▀──█─────█──▀▄─▀▄▄▄▀───█────
───────────────────────────────────────────
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9);
static final int MOD = (int) (1e9 + 7);
static final int N = (int) (1e6 + 6);
static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int j = i + rand.nextInt(a.length - i);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
static class P {
int t, zo;
P() {
}
}
static void solve() {
int n = in.nextInt();
int T = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
P[] ps = new P[n];
Arrays.setAll(ps, i -> new P());
int cntA = 0, cntB = 0;
for (int i = 0; i < n; i++) {
ps[i].zo = in.nextInt();
if (ps[i].zo == 0) {
cntA++;
} else {
cntB++;
}
}
for (int i = 0; i < n; i++) {
ps[i].t = in.nextInt();
}
Arrays.sort(ps, (o1, o2) -> Integer.compare(o1.t, o2.t));
int cnta = 0, cntb = 0;
int ans = 0;
for (int i = 0; i < n; i++) {
int t = ps[i].t;
long aa = (long) a * cnta;
long bb = (long) b * cntb;
if (aa + bb <= t - 1) {
long cnt = aa + bb;
int lol = cnta + cntb;
int cntAa = cntA - cnta;
int cntBb = cntB - cntb;
long dif = t - 1 - cnt;
lol += Math.min(dif / a, cntAa);
if (cntAa < dif / a) {
lol += Math.min(cntBb, (dif - a * cntAa) / b);
}
ans = Math.max(ans, lol);
}
int j = i;
while (j < n && ps[i].t == ps[j].t) {
if (ps[j].zo == 0) {
cnta++;
} else {
cntb++;
}
j++;
}
aa = (long) a * cnta;
bb = (long) b * cntb;
if (aa + bb <= t) {
long cnt = aa + bb;
int lol = cnta + cntb;
int cntAa = cntA - cnta;
int cntBb = cntB - cntb;
long dif = t - cnt;
lol += Math.min(dif / a, cntAa);
if (cntAa < dif / a) {
lol += Math.min(cntBb, (dif - a * cntAa) / b);
}
ans = Math.max(ans, lol);
}
i = j - 1;
}
long aa = (long) a * cnta;
long bb = (long) b * cntb;
if (aa + bb <= T) {
ans = Math.max(ans, n);
}
out.println(ans);
}
public static void main(String[] args) throws FileNotFoundException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("output.txt"));
int q = in.nextInt();
while (q-- > 0) {
solve();
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | 0a48036e4d6aa837bc46724c4141551d | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes | import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class C {
public static class Q {
boolean isHard;
int ti;
public Q(int tp, int ti) {
isHard = tp==1;
this.ti = ti;
}
public int getTi() {
return ti;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m = in.nextInt();
for (int mi=0; mi<m; mi++) {
int n = in.nextInt();
int t = in.nextInt();
long a = in.nextInt();
long b = in.nextInt();
int[] tp = new int[n];
int[] ti = new int[n];
Q[] q = new Q[n];
long toteasy = 0;
long tothard = 0;
for (int i=0; i<n; i++) {
tp[i] = in.nextInt();
if (tp[i] == 0) toteasy++;
else tothard++;
}
for (int i=0; i<n; i++) {
ti[i] = in.nextInt();
q[i] = new Q(tp[i], ti[i]);
}
Arrays.sort(q, Comparator.comparing(Q::getTi));
TreeSet<Integer> times = new TreeSet<>();
for (int i=0; i<n; i++)
if (ti[i] >= 1)
times.add(ti[i] - 1);
times.add(t);
int curq = -1; // Last question so that its time <= current time (i.e. need to be solved)
long cureasy = 0; // Number of easy questions up to curq
long curhard = 0;
long max = 0;
for (int curt : times) {
while (curq < q.length-1 && q[curq+1].ti <= curt) {
curq++;
if (q[curq].isHard) curhard++; else cureasy++;
}
long time = a * cureasy + b * curhard;
if (time > curt) { // Not enough time to solve requires probs
continue;
}
long pts = cureasy + curhard;
long remaintime = curt - time;
if (remaintime <= a * (toteasy - cureasy)) { // Remaining time for easy probs only
pts += remaintime / a;
} else {
pts += toteasy-cureasy;
remaintime -= a * (toteasy - cureasy);
pts += Math.min(remaintime/b, tothard-curhard);
}
max = Math.max(max, pts);
}
System.out.println(max);
}
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | a40e285786fe1f7d759e62228f044e80 | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
static PrintWriter out;
static InputReader in;
public static void main(String args[]){
out = new PrintWriter(System.out);
in = new InputReader();
new Main();
out.flush(); out.close();
}
Main(){
solve();
}
class pair{
int F, S;
pair(int a, int b){
F = a; S = b;
}
}
int c[], a, b;
long cal(long x){
if(x <= 0)return 0;
long ca = x / a;
if(ca <= c[0])return ca;
x -= c[0] * a;
return c[0] + Math.min(c[1], x / b);
}
void solve(){
int test = in.nextInt();
while(test-- > 0){
int n = in.nextInt(), t = in.nextInt(); a = in.nextInt(); b = in.nextInt();
int ty[] = new int[n];
c = new int[2];
for(int i = 0; i < n; i++)c[ty[i] = in.nextInt()]++;
ArrayList<pair> al = new ArrayList<>();
for(int i = 0; i < n; i++)al.add(new pair(i, in.nextInt()));
Collections.sort(al, (A, B) -> A.S - B.S);
long pt = 0, tt = 0;
long ans = 0;
int j = 0;
for(int i = 0; i < n; i = j){
j = i;
pair p = al.get(j);
tt = Math.min(p.S - 1, t);
ans = Math.max(ans, j + cal(tt - pt));
pt += (ty[p.F] == 0 ? a : b); c[ty[p.F]]--;
for(j = i + 1; j < n; j++){
p = al.get(j);
if(p.S <= pt){
pt += (ty[p.F] == 0 ? a : b);
c[ty[p.F]]--;
}else break;
}
// System.out.println(i + " " + j + " " + pt + " " + tt + " " + ans);
if(pt > t)break;
else{
if(j == n)ans = n;
}
}
out.println(ans);
}
}
public static class InputReader{
BufferedReader br;
StringTokenizer st;
InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){}
}
return st.nextToken();
}
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | ab2f92d2b56252ad3097004e3fdfd713 | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes | import java.util.*;
import java.io.*;
public class DD {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
PrintWriter out = new PrintWriter(System.out, false);
int m = scanner.nextInt();
while(m-->0) {
int n = scanner.nextInt(), t = scanner.nextInt();long a = scanner.nextInt(), b = scanner.nextInt();
boolean[] ez = new boolean[n];
Tuple[] arr = new Tuple[n];
int nez = 0;
int nhard = 0;
for(int i = 0; i <n; i++) {
ez[i] = scanner.nextInt() == 0;
if (ez[i]) nez++;
else nhard++;
}
for(int i = 0; i < n; i++) {
arr[i] = new Tuple(i, scanner.nextInt(), ez[i] ? a : b);
}
Arrays.sort(arr);
long time = 0;
long amt = 0;
long best = 0;
long rem = arr[0].time - time - 1;
long more = Math.min(nez, rem/a);
rem-= more * a;
more += Math.min(nhard, rem/b);
best = Math.max(best, more);
for(int i = 0; i < n; i++) {
time += arr[i].cost;
amt++;
if (arr[i].cost == a) nez--;
else nhard--;
if ((i == n-1&& time <= t)|| (i < n-1 && arr[i+1].time > time)) {
long extra = 0;
if (i < n-1) {
rem = arr[i + 1].time - time - 1;
more = Math.min(nez, rem / a);
rem -= more * a;
extra += more;
more = Math.min(nhard, rem / b);
extra += more;
}
best = Math.max(best, amt + extra);
}
}
out.println(best);
}
out.flush();
}
static class Tuple implements Comparable<Tuple>{
int num, time;
long cost;
public Tuple(int nn, int tt, long cc) {
num = nn; time = tt; cost = cc;
}
public int compareTo(Tuple o) {
if (time == o.time) {
return Long.compare(cost, o.cost);
}
return time - o.time;
}
} 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;
}
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | 5b59ad4711d388e149cc9ea0a1539bda | train_001.jsonl | 1577198100 | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.The exam consists of $$$n$$$ problems that can be solved in $$$T$$$ minutes. Thus, the exam begins at time $$$0$$$ and ends at time $$$T$$$. Petya can leave the exam at any integer time from $$$0$$$ to $$$T$$$, inclusive.All problems are divided into two types: easy problems — Petya takes exactly $$$a$$$ minutes to solve any easy problem; hard problems — Petya takes exactly $$$b$$$ minutes ($$$b > a$$$) to solve any hard problem. Thus, if Petya starts solving an easy problem at time $$$x$$$, then it will be solved at time $$$x+a$$$. Similarly, if at a time $$$x$$$ Petya starts to solve a hard problem, then it will be solved at time $$$x+b$$$.For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time $$$t_i$$$ ($$$0 \le t_i \le T$$$) at which it will become mandatory (required). If Petya leaves the exam at time $$$s$$$ and there is such a problem $$$i$$$ that $$$t_i \le s$$$ and he didn't solve it, then he will receive $$$0$$$ points for the whole exam. Otherwise (i.e if he has solved all such problems for which $$$t_i \le s$$$) he will receive a number of points equal to the number of solved problems. Note that leaving at time $$$s$$$ Petya can have both "mandatory" and "non-mandatory" problems solved.For example, if $$$n=2$$$, $$$T=5$$$, $$$a=2$$$, $$$b=3$$$, the first problem is hard and $$$t_1=3$$$ and the second problem is easy and $$$t_2=2$$$. Then: if he leaves at time $$$s=0$$$, then he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=1$$$, he will receive $$$0$$$ points since he will not have time to solve any problems; if he leaves at time $$$s=2$$$, then he can get a $$$1$$$ point by solving the problem with the number $$$2$$$ (it must be solved in the range from $$$0$$$ to $$$2$$$); if he leaves at time $$$s=3$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=4$$$, then he will receive $$$0$$$ points since at this moment both problems will be mandatory, but he will not be able to solve both of them; if he leaves at time $$$s=5$$$, then he can get $$$2$$$ points by solving all problems. Thus, the answer to this test is $$$2$$$.Help Petya to determine the maximal number of points that he can receive, before leaving the exam. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Solution(),"Main",1<<27).start();
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long findGCD(long arr[], int n)
{
long result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}
static void sortbycolumn(long[][] arr, int col) {
Arrays.sort(arr, new Comparator<long[]>() {
public int compare(final long[] entry1, final long[] entry2) {
if (entry1[col] > entry2[col]) return 1;
if (entry1[col] < entry2[col]) return -1;
return 0;
}
});
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t=in.nextInt();
while(t--!=0)
{
int n = in.nextInt();
long T = in.nextInt(), a = in.nextInt(), b = in.nextInt(), c0 = 0, c1 = 0;
long sum = 0;
long[][] arr = new long[n][2];
for (int i = 0; i < n; i++) {
arr[i][1] = in.nextInt();
if (arr[i][1] == 0) {
c0++;
sum += a;
} else {
c1++;
sum += b;
}
}
for (int i = 0; i < n; i++) arr[i][0] = in.nextInt();
if (sum <= T) {
w.println(n);
continue;
}
sortbycolumn(arr, 0);
long rem = arr[0][0] - 1, count = 0, r0, r1, can0, can1;
if (rem > 0) {
r0 = c0;
r1 = c1;
can0 = rem / a;
can0 = Math.min(can0, r0);
rem -= can0 * a;
can1 = rem / b;
can1 = Math.min(can1, r1);
count = can0 + can1;
}
long cur0 = 0, cur1 = 0, cur = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i][1] == 0) {
cur0++;
cur += a;
} else {
cur1++;
cur += b;
}
if (cur >= arr[i + 1][0] || cur > T) continue;
rem = arr[i + 1][0] - cur - 1;
r0 = c0 - cur0;
r1 = c1 - cur1;
can0 = rem / a;
can0 = Math.min(can0, r0);
rem -= can0 * a;
can1 = rem / b;
can1 = Math.min(can1, r1);
count = Math.max(count, i + 1 + can0 + can1);
}
w.println(count);
}
w.flush();
w.close();
}
}
| Java | ["10\n3 5 1 3\n0 0 1\n2 1 4\n2 5 2 3\n1 0\n3 2\n1 20 2 4\n0\n16\n6 20 2 5\n1 1 0 1 0 0\n0 8 2 9 11 6\n4 16 3 6\n1 0 1 1\n8 3 5 6\n6 20 3 6\n0 1 0 0 1 0\n20 11 3 20 16 17\n7 17 1 6\n1 1 0 1 0 0 0\n1 7 0 11 10 15 10\n6 17 2 6\n0 0 1 0 0 1\n7 6 3 7 10 12\n5 17 2 5\n1 1 1 1 0\n17 11 10 6 4\n1 1 1 2\n0\n1"] | 2 seconds | ["3\n2\n1\n0\n1\n4\n0\n1\n2\n1"] | null | Java 8 | standard input | [
"two pointers",
"sortings",
"greedy"
] | 6c165390c7f9fee059ef197ef40ae64f | The first line contains the integer $$$m$$$ ($$$1 \le m \le 10^4$$$) — the number of test cases in the test. The next lines contain a description of $$$m$$$ test cases. The first line of each test case contains four integers $$$n, T, a, b$$$ ($$$2 \le n \le 2\cdot10^5$$$, $$$1 \le T \le 10^9$$$, $$$1 \le a < b \le 10^9$$$) — the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively. The second line of each test case contains $$$n$$$ numbers $$$0$$$ or $$$1$$$, separated by single space: the $$$i$$$-th number means the type of the $$$i$$$-th problem. A value of $$$0$$$ means that the problem is easy, and a value of $$$1$$$ that the problem is hard. The third line of each test case contains $$$n$$$ integers $$$t_i$$$ ($$$0 \le t_i \le T$$$), where the $$$i$$$-th number means the time at which the $$$i$$$-th problem will become mandatory. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2\cdot10^5$$$. | 1,800 | Print the answers to $$$m$$$ test cases. For each set, print a single integer — maximal number of points that he can receive, before leaving the exam. | standard output | |
PASSED | 8ee74a5083e0498ef26e98bb4cc18ce1 | train_001.jsonl | 1355047200 | In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time. | 256 megabytes | import java.io.File;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner cin = new Scanner(new File("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int[] count = new int[500];
int n = cin.nextInt();
while (n-- > 0) {
int month = cin.nextInt();
int day = cin.nextInt();
int jury = cin.nextInt();
int days = cin.nextInt();
int preparationDate = 100 + day;
for (int i = 0; i < month - 1; ++i) {
GregorianCalendar c = new GregorianCalendar(2013, i, 1);
preparationDate += c.getActualMaximum(Calendar.DAY_OF_MONTH);
}
for (int i = preparationDate - days; i < preparationDate; ++i) {
count[i] += jury;
}
}
int result = 0;
for (int value : count) {
result = Math.max(result, value);
}
out.println(result);
out.close();
}
}
| Java | ["2\n5 23 1 2\n3 13 2 3", "3\n12 9 2 1\n12 8 1 3\n12 8 2 2", "1\n1 10 1 13"] | 1 second | ["2", "3", "1"] | null | Java 8 | input.txt | [
"implementation",
"brute force"
] | 34655e8de9f1020677c5681d9d217d75 | The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers mi, di, pi and ti — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ mi ≤ 12, di ≥ 1, 1 ≤ pi, ti ≤ 100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year. | 1,500 | Print a single number — the minimum jury size. | output.txt | |
PASSED | 865b0af170b99861cd0149e97eb84b17 | train_001.jsonl | 1355047200 | In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time. | 256 megabytes | /**
* Created with IntelliJ IDEA.
* User: manu
* Date: 09/12/12
* Time: 21:32
* To change this template use File | Settings | File Templates.
*/
import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException
{
new B().run();
}
InputReader in;
PrintWriter out;
public void run() throws IOException
{
in = new InputReader(new FileInputStream("input.txt"));
out = new PrintWriter(new FileOutputStream("output.txt"));
solve();
out.close();
}
int[] cnt = new int[ 465 ];
int[] month = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private void solve() throws IOException
{
int n = in.nextInt();
for (int i=0; i<n; i++)
{
int M = in.nextInt();
int D = in.nextInt();
int P = in.nextInt();
int T = in.nextInt();
int d = 1;
int m = 1;
int j = 100;
while ( d!=D || m!=M )
{
j++;
d++;
if ( d > month[ m ] )
{
d = 1;
m++;
}
}
for (int k=1; k<=T; k++)
{
cnt[ j-k ] += P;
}
}
int ans = 0;
for (int x : cnt) ans = Math.max( ans, x );
out.println( ans );
}
}
class InputReader
{
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next() throws IOException
{
while (st==null || !st.hasMoreTokens())
{
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(next());
}
}
| Java | ["2\n5 23 1 2\n3 13 2 3", "3\n12 9 2 1\n12 8 1 3\n12 8 2 2", "1\n1 10 1 13"] | 1 second | ["2", "3", "1"] | null | Java 6 | input.txt | [
"implementation",
"brute force"
] | 34655e8de9f1020677c5681d9d217d75 | The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers mi, di, pi and ti — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ mi ≤ 12, di ≥ 1, 1 ≤ pi, ti ≤ 100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year. | 1,500 | Print a single number — the minimum jury size. | output.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.