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
ed7d17c9eb17f987f437a255db66bd28
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; import java.util.Vector; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int x =scanner.nextInt(); String str=scanner.next(); int b =0, w=0; for(int i=0;i<x;i++){ if(str.charAt(i)=='B')b++; else w++; } if(b%2==1&&w%2==1){ System.out.println(-1); return; } char goal='W'; if(w%2==1)goal='B'; int ans=0; Vector<Integer >vector=new Vector<>(); Boolean fond=false; for(int i=0;i<x;i++){ if(!fond){ if(str.charAt(i)==goal){ fond=true; } continue; } vector.add(i); if(str.charAt(i)==goal){ fond=false; } } System.out.println(vector.size()); for(int num :vector) System.out.print(num+" "); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
5a6351ce138a459fab46b023d1f5c2ec
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public final class Main { public static void main (String[] args) throws java.lang.Exception { Scanner s = new Scanner(System.in); int n = s.nextInt(); String str = s.next(); char[] strarr = str.toCharArray(); ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2= new ArrayList<>(); for(int i=0;i<str.length()-1;i++){ if(strarr[i] == 'W'){ strarr[i] = 'B'; strarr[i+1] = strarr[i+1] == 'W'?'B':'W'; list1.add(i); } } boolean flag = true; for(int i=0;i<str.length();i++){ if(strarr[i]!='B') { flag= false; break; } } if(flag){ System.out.println(list1.size()); for(int i: list1){ System.out.print(i+1+" "); } return; } strarr = str.toCharArray(); for(int i=0;i<str.length()-1;i++){ if(strarr[i] == 'B'){ strarr[i] = 'W'; strarr[i+1] = strarr[i+1] == 'W'?'B':'W'; list2.add(i); } } flag = true; for(int i=0;i<str.length();i++){ if(strarr[i]!='W') { flag= false; break; } } if(flag){ System.out.println(list2.size()); for(int i: list2){ System.out.print(i+1+" "); } return; } System.out.println(-1); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
2e65a08c8e422aa89a2e05826f0b7df4
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
/* *created by Kraken on 08-04-2020 at 13:21 */ //package com.kraken.cf.cf608; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class B { public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(); char[] x = sc.next().toCharArray(); int nw = 0, nb = 0; for (char i : x) if (i == 'W') nw++; else nb++; if ((nw & 1) != 0 && (nb & 1) != 0) { System.out.println(-1); return; } ArrayList<Integer> res = new ArrayList<>(); if ((nw & 1) == 0) { for (int i = 0; i < n - 1; i++) { if (x[i] == 'W' && x[i + 1] == 'W') { res.add(i); swap(x, i, i + 1); i++; } else if (x[i] == 'W') { res.add(i); swap(x, i, i + 1); } } } else { for (int i = 0; i < n - 1; i++) { if (x[i] == 'B' && x[i + 1] == 'B') { res.add(i); swap(x, i, i + 1); i++; } else if (x[i] == 'B'){ res.add(i); swap(x, i, i + 1); } } } System.out.println(res.size()); StringBuilder sb = new StringBuilder(); for (Integer i : res) sb.append((i + 1) + " "); System.out.println(sb.toString()); } private static void swap(char[] x, int src, int sink) { if (x[src] == 'W') x[src] = 'B'; else x[src] = 'W'; if (x[sink] == 'W') x[sink] = 'B'; else x[sink] = 'W'; } 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
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
dddec2d28d1f5001a1ef4e5ace260ce7
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.math.BigInteger; import java.text.Format; import java.util.Arrays; import java.util.Scanner; public class Main { // final static int N = (int) (1e5 + 10); static int sum; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); char[] a=new char[210]; int [] q=new int[610]; String s=sc.next(); a=s.toCharArray(); int b=0,c=0; for(int i=0;i<n;i++) { if(a[i]=='B') b++; else c++; } if(b==0||c==0) sum=0; else if(b%2!=0&&c%2!=0) { sum=-1; } else { if(b%2==0) { for(int i=0;i<n-1;i++) { if(a[i]=='B') { sum++; q[sum]=i+1; if(a[i+1]=='B') { a[i]='W'; a[i+1]='W'; } else { a[i]='W'; a[i+1]='B'; } } } } else { for(int i=0;i<n-1;i++) { if(a[i]=='W') { sum++; q[sum]=i+1; if(a[i+1]=='W') { a[i]='B'; a[i+1]='B'; i+=1; } else { a[i]='B'; a[i+1]='W'; } } } } } System.out.println(sum); for(int i=1;i<=sum;i++) { System.out.print(q[i]); System.out.print(" "); } System.out.println(); sc.close(); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
a2059c6ba7da10b2bccdfbb73ac1094d
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Q2 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub MScanner s = new MScanner(System.in); int n = s.nextInt(); String str = s.next(); char[] arr = str.toCharArray(); int count_b = 0; int count_w = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == 'B') { count_b++; } else { count_w++; } } if (count_b % 2 != 0 && count_w % 2 != 0) { System.out.println(-1); return; } if (count_b == 0 || count_w == 0) { System.out.println(0); return; } if (blackandwhite(arr, 'B', 'W', count_w, count_b)) { return; } else { System.out.println(-1); } } private static boolean blackandwhite(char[] arr, char c, char d, int w, int b) { // TODO Auto-generated method stub ArrayList<Integer> ans = new ArrayList<Integer>(); if (b % 2 != 0) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] == d) { if (arr[i + 1] == d) { arr[i] = c; arr[i + 1] = c; } else { char temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } ans.add(i + 1); } } } else { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] == c) { if (arr[i + 1] == c) { arr[i] = d; arr[i + 1] = d; } else { char temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } ans.add(i + 1); } } } for (int i = 0; i < arr.length - 1; i++) { if (arr[i] != arr[i + 1]) { return false; } } System.out.println(ans.size()); for (Integer x : ans) { System.out.print(x + " "); } return true; } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } 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); } } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void shuffle(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
af16ff3a2626b95a0c7253a43c3a2e5c
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Q2 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub MScanner s = new MScanner(System.in); int n = s.nextInt(); String str = s.next(); char[] arr = str.toCharArray(); int count_b = 0; int count_w = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == 'B') { count_b++; } else { count_w++; } } if (count_b % 2 != 0 && count_w % 2 != 0) { System.out.println(-1); return; } if (count_b == 0 || count_w == 0) { System.out.println(0); return; } ArrayList<Integer> ans = new ArrayList<Integer>(); if (count_b % 2 != 0) { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] == 'W') { if (arr[i + 1] == 'W') { arr[i] = 'B'; arr[i + 1] = 'B'; } else { char temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } ans.add(i + 1); } } } else { for (int i = 0; i < arr.length - 1; i++) { if (arr[i] == 'B') { if (arr[i + 1] == 'B') { arr[i] = 'W'; arr[i + 1] = 'W'; } else { char temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp; } ans.add(i + 1); } } } System.out.println(); System.out.println(ans.size()); for (int x : ans) { System.out.print(x + " "); } } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] longArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } 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); } } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static void shuffle(long[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); long tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
c1e0eb035f9cb76681e0a1275f58f706
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
//package CodeforcesProject; import java.io.*; import java.lang.*; import java.util.*; import java.util.function.BiFunction; public class Main extends IO { public static void main(String[] args) throws Exception { int quantity = readInt(); String[] base = readArrayString(""); long answer = 0; List<Integer> position = new ArrayList<>(); for (int i = 0; i < quantity; i++) { if (i + 1 < quantity) { if (base[i].equals("B")) { base[i] = "W"; base[i + 1] = base[i + 1].equals("W") ? "B" : "W"; answer++; position.add(i + 1); } } } if (base[quantity - 1].equals("B")) { for (int i = 0; i < quantity; i++) { if (i + 1 < quantity) { if (base[i].equals("W")) { base[i] = "B"; base[i + 1] = base[i + 1].equals("B") ? "W" : "B"; answer++; position.add(i + 1); } } } if (base[quantity - 1].equals("W")) { System.out.println(-1); } else { writeLong(answer, "\n"); writeArray(position.toArray(Integer[]::new), " ", false); print(); } } else { writeLong(answer, "\n"); writeArray(position.toArray(Integer[]::new), " ", false); print(); } } } class math { protected static int remains = 0x989687; protected static int gcd(int a, int b) { // NOD if (b == 0) { return a; } return gcd(b, a % b); } protected static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static float gcd(float a, float b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static double gcd(double a, double b) { if (b == 0) { return a; } return gcd(b, a % b); } protected static double lcm(double a, double b) { // NOK return a / gcd(a, b) * b; } protected static float lcm(float a, float b) { // NOK return a / gcd(a, b) * b; } protected static int lcm(int a, int b) { // NOK return a / gcd(a, b) * b; } protected static long lcm(long a, long b) { return a / gcd(a, b) * b; } protected static double log(double value, int base) { return Math.log(value) / Math.log(base); } protected static long factorial(int number) { if (number < 0) { return 0; } return solveFactorial(number); } private static long solveFactorial(int number) { if (number > 0) { return solveFactorial(number - 1) * number; } return 1; } } class Int implements Comparable<Integer> { protected int value; Int(int value) { this.value = value; } @Override public int compareTo(Integer o) { return (this.value < o) ? -1 : ((this.value == o) ? 0 : 1); } @Override public boolean equals(Object obj) { if (obj instanceof Integer) { return value == (Integer) obj; } return false; } @Override public int hashCode() { return value; } @Override protected void finalize() throws Throwable { super.finalize(); } } class Fraction<T extends Number> extends Pair { private Fraction(T dividend, T divider) { super(dividend, divider); reduce(); } protected static <T extends Number> Fraction<T> createFraction(T dividend, T divider) { return new Fraction<>(dividend, divider); } protected void reduce() { if (getFirstElement() instanceof Integer) { Integer Dividend = (Integer) getFirstElement(); Integer Divider = (Integer) getSecondElement(); int gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Long) { Long Dividend = (Long) getFirstElement(); Long Divider = (Long) getSecondElement(); long gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Float) { Float Dividend = (Float) getFirstElement(); Float Divider = (Float) getSecondElement(); float gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } else if (getFirstElement() instanceof Double) { Double Dividend = (Double) getFirstElement(); Double Divider = (Double) getSecondElement(); double gcd = math.gcd(Dividend, Divider); setFirst(Dividend / gcd); setSecond(Divider / gcd); } } protected void addWithoutReturn(Fraction number) throws UnsupportedOperationException { add(number, 0); } private Fraction add(Fraction number, int function) throws UnsupportedOperationException { if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) { Integer Dividend = (Integer) getFirstElement(); Integer Divider = (Integer) getSecondElement(); Integer Dividend1 = (Integer) number.getFirstElement(); Integer Divider1 = (Integer) number.getSecondElement(); Integer lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) { Long Dividend = (Long) getFirstElement(); Long Divider = (Long) getSecondElement(); Long Dividend1 = (Long) number.getFirstElement(); Long Divider1 = (Long) number.getSecondElement(); Long lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) { Float Dividend = (Float) getFirstElement(); Float Divider = (Float) getSecondElement(); Float Dividend1 = (Float) number.getFirstElement(); Float Divider1 = (Float) number.getSecondElement(); Float lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) { Double Dividend = (Double) getFirstElement(); Double Divider = (Double) getSecondElement(); Double Dividend1 = (Double) number.getFirstElement(); Double Divider1 = (Double) number.getSecondElement(); Double lcm = math.lcm(Divider, Divider1); if (function == 0) { setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1); setSecond(lcm); reduce(); return null; } Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm); result.reduce(); return result; } else { throw new UnsupportedOperationException(); } } protected Fraction addWithReturn(Fraction number) { return add(number, 1); } protected void multiplyWithoutReturn(Fraction number) throws UnsupportedOperationException { multiply(number, 0); } protected Fraction multiplyWithReturn(Fraction number) throws UnsupportedOperationException { return multiply(number, 1); } private Fraction multiply(Fraction number, int function) throws UnsupportedOperationException { if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) { Integer first = (Integer) getFirstElement() * (Integer) number.getFirstElement(); Integer second = (Integer) getSecondElement() * (Integer) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) { Long first = (Long) getFirstElement() * (Long) number.getFirstElement(); Long second = (Long) getSecondElement() * (Long) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) { Float first = (Float) getFirstElement() * (Float) number.getFirstElement(); Float second = (Float) getSecondElement() * (Float) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) { Double first = (Double) getFirstElement() * (Double) number.getFirstElement(); Double second = (Double) getSecondElement() * (Double) number.getSecondElement(); if (function == 0) { setFirst(first); setSecond(second); reduce(); return null; } Fraction answer = Fraction.createFraction(first, second); answer.reduce(); return answer; } else { throw new UnsupportedOperationException(); } } } class Pair<T, T1> implements Cloneable { private T first; private T1 second; Pair(T obj, T1 obj1) { first = obj; second = obj1; } protected static <T, T1> Pair<T, T1> createPair(T element, T1 element1) { return new Pair<>(element, element1); } protected T getFirstElement() { return first; } protected T1 getSecondElement() { return second; } protected void setFirst(T element) { first = element; } protected void setSecond(T1 element) { second = element; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) { return false; } Pair pair = (Pair) obj; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + (first == null ? 0 : first.hashCode()); return 31 * hashCode + (second == null ? 0 : second.hashCode()); } @Override public Object clone() { return Pair.createPair(first, second); } } class Graph { private int[][] base; private boolean[] used; private int quantity; private Integer[] ancestor; public int[][] getBase() { return base.clone(); } public boolean[] getUsed() { return used.clone(); } public int getQuantity() { return quantity; } public Integer[] getAncestor() { return ancestor.clone(); } public void setBase(int[][] base) { this.base = base; } protected void start(int length) { used = new boolean[length]; ancestor = new Integer[length]; Arrays.fill(ancestor, -1); quantity = 0; } protected void edgesMatrixToDefault(int length, int quantity, boolean readConsole, int[][] value) throws Exception { base = new int[length][]; List<ArrayList<Integer>> inputBase = new ArrayList<>(); for (int i = 0; i < length; i++) { inputBase.add(new ArrayList<>()); } for (int i = 0; i < quantity; i++) { int[] input = readConsole ? IO.readArrayInt(" ") : value[i]; inputBase.get(input[0] - 1).add(input[1] - 1); //inputBase.get(input[0] - 1).add(input[2]); // price inputBase.get(input[1] - 1).add(input[0] - 1); //inputBase.get(input[1] - 1).add(input[2]); // price } for (int i = 0; i < length; i++) { base[i] = inputBase.get(i).stream().mapToInt(Integer::intValue).toArray(); } start(length); } protected void adjacencyMatrixToDefault(int length, int not, boolean readConsole, int[][] value) throws Exception { this.base = new int[length][]; List<Integer> buffer = new ArrayList<>(); for (int i = 0; i < length; i++) { int[] InputArray = readConsole ? IO.readArrayInt(" ") : value[i]; for (int index = 0; index < length; index++) { if (i != index && InputArray[index] != not) { buffer.add(index); // buffer.add(InputArray[index]); // price } } this.base[i] = buffer.stream().mapToInt(Integer::intValue).toArray(); buffer.clear(); } start(length); } protected void dfs(int position) throws Exception { used[position] = true; quantity++; int next; for (int index = 0; index < base[position].length; index++) { next = base[position][index]; if (!used[next]) { ancestor[next] = position; dfs(next); } /*else { if (next != ancestor[position]) { // if cycle throw new Exception(); } }*/ } } protected int dijkstra(int start, int stop, int size) { start--; stop--; int[] dist = new int[size]; for (int i = 0; i < size; i++) { if (i != start) { dist[i] = Integer.MAX_VALUE; } ancestor[i] = start; } Queue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt((int[] ints) -> ints[1])); queue.add(new int[]{start, 0}); int position; int[] getQueue; while (queue.size() != 0) { getQueue = queue.poll(); position = getQueue[0]; if (getQueue[1] > dist[position]) { continue; } for (int index = 0; index < this.base[position].length; index += 2) { if (dist[position] + this.base[position][index + 1] < dist[this.base[position][index]] && !this.used[this.base[position][index]]) { dist[this.base[position][index]] = dist[position] + this.base[position][index + 1]; this.ancestor[this.base[position][index]] = position; queue.add(new int[]{this.base[position][index], dist[this.base[position][index]]}); } } used[position] = true; } return dist[stop] == Integer.MAX_VALUE ? -1 : dist[stop]; } protected static boolean solveFloydWarshall(int[][] base, int length, int not) { for (int k = 0; k < length; k++) { for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (base[i][k] == not || base[k][j] == not) { continue; } int total = base[i][k] + base[k][j]; if (base[i][j] != not) { base[i][j] = Math.min(base[i][j], total); } else { base[i][j] = total; } } } } for (int index = 0; index < length; index++) { if (base[index][index] != 0) { // if cycle return false; } } return true; } protected static Pair<Long, int[][]> solveKruskal(int[][] edgesMatrix, final int countVertex, final int indexSort) { int[][] answer = new int[countVertex - 1][2]; long sum = 0; Arrays.sort(edgesMatrix, Comparator.comparingInt(value -> value[indexSort])); SystemOfDisjointSets dsu = new SystemOfDisjointSets(countVertex); for (int i = 0; i < countVertex; i++) { dsu.makeSet(i); } int index = 0; for (int[] value : edgesMatrix) { if (dsu.mergeSets(value[0], value[1])) { sum += value[indexSort]; answer[index] = new int[]{value[0], value[1]}; index++; } } if (index < countVertex - 1) { return Pair.createPair(null, null); } return Pair.createPair(sum, answer); } static class SegmentTree { private int[] segmentArray; private BiFunction<Integer, Integer, Integer> function; protected void setSegmentArray(int[] segmentArray) { this.segmentArray = segmentArray; } protected int[] getSegmentArray() { return segmentArray.clone(); } protected void setFunction(BiFunction<Integer, Integer, Integer> function) { this.function = function; } protected BiFunction<Integer, Integer, Integer> getFunction() { return function; } SegmentTree() { } SegmentTree(int[] startBase, int neutral, BiFunction<Integer, Integer, Integer> function) { this.function = function; int length = startBase.length; int[] base; if ((length & (length - 1)) != 0) { int pow = 0; while (length > 0) { length >>= 1; pow++; } pow--; base = new int[2 << pow]; System.arraycopy(startBase, 0, base, 0, startBase.length); Arrays.fill(base, startBase.length, base.length, neutral); } else { base = startBase; } segmentArray = new int[base.length << 1]; // maybe * 4 Arrays.fill(segmentArray, neutral); inDepth(base, 1, 0, base.length - 1); } private void inDepth(int[] base, int position, int low, int high) { if (low == high) { segmentArray[position] = base[low]; } else { int mid = (low + high) >> 1; inDepth(base, position << 1, low, mid); inDepth(base, (position << 1) + 1, mid + 1, high); segmentArray[position] = function.apply(segmentArray[position << 1], segmentArray[(position << 1) + 1]); } } protected int getValue(int left, int right, int neutral) { return findValue(1, 0, ((segmentArray.length) >> 1) - 1, left, right, neutral); } private int findValue(int position, int low, int high, int left, int right, int neutral) { if (left > right) { return neutral; } if (left == low && right == high) { return segmentArray[position]; } int mid = (low + high) >> 1; return function.apply(findValue(position << 1, low, mid, left, Math.min(right, mid), neutral), findValue((position << 1) + 1, mid + 1, high, Math.max(left, mid + 1), right, neutral)); } protected void replaceValue(int index, int value) { update(1, 0, (segmentArray.length >> 1) - 1, index, value); } private void update(int position, int low, int high, int index, int value) { if (low == high) { segmentArray[position] = value; } else { int mid = (low + high) >> 1; if (index <= mid) { update(position << 1, low, mid, index, value); } else { update((position << 1) + 1, mid + 1, high, index, value); } segmentArray[position] = function.apply(segmentArray[position << 1], segmentArray[(position << 1) + 1]); } } } static class SegmentTreeGeneric<T> { private Object[] segmentArray; private BiFunction<T, T, T> function; protected void setSegmentArray(T[] segmentArray) { this.segmentArray = segmentArray; } protected Object getSegmentArray() { return segmentArray.clone(); } protected void setFunction(BiFunction<T, T, T> function) { this.function = function; } protected BiFunction<T, T, T> getFunction() { return function; } SegmentTreeGeneric() { } SegmentTreeGeneric(T[] startBase, T neutral, BiFunction<T, T, T> function) { this.function = function; int length = startBase.length; Object[] base; if ((length & (length - 1)) != 0) { int pow = 0; while (length > 0) { length >>= 1; pow++; } pow--; base = new Object[2 << pow]; System.arraycopy(startBase, 0, base, 0, startBase.length); Arrays.fill(base, startBase.length, base.length, neutral); } else { base = startBase; } segmentArray = new Object[base.length << 1]; // maybe * 4 Arrays.fill(segmentArray, neutral); inDepth(base, 1, 0, base.length - 1); } private void inDepth(Object[] base, int position, int low, int high) { if (low == high) { segmentArray[position] = base[low]; } else { int mid = (low + high) >> 1; inDepth(base, position << 1, low, mid); inDepth(base, (position << 1) + 1, mid + 1, high); segmentArray[position] = function.apply((T) segmentArray[position << 1], (T) segmentArray[(position << 1) + 1]); } } protected T getValue(int left, int right, T neutral) { return findValue(1, 0, ((segmentArray.length) >> 1) - 1, left, right, neutral); } private T findValue(int position, int low, int high, int left, int right, T neutral) { if (left > right) { return neutral; } if (left == low && right == high) { return (T) segmentArray[position]; } int mid = (low + high) >> 1; return function.apply(findValue(position << 1, low, mid, left, Math.min(right, mid), neutral), findValue((position << 1) + 1, mid + 1, high, Math.max(left, mid + 1), right, neutral)); } protected void replaceValue(int index, T value) { update(1, 0, (segmentArray.length >> 1) - 1, index, value); } private void update(int position, int low, int high, int index, T value) { if (low == high) { segmentArray[position] = value; } else { int mid = (low + high) >> 1; if (index <= mid) { update(position << 1, low, mid, index, value); } else { update((position << 1) + 1, mid + 1, high, index, value); } segmentArray[position] = function.apply((T) segmentArray[position << 1], (T) segmentArray[(position << 1) + 1]); } } } } class SystemOfDisjointSets { private int[] rank; private int[] ancestor; SystemOfDisjointSets(int size) { this.rank = new int[size]; this.ancestor = new int[size]; } protected void makeSet(int value) { ancestor[value] = value; rank[value] = 0; } protected int findSet(int value) { if (value == ancestor[value]) { return value; } return ancestor[value] = findSet(ancestor[value]); } protected boolean mergeSets(int first, int second) { first = findSet(first); second = findSet(second); if (first != second) { if (rank[first] < rank[second]) { int number = first; first = second; second = number; } ancestor[second] = first; if (rank[first] == rank[second]) { rank[first]++; } return true; } return false; } } interface Array { void useArray(int[] a); } interface Method { void use(); } class FastSort { protected static int[] sort(int[] array, int ShellHeapMergeMyInsertionSort) { sort(array, ShellHeapMergeMyInsertionSort, array.length); return array; } protected static int[] sortClone(int[] array, int ShellHeapMergeMyInsertionSort) { int[] base = array.clone(); sort(base, ShellHeapMergeMyInsertionSort, array.length); return base; } private static void sort(int[] array, int ShellHeapMergeMyInsertionSort, int length) { if (ShellHeapMergeMyInsertionSort < 0 || ShellHeapMergeMyInsertionSort > 4) { Random random = new Random(); ShellHeapMergeMyInsertionSort = random.nextInt(4); } if (ShellHeapMergeMyInsertionSort == 0) { ShellSort(array); } else if (ShellHeapMergeMyInsertionSort == 1) { HeapSort(array); } else if (ShellHeapMergeMyInsertionSort == 2) { MergeSort(array, 0, length - 1); } else if (ShellHeapMergeMyInsertionSort == 3) { straightMergeSort(array, length); } else if (ShellHeapMergeMyInsertionSort == 4) { insertionSort(array); } } private static void straightMergeSort(int[] array, int size) { if (size == 0) { return; } int length = (size >> 1) + ((size % 2) == 0 ? 0 : 1); Integer[][] ZeroBuffer = new Integer[length + length % 2][2]; Integer[][] FirstBuffer = new Integer[0][0]; for (int index = 0; index < length; index++) { int ArrayIndex = index << 1; int NextArrayIndex = (index << 1) + 1; if (NextArrayIndex < size) { if (array[ArrayIndex] > array[NextArrayIndex]) { ZeroBuffer[index][0] = array[NextArrayIndex]; ZeroBuffer[index][1] = array[ArrayIndex]; } else { ZeroBuffer[index][0] = array[ArrayIndex]; ZeroBuffer[index][1] = array[NextArrayIndex]; } } else { ZeroBuffer[index][0] = array[ArrayIndex]; } } boolean position = false; int pointer0, pointer, pointer1, number = 4, NewPointer, count; Integer[][] NewBuffer; Integer[][] OldBuffer; length = (size >> 2) + ((size % 4) == 0 ? 0 : 1); while (true) { pointer0 = 0; count = (number >> 1) - 1; if (!position) { FirstBuffer = new Integer[length + length % 2][number]; NewBuffer = FirstBuffer; OldBuffer = ZeroBuffer; } else { ZeroBuffer = new Integer[length + length % 2][number]; NewBuffer = ZeroBuffer; OldBuffer = FirstBuffer; } for (int i = 0; i < length; i++) { pointer = 0; pointer1 = 0; NewPointer = pointer0 + 1; if (length == 1) { for (int g = 0; g < size; g++) { if (pointer > count || OldBuffer[pointer0][pointer] == null) { array[g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) { if (OldBuffer[pointer0][pointer] == null) { continue; } array[g] = OldBuffer[pointer0][pointer]; pointer++; } else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) { array[g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else { array[g] = OldBuffer[pointer0][pointer]; pointer++; } } return; } for (int g = 0; g < number; g++) { if (pointer > count || OldBuffer[pointer0][pointer] == null) { if (OldBuffer[NewPointer][pointer1] == null) { continue; } NewBuffer[i][g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) { if (OldBuffer[pointer0][pointer] == null) { continue; } NewBuffer[i][g] = OldBuffer[pointer0][pointer]; pointer++; } else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) { NewBuffer[i][g] = OldBuffer[NewPointer][pointer1]; pointer1++; } else { NewBuffer[i][g] = OldBuffer[pointer0][pointer]; pointer++; } } pointer0 += 2; } position = !position; length = (length >> 1) + length % 2; number <<= 1; } } private static void ShellSort(int[] array) { int j; for (int gap = (array.length >> 1); gap > 0; gap >>= 1) { for (int i = gap; i < array.length; i++) { int temp = array[i]; for (j = i; j >= gap && array[j - gap] > temp; j -= gap) { array[j] = array[j - gap]; } array[j] = temp; } } } private static void HeapSort(int[] array) { for (int i = (array.length >> 1) - 1; i >= 0; i--) shiftDown(array, i, array.length); for (int i = array.length - 1; i > 0; i--) { swap(array, 0, i); shiftDown(array, 0, i); } } private static void shiftDown(int[] array, int i, int n) { int child; int tmp; for (tmp = array[i]; leftChild(i) < n; i = child) { child = leftChild(i); if (child != n - 1 && (array[child] < array[child + 1])) child++; if (tmp < array[child]) array[i] = array[child]; else break; } array[i] = tmp; } private static int leftChild(int i) { return (i << 1) + 1; } private static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } private static void MergeSort(int[] array, int low, int high) { if (low < high) { int mid = (low + high) >> 1; MergeSort(array, low, mid); MergeSort(array, mid + 1, high); merge(array, low, mid, high); } } private static void merge(int[] array, int low, int mid, int high) { int n = high - low + 1; int[] Temp = new int[n]; int i = low, j = mid + 1; int k = 0; while (i <= mid || j <= high) { if (i > mid) Temp[k++] = array[j++]; else if (j > high) Temp[k++] = array[i++]; else if (array[i] < array[j]) Temp[k++] = array[i++]; else Temp[k++] = array[j++]; } for (j = 0; j < n; j++) array[low + j] = Temp[j]; } private static void insertionSort(int[] elements) { for (int i = 1; i < elements.length; i++) { int key = elements[i]; int j = i - 1; while (j >= 0 && key < elements[j]) { elements[j + 1] = elements[j]; j--; } elements[j + 1] = key; } } } class IO { private static BufferedReader read; private static boolean fileInput = false; private static BufferedWriter write; private static boolean fileOutput = false; public static void setFileInput(boolean fileInput) { IO.fileInput = fileInput; } public static void setFileOutput(boolean fileOutput) { IO.fileOutput = fileOutput; } private static void startInput() { try { read = new BufferedReader(fileInput ? new FileReader("input.txt") : new InputStreamReader(System.in)); } catch (Exception error) { } } private static void startOutput() { try { write = new BufferedWriter(fileOutput ? new FileWriter("output.txt") : new OutputStreamWriter(System.out)); } catch (Exception error) { } } protected static int readInt() throws Exception { if (read == null) { startInput(); } return Integer.parseInt(read.readLine()); } protected static long readLong() throws Exception { if (read == null) { startInput(); } return Long.parseLong(read.readLine()); } protected static String readString() throws Exception { if (read == null) { startInput(); } return read.readLine(); } protected static int[] readArrayInt(String split) throws Exception { if (read == null) { startInput(); } return Arrays.stream(read.readLine().split(split)).mapToInt(Integer::parseInt).toArray(); } protected static long[] readArrayLong(String split) throws Exception { if (read == null) { startInput(); } return Arrays.stream(read.readLine().split(split)).mapToLong(Long::parseLong).toArray(); } protected static String[] readArrayString(String split) throws Exception { if (read == null) { startInput(); } return read.readLine().split(split); } protected static void writeArray(int[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(Integer[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(Int[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Integer.toString(array[index].value)); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(long[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Long.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } protected static void writeArray(Long[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Long.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception error) { } } public static void writeArray(String[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(array[index]); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception ignored) { } } protected static void writeArray(boolean[] array, String split, boolean enter) { if (write == null) { startOutput(); } try { int length = array.length; for (int index = 0; index < length; index++) { write.write(Boolean.toString(array[index])); if (index + 1 != length) { write.write(split); } } if (enter) { writeEnter(); } } catch (Exception ignored) { } } protected static void writeInt(int number, String end) { if (write == null) { startOutput(); } try { write.write(Integer.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeInt(Integer number, String end) { if (write == null) { startOutput(); } try { write.write(Integer.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeLong(long number, String end) { if (write == null) { startOutput(); } try { write.write(Long.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeLong(Long number, String end) { if (write == null) { startOutput(); } try { write.write(Long.toString(number)); write.write(end); } catch (Exception ignored) { } } protected static void writeString(String word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception ignored) { } } protected static void writeBoolean(boolean value, String end) { if (write == null) { startOutput(); } try { write.write(value ? "true" : "false"); write.write(end); } catch (Exception ignored) { } } protected static void writeBoolean(Boolean value, String end) { if (write == null) { startOutput(); } try { write.write(value ? "true" : "false"); write.write(end); } catch (Exception ignored) { } } protected static void writeChar(char word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception ignored) { } } protected static void writeChar(Character word, String end) { if (write == null) { startOutput(); } try { write.write(word); write.write(end); } catch (Exception ignored) { } } protected static void writeEnter() { if (write == null) { startOutput(); } try { write.newLine(); } catch (Exception ignored) { } } protected static void print(boolean exit) throws Exception { if (exit) { print(); } else { write.flush(); } } protected static void print() throws Exception { if (write == null) { return; } write.flush(); if (read != null) { read.close(); } write.close(); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
3d3c29cf44d05ae8ea2b9fb293928da6
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class Main { public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); char[] s = in.next().toCharArray(); char[] c = s.clone(); ArrayList<Integer>id1 = new ArrayList<>(); ArrayList<Integer>id2 = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { if(s[i] == 'W'){ s[i] = 'B'; s[i+1] = s[i+1] == 'W' ? 'B' : 'W'; id1.add(i); } } boolean cn = true; for (int i = 0; i < n; i++) { if(s[i] != 'B')cn = false; } if(cn){ out.println(id1.size()); for(int id : id1)out.print(id+1+ " "); out.close(); return; } for (int i = 0; i < n - 1; i++) { if(c[i] == 'B'){ c[i] = 'W'; c[i+1] = c[i+1] == 'B' ? 'W' : 'B'; id2.add(i); } } cn = true; for (int i = 0; i < n; i++) { if(c[i] != 'W')cn = false; } if(cn){ out.println(id2.size()); for(int id : id2)out.print(id+1+ " "); out.close(); return; } out.println(-1); out.close(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) throws FileNotFoundException { br = new BufferedReader(new FileReader(f)); } FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
cfde3a21d374d36df7e4da38b315d63e
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; public class Codeforces1271B_Real { public static void main(String[] args) { Scanner input = new Scanner(System.in); int length = input.nextInt(); input.nextLine(); String given = input.nextLine(); int countW = 0; int i; for (i = 0; i < given.length(); i++) { if (given.charAt(i) == 'W') countW += 1; } if (length % 2 == 0 && countW % 2 != 0) { System.out.println("-1"); System.exit(0); } int[] todo = new int[3 * length]; int place = 0; for (i = 0; i < given.length() - 1; i++) { if (given.substring(i, i + 2).equals("WB")) { given = given.substring(0, i) + "BW" + given.substring(i + 2); todo[place] = i + 1; place += 1; } if (given.substring(i, i + 2).equals("WW")) { given = given.substring(0, i) + "BB" + given.substring(i + 2); todo[place] = i + 1; place += 1; } } if (given.charAt(length - 1) == 'W') { for (i = 0; i < length / 2; i++) { todo[place] = 2 * i + 1; place += 1; } } int count = 0; for (i = 0; i < 3 * length; i++) { if (todo[i] != 0) count += 1; } System.out.println(count); for (i = 0; i < count; i++) { System.out.print(todo[i] + " "); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
9fe323bec5f97c58189858974c439b8e
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.math.*; import java.io.*; import java.util.*; import java.awt.*; public class CP { public static void main(String[] args) throws Exception { /*new Thread(null, new Runnable() { @Override public void run() { try { new Solver().solve(); } catch (Exception e) { e.printStackTrace(); } } }, "Solver", 1l << 30).start();*/ new Solver().solve(); } } class Solver { final Helper hp; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; Solver() { hp = new Helper(MOD, MAXN); hp.initIO(System.in, System.out); } void solve() throws Exception { int i, j, k; int N = hp.nextInt(); BitSet bs = new BitSet(); char[] C = hp.next().toCharArray(); for (i = 0; i < N; ++i) if (C[i] == 'W') bs.set(i); if (bs.cardinality() % 2 == 1) bs.flip(0, N); ArrayList<Integer> arr = new ArrayList<>(); for (i = 0; i < N - 1; ++i) if (bs.get(i)) { arr.add(i); bs.flip(i, i + 2); } if (bs.cardinality() > 0) hp.println(-1); else { hp.println(arr.size()); for (int itr : arr) hp.printsp(itr + 1); } hp.flush(); } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public String[] getStringArray(int size) throws Exception { String[] ar = new String[size]; for (int i = 0; i < size; ++i) ar[i] = next(); return ar; } public String joinElements(long[] ar) { StringBuilder sb = new StringBuilder(); for (long itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(int[] ar) { StringBuilder sb = new StringBuilder(); for (int itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(String[] ar) { StringBuilder sb = new StringBuilder(); for (String itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public String joinElements(Object[] ar) { StringBuilder sb = new StringBuilder(); for (Object itr : ar) sb.append(itr).append(" "); return sb.toString().trim(); } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long[] ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int[] ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static byte[] buf = new byte[2048]; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String next() throws Exception { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) sb.append((char) c); return sb.toString(); } public int nextInt() throws Exception { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public long nextLong() throws Exception { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') c = scan(); for (; c >= '0' && c <= '9'; c = scan()) val = (val << 3) + (val << 1) + (c & 15); return neg ? -val : val; } public void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
44ed44c3a490fd0f8a550577c61ddbd6
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Blocks { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); String st = s.next(); s.close(); int[] arr = new int[n]; for (int i=0;i<n;i++) arr[i] = st.charAt(i)=='W'?1:0; StringBuilder res = new StringBuilder(); int count =0; for (int i=0;i<n-1;i++) { if (arr[i]==0) { arr[i] = 1; arr[i+1] = arr[i+1]==1?0:1; res.append((i+1)+" "); count++; } } if (arr[n-1]==1) { System.out.println(count); System.out.println(res); return; } count = 0; res = new StringBuilder(); for (int i=0;i<n;i++) arr[i] = st.charAt(i)=='W'?1:0; for (int i=0;i<n-1;i++) { if (arr[i]==1) { arr[i] = 0; arr[i+1] = arr[i+1]==1?0:1; res.append((i+1)+" "); count++; } } if (arr[n-1]==0) { System.out.println(count); System.out.println(res); } else { System.out.println(-1); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
005670f477dc0e114676cd48a80831db
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf131 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 Cf131(),"Main",1<<27).start(); } static class Pair{ int nod; int ucn; Pair(int nod,int ucn){ this.nod=nod; this.ucn=ucn; } public static Comparator<Pair> wc = new Comparator<Pair>(){ public int compare(Pair e1,Pair e2){ //reverse order if(e1.ucn < e2.ucn) return 1; // 1 for swaping. else if (e1.ucn > e2.ucn) return -1; else{ // if(e1.siz>e2.siz) // return 1; // else // return -1; return 0; } } }; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } ////recursive BFS public static int bfsr(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,int[] pre){ b[s]=true; int p = 0; int t = a[s].size(); for(int i=0;i<t;i++){ int x = a[s].get(i); if(!b[x]){ dist[x] = dist[s] + 1; p+= (bfsr(x,a,dist,b,pre)+1); } } pre[s] = p; return p; } //// iterative BFS public static int bfs(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,PrintWriter w){ b[s]=true; int siz = 0; Queue<Integer> q = new LinkedList<>(); q.add(s); while(q.size()!=0){ int i=q.poll(); Iterator<Integer> it = a[i].listIterator(); int z=0; while(it.hasNext()){ z=it.next(); if(!b[z]){ b[z]=true; dist[z] = dist[i] + 1; siz++; q.add(z); } } } return siz; } public static char alter(char x){ if(x=='B')return 'W'; else return 'B'; } ////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////// public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int defaultValue=0; int n = sc.nextInt(); String s = sc.next(); //s = sc.next(); //w.println(s); char[] a = s.toCharArray(); int black = 0; int white = 0; int count = 0; ArrayList<Integer> ans = new ArrayList<Integer>(); boolean poss = true; for(int i=0;i<n;i++){ if(a[i]== 'B')black++; else white++; } if(white%2==1 && black%2==1){ w.print("-1"); } else { if(white%2==1){ //while(black!=0){ for(int i=0;i<n-1;i++){ if(a[i]=='W')continue; else{ count++; ans.add(i+1); a[i] = alter(a[i]); black--; a[i+1] = alter(a[i+1]); if(a[i+1]=='B')black++; } if(black == 0){ break; } } //} } else{ //while(white!=0){ for(int i=0;i<n-1;i++){ if(a[i]=='B')continue; else{ count++; ans.add(i+1); a[i] = alter(a[i]); black--; a[i+1] = alter(a[i+1]); if(a[i+1]=='W')white++; } if(white == 0){ break; } } //} } w.println(count); for(int i=0;i<count;i++){ w.print(ans.get(i)+" "); } w.println(""); } //int t = sc.nextInt(); // while(t-->0){ // } w.flush(); w.close(); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
11179cdc1ab158234eb95ff74c75e48d
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; public class BAy { public static void main(String[] args) { int num; String s; Scanner scan = new Scanner(System.in); num=scan.nextInt(); s=scan.next(); char[] s1 = s.toCharArray(); char[] s2 = s.toCharArray(); int dex=0; int arr[] = new int[num]; for(int i=0;i<num-1;i++){ if(s1[i]=='W'){ s1[i]='B'; arr[dex++]=i+1; if(s1[i+1]=='B'){ s1[i+1]='W'; }else{ s1[i+1]='B'; } } } if(s1[num-1]=='B'){ System.out.println(dex); for(int j=0;j<dex;j++){ System.out.print(arr[j]+ " "); } return; } int dex1=0; int arr1[] = new int[num]; for(int i=0;i<num-1;i++){ if(s2[i]=='B'){ s2[i]='W'; arr1[dex1++]=i+1; if(s2[i+1]=='W'){ s2[i+1]='B'; }else{ s2[i+1]='W'; } } } if(s2[num-1]=='W'){ System.out.println(dex1); for(int j=0;j<dex1;j++){ System.out.print(arr1[j] + " "); } return; } System.out.println("-1"); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
c831c523e9c62f19807392be91fc8824
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF1271B extends PrintWriter { CF1271B() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1271B o = new CF1271B(); o.main(); o.flush(); } int[] qu; int cnt; boolean solve(byte[] aa, int n) { cnt = 0; for (int i = 0; i < n - 1; i++) if (aa[i] == 1) { aa[i] ^= 1; aa[i + 1] ^= 1; qu[cnt++] = i; } return aa[n - 1] == 0; } void main() { int n = sc.nextInt(); byte[] aa = sc.next().getBytes(); byte[] bb = new byte[n]; for (int i = 0; i < n; i++) if (aa[i] == 'B') { aa[i] = 1; bb[i] = 0; } else { aa[i] = 0; bb[i] = 1; } qu = new int[n]; if (solve(aa, n) || solve(bb, n)) { println(cnt); for (int h = 0; h < cnt; h++) print(qu[h] + 1 + " "); println(); } else println(-1); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
d526b4647705cbdf48b12af1d9e8abff
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.*; import java.util.*; 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); Unstoppable solver = new Unstoppable(); //int t=in.nextInt(); //while(t-->0) solver.solve(in, out); out.close(); } static class Unstoppable { public void solve(InputReader in, PrintWriter out) { int n=in.nextInt(); char ch[]=in.next().toCharArray(); int b=0,w=0; ArrayList<Integer> array=new ArrayList<>(); for(int i=0;i<n;i++){ if(ch[i]=='W') w++; else b++; } char c='z'; if(b%2==0&&b>0) c='B'; if(w%2==0&&w>0) c='W'; if(w==0||b==0) out.println("0"); else if(c=='z') out.println("-1"); else{ for(int i=0;i<n-1;i++){ if(ch[i]==c) { if(ch[i]=='W') ch[i]='B'; else ch[i]='W'; if(ch[i+1]=='W') ch[i+1]='B'; else ch[i+1]='W'; array.add(i+1); } } out.println(array.size()); for(int i=0;i<array.size();i++) out.print(array.get(i)+" "); out.println(""); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong(){ return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
0d6ae718a79af95157661dcc9ace4fbc
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { MScanner sc = new MScanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n=sc.nextInt(); char[]in=sc.nextLine().toCharArray(); int b=0;int w=0; for(char x:in) { if(x=='B') { b++; } else { w++; } } if(b%2==1 && w%2==1) { pw.println(-1); } else { char change; char to; if(b%2==0) { change='B'; to='W'; } else { change='W'; to='B'; } int ans=0; StringBuilder p=new StringBuilder(); for(int i=1;i<in.length;i++) { if(in[i]==change && in[i-1]==change) { ans++; p.append((i)+" "); in[i]=to;in[i-1]=to; } else { if(in[i-1]==change) { ans++; p.append((i)+" "); in[i]=change;in[i-1]=to; } } } pw.println(ans); pw.println(p); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] takearr(int n) throws IOException { int[] in = new int[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[] in = new long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[] in = new Integer[n]; for (int i = 0; i < n; i++) in[i] = nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[] in = new Long[n]; for (int i = 0; i < n; i++) in[i] = nextLong(); return in; } 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); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
e349bfbedb83e09b764551ebdf8cd5b5
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.*; public class Main { public static void printAns(Vector<Integer> v) { System.out.println(v.size()); for(Integer i : v) System.out.print(i + " "); } public static void checkInvert(Vector<Integer> v, boolean[] a, int i, int j, int k) { if(a[i] != a[j]) { a[i] = !a[i]; a[k] = !a[k]; v.add(Math.min(i, k) + 1); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String s = scanner.next(); Vector<Integer> v = new Vector<Integer>(); boolean a[] = new boolean[n]; for(int i = 0; i < n; i++) a[i] = (s.charAt(i) == 'B'); for(int i = 1; i < n - 1; i++) checkInvert(v, a, i, i - 1, i + 1); for(int i = n - 2; i > 0; i--) checkInvert(v, a, i, i + 1, i - 1); boolean ans = true; for(int i = 1; i < n; i++) if(a[i] != a[i - 1]) ans = false; if(ans) printAns(v); else System.out.println(-1); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
72f4b8d0ddeb724778fa52c53bd95fcb
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in); int l=in.nextInt(); String x=in.next(); int a[]=new int[l]; int z[]=new int[l]; int b=0,w=0; boolean t=true; for(int i=0;i<l;i++) { if(x.charAt(i)=='B') { b++; a[i]=1; } if(x.charAt(i)=='W') { w++; a[i]=-1; } } if(b%2==1&&w%2==1) { System.out.println(-1); t=false; } int q=0; if(t==true&&w%2==0) { for(int i=0;i<l-1;i++) { if(a[i]==-1) { a[i]=-a[i]; a[i+1]=-a[i+1]; z[q]=i+1; q++; } } System.out.println(q); } if(t==true&&w%2==0&&q!=0) { for(int i=0;i<q;i++) { if(i==0) System.out.print(z[i]); else System.out.print(" "+z[i]); } System.out.println(); } if(t==true&&b%2==0&&w%2==1) { for(int i=0;i<l-1;i++) { if(a[i]==1) { a[i]=-a[i]; a[i+1]=-a[i+1]; z[q]=i+1; q++; } } System.out.println(q); } if(t==true&&b%2==0&&w%2==1&&q!=0) { for(int i=0;i<q;i++) { if(i==0) System.out.print(z[i]); else System.out.print(" "+z[i]); } System.out.println(); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
3434951649c011416b9d00e53c1a013e
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class test { public static void main(String[] args) { // int test = fs.nextInt(); int test = 1; for (int cases = 0; cases < test; cases++) { int n = fs.nextInt(); String s = fs.next(); boolean ans1 = false; boolean ans2 = false; StringBuilder ss = new StringBuilder(s); ArrayList<Integer> ops1 = new ArrayList<Integer>(); ArrayList<Integer> ops2 = new ArrayList<Integer>(); for (int i = 0; i < ss.length() - 1; i++) { if (ss.charAt(i) == 'W') { continue; } else { ss.setCharAt(i, 'W'); ops1.add(i + 1); if (ss.charAt(i + 1) == 'W') { ss.setCharAt(i + 1, 'B'); } else { ss.setCharAt(i + 1, 'W'); } } } if (ss.charAt(n - 1) == 'W') { ans1 = true; } else { StringBuilder sss = new StringBuilder(s); for (int i = 0; i < sss.length() - 1; i++) { if (sss.charAt(i) == 'B') { continue; } else { sss.setCharAt(i, 'B'); ops2.add(i + 1); if (sss.charAt(i + 1) == 'W') { sss.setCharAt(i + 1, 'B'); } else { sss.setCharAt(i + 1, 'W'); } } } if (sss.charAt(n - 1) == 'B') { ans2 = true; } } if (ans1) { op.print(ops1.size() + "\n"); if (!ops1.isEmpty()) { for (Integer integer : ops1) { op.print(integer + " "); } } } else if (ans2) { op.print(ops2.size() + "\n"); if (!ops2.isEmpty()) { for (Integer integer : ops2) { op.print(integer + " "); } } } else { op.print(-1); } op.flush(); } } /* * array list * * ArrayList<Integer> al=new ArrayList<>(); creating BigIntegers * * BigInteger a=new BigInteger(); BigInteger b=new BigInteger(); * * hash map * * HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); for(int * i=0;i<ar.length;i++) { Integer c=hm.get(ar[i]); if(hm.get(ar[i])==null) { * hm.put(ar[i],1); } else { hm.put(ar[i],++c); } } * * while loop * * int t=sc.nextInt(); while(t>0) { t--; } * * array input * * int n = sc.nextInt(); int ar[] = new int[n]; for (int i = 0; i < ar.length; * i++) { ar[i] = sc.nextInt(); } */ static class Graph { HashMap<Character, LinkedList<Character>> hm = new HashMap<Character, LinkedList<Character>>(); private void addVertex(char vertex) { hm.put(vertex, new LinkedList<>()); } private void addEdge(char source, char dest, boolean bi) { if (!hm.containsKey(source)) addVertex(source); if (!hm.containsKey(dest)) addVertex(dest); hm.get(source).add(dest); if (bi) { hm.get(dest).add(source); } } private boolean isCyclicUtil(char ch, boolean visited[], char parent, HashMap<Character, Integer> index) { visited[index.get(ch)] = true; Iterator<Character> it = hm.get(ch).iterator(); while (it.hasNext()) { Character character = (Character) it.next(); if (!visited[index.get(character)]) { if (isCyclicUtil(character, visited, ch, index)) return true; } else if (character != ch) return true; } return false; } private boolean isCyclic(HashMap<Character, Integer> index) { boolean visited[] = new boolean[hm.size()]; Set<Character> set = hm.keySet(); for (Character character : set) { if (!visited[index.get(character)]) { if (isCyclicUtil(character, visited, '-', index)) return true; } } return false; } } static class Node { Node left, right; int data; public Node(int data) { this.data = data; } public void insert(int val) { if (val <= data) { if (left == null) { left = new Node(val); } else { left.insert(val); } } else { if (right == null) { right = new Node(val); } else { right.insert(val); } } } public boolean contains(int val) { if (data == val) { return true; } else if (val < data) { if (left == null) { return false; } else { return left.contains(val); } } else { if (right == null) { return false; } else { return right.contains(val); } } } public void inorder() { if (left != null) { left.inorder(); } System.out.print(data + " "); if (right != null) { right.inorder(); } } public int maxDepth() { if (left == null) return 0; if (right == null) return 0; else { int ll = left.maxDepth(); int rr = right.maxDepth(); if (ll > rr) return (ll + 1); else return (rr + 1); } } public int countNodes() { if (left == null) return 1; if (right == null) return 1; else { return left.countNodes() + right.countNodes() + 1; } } public void preorder() { System.out.print(data + " "); if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } } public void postorder() { if (left != null) { left.inorder(); } if (right != null) { right.inorder(); } System.out.print(data + " "); } public void levelorder(Node node) { LinkedList<Node> ll = new LinkedList<Node>(); ll.add(node); getorder(ll); } public void getorder(LinkedList<Node> ll) { while (!ll.isEmpty()) { Node node = ll.poll(); System.out.print(node.data + " "); if (node.left != null) ll.add(node.left); if (node.right != null) ll.add(node.right); } } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } private static final Scanner sc = new Scanner(System.in); private static final FastReader fs = new FastReader(); private static final OutputWriter op = new OutputWriter(System.out); static int[] getintarray(int n) { int ar[] = new int[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextInt(); } return ar; } static long[] getlongarray(int n) { long ar[] = new long[n]; for (int i = 0; i < n; i++) { ar[i] = fs.nextLong(); } return ar; } static int[][] get2darray(int n, int m) { int ar[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ar[i][j] = fs.nextInt(); } } return ar; } static Pair[] getpairarray(int n) { Pair ar[] = new Pair[n]; for (int i = 0; i < n; i++) { ar[i] = new Pair(fs.nextInt(), fs.nextInt()); } return ar; } static void printarray(int ar[]) { for (int i : ar) { op.print(i + " "); } op.flush(); } static int fact(int n) { int fact = 1; for (int i = 2; i <= n; i++) { fact *= i; } return fact; } // // function to find largest prime factor }/* * 1 5 -2 -3 -1 -4 -6till here */ // while (t > 0) { // int a[] = getintarray(3); // int b[] = getintarray(3); // int ans = getans(a, b); // System.out.println(ans); // }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
34e95bf573060ff5c29ad6fcf5124551
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n =sc.nextInt(); char[] s = sc.next().toCharArray(); if(allSameCharacters(s)){ System.out.println(0); return; } ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n-1;i++){ if(s[i]=='B'){ s[i]='W'; if(s[i+1]=='W'){ s[i+1] = 'B'; }else { s[i+1] = 'W'; } list.add(i+1); } } if(allSameCharacters(s)){ System.out.println(list.size()); for(int a: list){ System.out.printf(a+ " "); } }else { for(int i=n-1;i>0;i--){ if(s[i]=='W'){ s[i]='B'; if(s[i-1]=='W'){ s[i-1] = 'B'; }else { s[i-1] = 'W'; } list.add(i); } } if(allSameCharacters(s)){ System.out.println(list.size()); for(int a: list){ System.out.printf(a+ " "); } }else { System.out.printf("-1"); } } } private static boolean allSameCharacters(char[] s) { for(int i=0;i<s.length-1;i++){ if(s[i]!=s[i+1]){ return false; } } return true; } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
f0c367b47c667fabe3f90e888c45ec7b
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n; String s; Scanner sc = new Scanner(System.in); n=sc.nextInt(); s=sc.next(); char[] s1 = s.toCharArray(); char[] s2 = s.toCharArray(); // All Black int index=0; int arr[] = new int[n]; for(int i=0;i<n-1;i++){ if(s1[i]=='W'){ s1[i]='B'; arr[index]=i+1; index++; if(s1[i+1]=='B'){ s1[i+1]='W'; }else{ s1[i+1]='B'; } } } if(s1[n-1]=='B'){ System.out.println(index); for(int j=0;j<index;j++){ System.out.print(arr[j]+ " "); } return; } // All White int index1=0; int arr1[] = new int[n]; for(int i=0;i<n-1;i++){ if(s2[i]=='B'){ s2[i]='W'; arr1[index1]=i+1; index1++; if(s2[i+1]=='W'){ s2[i+1]='B'; }else{ s2[i+1]='W'; } } } if(s2[n-1]=='W'){ System.out.println(index1); for(int j=0;j<index1;j++){ System.out.print(arr1[j] + " "); } return; } System.out.println("-1"); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
37102404d37d362e0da336505cc152de
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n; String s; Scanner sc = new Scanner(System.in); n=sc.nextInt(); s=sc.next(); char[] s1 = s.toCharArray(); char[] s2 = s.toCharArray(); // All Black int index=0; int arr[] = new int[n]; for(int i=0;i<n-1;i++){ if(s1[i]=='W'){ s1[i]='B'; arr[index]=i+1; index++; if(s1[i+1]=='B'){ s1[i+1]='W'; }else{ s1[i+1]='B'; } } } if(s1[n-1]=='B'){ System.out.println(index); for(int j=0;j<index;j++){ System.out.print(arr[j]+ " "); } return; } // All White int index1=0; int arr1[] = new int[n]; for(int i=0;i<n-1;i++){ if(s2[i]=='B'){ s2[i]='W'; arr1[index1]=i+1; index1++; if(s2[i+1]=='W'){ s2[i+1]='B'; }else{ s2[i+1]='W'; } } } if(s2[n-1]=='W'){ System.out.println(index1); for(int j=0;j<index1;j++){ System.out.print(arr1[j] + " "); } return; } System.out.println("-1"); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
d560dbd4f7d5699fd5f8768c042689cd
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class ProbB { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=0; List<Integer> l = new ArrayList<>(); n = sc.nextInt(); String s = sc.next(); char a[] = s.toCharArray(); int w=0,b=0; for(int i=0;i<a.length;i++) { if(a[i]=='W') w++; else b++; } // System.out.println(a); if(w%2==1 && b%2==1) { System.out.println("-1"); } else { int swaps=0; char goal = a[a.length-1]; boolean flag=false; for(int i=n-2;i>=1;i--) { if(a[i]!=goal) { swaps++; flag=true; if(a[i]=='B') a[i]='W'; else a[i]='B'; if(a[i-1]=='W') a[i-1]='B'; else a[i-1]='W'; l.add(i); // System.out.print(i+" "); } } goal = (goal=='B')?'W':'B'; //System.out.println("GOALLLLLL "+goal); //System.out.println(new String(a)); if(new String(a).contains(goal+"")) { swaps=0; a=s.toCharArray(); //System.out.println("SSSS"); l = new ArrayList<Integer>(); flag=false; for(int i=a.length-1;i>=1;i--) { if(a[i]!=goal) { swaps++; flag=true; if(a[i]=='B') a[i]='W'; else a[i]='B'; if(a[i-1]=='W') a[i-1]='B'; else a[i-1]='W'; l.add(i); // System.out.print(i+" "); } } } if(!flag) System.out.println(0); else { System.out.println(swaps); for(int i=0;i<l.size();i++) { System.out.print(l.get(i)+" "); } } } //System.out.println(new String(a)); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
e50a5af67b4756123b7ab5307421e22c
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int l = sc.nextInt(), last_index=-1, curr_index=-1; char[] arr = sc.next().toCharArray(); String str = new String(); int count_b =0, count_w=0, count=0; for(int i=0; i<l; i++) { if(arr[i]=='W') count_w++; else count_b++; } if(count_w%2==1 && count_b%2==1) { System.out.println("-1"); }else if(count_w%2==0) { for(int i=0; i<l; i++) { if(arr[i]=='W') { if(last_index==-1) last_index=i; else curr_index=i; } if(last_index!=-1 && curr_index!=-1) { for(int j=last_index+1; j<=curr_index; j++) str+=(j+" "); count += (curr_index-last_index); curr_index = last_index = -1; } } System.out.println(count); System.out.println(str); }else { for(int i=0; i<l; i++) { if(arr[i]=='B') { if(last_index==-1) last_index=i; else curr_index=i; } if(last_index!=-1 && curr_index!=-1) { for(int j=last_index+1; j<=curr_index; j++) str+=(j+" "); count += (curr_index-last_index); curr_index = last_index = -1; } } System.out.println(count); System.out.println(str); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
e8155206fc91879c73a1bd781a06525f
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
//package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; //import java.nio.file.Paths; import java.util.*; public class Main { public static void main(String[] args) throws IOException { // write your code here // BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); Scanner s = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int n=s.nextInt();ArrayList<Integer> aans=new ArrayList<Integer>(); char[] a=s.next().toCharArray(); char[] b=a.clone();char[] change=new char[200]; change['B']='W';change['W']='B'; for(int i=0;i<n-1;i++){ if(a[i]=='B'){ a[i]='W';a[i+1]=change[a[i+1]];aans.add(i+1); } }if(a[n-1]=='B'&&a.length%2==0){ System.out.println(-1);System.exit(0); }else if(a[n-1]=='B'){ for(int i=0;i<a.length-1;i+=2){ aans.add(i+1); } } System.out.println(aans.size()); for(int i:aans){ System.out.print(i+" "); } } } class Student { int rollno; int color; // Constructor public Student(int rollno, int color) { this.rollno = rollno; this.color=color;} // Used to print student details in main() public String toString() { return this.rollno + " " ; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b) { return a.color - b.color; } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
006a35b4c46f97314ae7342d7f760902
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.io.*; import java.util.*; public class R608B { public static void main(String[] args) { JS scan = new JS(); int n= scan.nextInt(); char[] s = scan.next().toCharArray(); int w = 0, b= 0 ; for(int i = 0;i<s.length;i++) { if(s[i]=='W')w++; else b++; } ArrayList<Integer> ans = new ArrayList<>(); if(w%2==1 && b%2==1) { System.out.println(-1); return; } else if(w%2==1) { //turn all blacks to white for(int i = 0;i<n;i++) { if(s[i]=='B') { for(int j = i+1 ;j<n;j++) { ans.add(j); if(s[j]=='B') { s[i] = 'W'; s[j] = 'W'; break; } } } } }else { //turn all whites to blacks for(int i = 0;i<n;i++) { if(s[i]=='W') { for(int j = i+1 ;j<n;j++) { ans.add(j); if(s[j]=='W') { s[i] = 'B'; s[j] = 'B'; break; } } } } } System.out.println(ans.size()); for(int i = 0;i<ans.size();i++) { System.out.print(ans.get(i)+" "); } } static class JS{ 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 JS() { in = new BufferedInputStream(System.in, BS); } public JS(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; } } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
11f3165594394ff8a0f69a7f5d26067c
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.*; import java.io.*; public class Main { static final int MOD_PRIME = 1000000007; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); int i = 0; int t = 1; //t = in.nextInt(); for (; i < t; i++) solver.solve(i, in, out); out.close(); } static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); String s = in.next(); char[] ar = s.toCharArray(); int ctr = 0; char trg; for(int i = 0; i < n; i++) { if(s.charAt(i) == 'W') { ctr++; } } if(ctr % 2 == 0) { trg = 'W'; }else if((n-ctr) % 2 == 0) { trg = 'B'; }else { out.println(-1); return; } //System.out.println(trg); ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i = 0; i < n; i++) { //System.out.println(ar[n-1]); if(ar[i] == trg) { ans.add(i); //System.out.println((char)((int)'W' + 'B' - ar[i])); ar[i+1] = (char)((int)'W' + 'B' - ar[i+1]); } } out.println(ans.size()); for(int i = 0; i < ans.size(); i++) { out.print((ans.get(i) + 1) + " "); } } } // template code static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static long modexp(long a, long b, long p) { // returns a to the power b mod p by modular exponentiation long res = 1; long mult = a % p; while (b > 0) { if (b % 2 == 1) { res = (res * mult) % p; } b /= 2; mult = (mult * mult) % p; } return res; } static double log(double arg, double base) { // returns log of a base b, contains floating point errors, dont use for exact // calculations. if (base < 0 || base == 1) { throw new ArithmeticException("base cant be 1 or negative"); } if (arg < 0) { throw new ArithmeticException("log of negative number undefined"); } return Math.log10(arg) / Math.log10(base); } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } // scope for improvement static ArrayList<Integer> sieveOfEratosthenes(int n) { boolean[] check = new boolean[n + 1]; ArrayList<Integer> prime = new ArrayList<Integer>(); for (long i = 2; i <= n; i++) { if (!check[(int) i]) { prime.add((int) i); for (long j = i * i; j <= n; j += i) { check[(int) j] = true; } } } return prime; } static int modInverse(int a, int n) { // returns inverse of a mod n by extended euclidean algorithm int t = 0; int newt = 1; int r = n; int newr = a; int quotient; int tempr, tempt; while (newr != 0) { quotient = r / newr; tempt = newt; tempr = newr; newr = r - quotient * tempr; newt = t - quotient * tempt; t = tempt; r = tempr; } if (r > 1) { throw new ArithmeticException("inverse of " + a + " mod " + n + " does not exist"); } else { if (t < 0) { t += n; } return t; } } static int primeModInverse(int a, int n) { // returns inverse of a mod n by mod exponentiation, use only if n is prime return (int) modexp(a, n - 2, n); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
3d5e510a7b7e57d7819de582fbbf16f3
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int len,len1,flag=0,sum[]=new int[606],k; int b=0,w=0; k=0; len=sc.nextInt(); char str[]=sc.next().toCharArray(); for(int i=0;i<str.length;i++) { if(str[i]=='W') w++; if(str[i]=='B') b++; } if(w==0||b==0) { System.out.println(0); return ; } if(w%2==1&&b%2==1) { System.out.println(-1); return ; } if(w%2==0) { while(flag==0) { for(int i=0;i<str.length;i++) { if(str[i]=='W') { flag=0; str[i]='B'; if(str[i+1]=='W') str[i+1]='B'; else str[i+1]='W'; sum[k++]=i+1; break; } flag=1; } } System.out.println(k); for(int i=0;i<k;i++) { System.out.print(sum[i]+" "); } System.out.println(); }else if(b%2==0) { while(flag==0) { for(int i=0;i<str.length;i++) { if(str[i]=='B') { flag=0; str[i]='W'; if(str[i+1]=='W') str[i+1]='B'; else str[i+1]='W'; sum[k++]=i+1; break; }else flag=1; } } System.out.println(k); for(int i=0;i<k;i++) { System.out.print(sum[i]+" "); } System.out.println(); } } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
2e27bc4ed0bffc5db423114276e22c50
train_001.jsonl
1576401300
There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.
256 megabytes
import java.util.*; public class Blocks{ static Scanner in=new Scanner(System.in); public static void main(String array[]){ int n=in.nextInt(); char ch[]=in.next().toCharArray(); int white=0,black=0; ArrayList<Integer> list=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(ch[i]=='W') white++; else black++; } char c; if(ch[0]==ch[1]) c=ch[0]; else c=ch[1]; if((n%2==0&&(black%2==0&&white%2==0))||(n%2!=0&&((white%2==0&&black%2!=0)||(white%2!=0&&black%2==0)))){ while(true){ for(int i=0;i<n-1;i++){ if(ch[i]!=c){ list.add(i+1); ch[i]=c; ch[i+1]=(ch[i+1]=='B')?'W':'B'; } } if(ch[n-1]==c) break; else c=ch[n-1]; } int size=list.size(); if(size<=3*n){ System.out.println(list.size()); for(int i:list) System.out.print(i+" "); System.out.println(); } else System.out.println(-1); } else System.out.println(-1); } }
Java
["8\nBWWWWWWB", "4\nBWBB", "5\nWWWWW", "3\nBWB"]
2 seconds
["3\n6 2 4", "-1", "0", "2\n2 1"]
NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).
Java 11
standard input
[ "greedy", "math" ]
3336662e6362693b8ac9455d4c2fe158
The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.
1,300
If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.
standard output
PASSED
791448f8f4e7da93588168f7f496907b
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); long arr[]=new long[26]; for(int i=0;i<arr.length;i++) { arr[i]=input.scanInt(); } String str=input.scanString(); System.out.println(solve(arr,str)); } public static long solve(long arr[],String str) { HashMap<Long,Long> map[]=new HashMap[26]; for(int i=0;i<arr.length;i++) { map[i]=new HashMap<>(); } long prefix[]=new long[str.length()]; prefix[0]=arr[str.charAt(0)-97]; for(int i=1;i<str.length();i++) { prefix[i]=prefix[i-1]+arr[str.charAt(i)-97]; } map[str.charAt(0)-97].put(0L, 1L); long ans=0; for(int i=1;i<prefix.length;i++) { if(map[str.charAt(i)-97].containsKey(prefix[i]-2*arr[str.charAt(i)-97])) { ans+=map[str.charAt(i)-97].get(prefix[i]-2*arr[str.charAt(i)-97]); } if(!map[str.charAt(i)-97].containsKey(prefix[i-1])) { map[str.charAt(i)-97].put(prefix[i-1], 0L); } map[str.charAt(i)-97].replace(prefix[i-1], map[str.charAt(i)-97].get(prefix[i-1])+1L); } return ans; } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
4bfa4a56f7bec33acdf040718cb607c5
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import java.util.Scanner; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Kraken */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { long[] x = new long[26]; for (int i = 0; i < 26; i++) x[i] = in.nextLong(); char[] c = in.next().toCharArray(); int n = c.length; Map<Long, Long>[] map = new HashMap[26]; for (int i = 0; i < 26; i++) map[i] = new HashMap<>(); long res = 0; long sum = 0; for (int i = 1; i < n; i++) { int idx = c[i - 1] - 'a'; res += map[idx].getOrDefault(sum, 0L); sum += x[idx]; map[idx].put(sum, map[idx].getOrDefault(sum, 0L) + 1); } res += map[c[n - 1] - 'a'].getOrDefault(sum, 0L); out.println(res); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
89a31593e7c03a7aab217ac5ebc79861
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.*; public class Solution { public static void main(String []args) { Scanner sc = new Scanner(System.in); long arr[] = new long[26]; for(int i = 0 ; i < 26 ; i++) { arr[i] = sc.nextLong(); } sc.nextLine(); String s = sc.nextLine(); int n = s.length(); HashMap<Long,Integer> map = new HashMap<Long,Integer>(); long ans = 0; for(int i = 0 ; i < 26 ; i++) { map.clear(); long sum = 0; for(int j = 0 ; j < n ; j++) { sum += arr[s.charAt(j)-'a']; if(s.charAt(j)-'a' == i) { long dd = sum-arr[i]; if(map.containsKey(dd)) map.replace(dd,map.get(dd)+1); else map.put(dd,1); } } sum = 0; for(int j = 0 ; j < n ; j++) { sum += arr[s.charAt(j)-'a']; if(s.charAt(j)-'a' == i) { if(s.charAt(j)-'a' == i) { if(map.get(sum-arr[i]) == 1) map.remove(sum-arr[i]); else map.replace(sum-arr[i],map.get(sum-arr[i])-1); } if(map.containsKey(sum)) ans += map.get(sum); } } } System.out.println(ans); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
de486671b4b93273be1e989541120ba7
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class AAndBInterestingSubstrings{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int[] arr = new int[26]; HashMap[] freq = new HashMap[26]; for(int i = 0; i<26; i++){ freq[i] = new HashMap<Long, Integer>(); arr[i] = Integer.parseInt(st.nextToken()); } String s = br.readLine(); long[] acc = new long[s.length()+1]; for(int i = 0; i<s.length(); i++){ acc[i+1] = acc[i]+arr[s.charAt(i)-'a']; } long count = 0; for(int i = 0; i<s.length(); i++){ count+=(int)(freq[s.charAt(i)-'a'].getOrDefault(acc[i], 0)); freq[s.charAt(i)-'a'].put(acc[i+1], (Integer)freq[s.charAt(i)-'a'].getOrDefault(acc[i+1], 0)+1); } System.out.println(count); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
3f2ebf5f1c021058b73980317d45df67
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void r(int arr[],int l,int m,int r) { int n1=m-l+1; int n2=r-m; int L[]=new int[n1]; int R[]=new int[n2]; for(int i=0;i<n1;i++) { L[i]=arr[l+i]; } for(int j=0;j<n2;j++) { R[j]=arr[m+1+j]; } int i=0; int j=0; int k=l; while(i<n1 && j<n2) { if(L[i]<=R[j]) { arr[k]=L[i]; ++i; } else{ arr[k]=R[j]; ++j; } ++k; } while(i<n1) { arr[k]=L[i]; ++i; ++k; } while(j<n2) { arr[k]=R[j]; ++j; ++k; } } public static void r2(int arr[],int l,int r) { if(l<r) { int m=(l+r)/2; r2(arr,l,m); r2(arr,m+1,r); r(arr,l,m,r); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static void abc(int n, String s,long arr[]){ HashMap<Long,Integer> map = new HashMap<Long,Integer>(); long total = 0; for(int i = 0 ; i < 26 ; i++) { long sum = 0; map.clear(); for(int j = 0 ; j < n ; j++) { sum += arr[s.charAt(j)-'a']; if(s.charAt(j)-'a' == i) { long dd = sum-arr[i]; if(map.containsKey(dd)) map.replace(dd,map.get(dd)+1); else map.put(dd,1); } } sum = 0; for(int j = 0 ; j < n ; j++) { sum += arr[s.charAt(j)-'a']; if(s.charAt(j)-'a' == i) { if(s.charAt(j)-'a' == i) { if(map.get(sum-arr[i]) == 1) map.remove(sum-arr[i]); else map.replace(sum-arr[i],map.get(sum-arr[i])-1); } if(map.containsKey(sum)) total += map.get(sum); } } } System.out.println(total); } public static void main(String args[]) throws Exception { // try { // // FileOutputStream output=new FileOutputStream("C:\\Users\\icons\\Desktop\\java\\output.txt"); // // PrintStream out=new PrintStream(output); // // Diverting the output stream into file "temp.out".Comment the below line to use console // // System.setOut(out); // InputStream input=new FileInputStream("C:\\Users\\icons\\Desktop\\java\\input.txt"); // //Diverting the input stream into file "temp.in".Comment the below line to use console // System.setIn(input); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } FastReader sc = new FastReader(); long arr[] = new long[26]; for(int i = 0 ; i < 26 ; i++) { arr[i] = sc.nextLong(); } String s = sc.nextLine(); int n = s.length(); abc(n,s,arr); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
ab38d36e4ef65352f470f5529155bf15
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class Main { static PrintWriter out = new PrintWriter(System.out); public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); int cost[]=new int[26]; for (int i = 0; i < cost.length; i++) { cost[i]=sc.nextInt(); } String s=sc.nextLine(); char c[]=s.toCharArray(); int prefix[]=new int[s.length()]; prefix[0]=cost[c[0]-'a']; for (int i = 1; i < prefix.length; i++) { prefix[i]=prefix[i-1]+cost[c[i]-'a']; } HashMap<Long,Long> map[]=new HashMap[26]; for (int i = 0; i < map.length; i++) { map[i]=new HashMap<>(); } long total=0; long cursum=0; for (int i = 0; i < c.length; i++) { total+=map[c[i]-'a'].getOrDefault(cursum,0*1l); cursum+=cost[c[i]-'a']; long z=map[c[i]-'a'].getOrDefault(cursum,0*1l); map[c[i]-'a'].put(cursum,z+1); } System.out.println(total); //System.out.println(set[i].size()); } 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; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
4a670cc070b268e7e77528682c8718be
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
//package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.sql.SQLOutput; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); StringBuilder sb=new StringBuilder(); int[] count=new int[123]; for(int i=97;i<123;i++){ int x=s.nextInt(); count[i]=x; } char [] a=s.next().toCharArray(); long fans=0; HashMap<Long,Integer> pos=new HashMap<Long, Integer>(); long p=0; long [] ans=new long[a.length]; HashMap<Long,Integer>[] map=new HashMap[123]; long sum=0; for(int i=0;i<a.length;i++){ if(map[a[i]]!=null&&map[a[i]].containsKey(sum)){ fans+=map[a[i]].get(sum); } sum+=count[a[i]]; if(map[a[i]]!=null&&map[a[i]].containsKey(sum)){ map[a[i]].put(sum,map[a[i]].get(sum)+1); } else { if(map[a[i]]==null) map[a[i]]=new HashMap<Long,Integer>(); map[a[i]].put(sum,1); } } /*int c=1; for(int i=1;i<a.length;i++){ if(a[i]==a[i-1]) c++; else{ fans+=c-1;c=1; } }if(c>1) fans+=c-1;c=1; */ System.out.println(fans); } static void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else // (pat[i] != pat[len]) { if (len != 0) { len = lps[len - 1]; } else // if (len == 0) { lps[i] = len; i++; } } } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static double power(double x, long y, int p) { double res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static void fracion(double x) { String a = "" + x; String spilts[] = a.split("\\."); // split using decimal int b = spilts[1].length(); // find the decimal length int denominator = (int) Math.pow(10, b); // calculate the denominator int numerator = (int) (x * denominator); // calculate the nerumrator Ex // 1.2*10 = 12 int gcd = (int)gcd((long)numerator, denominator); // Find the greatest common // divisor bw them String fraction = "" + numerator / gcd + "/" + denominator / gcd; // System.out.println((denominator/gcd)); long x1=modInverse(denominator / gcd,998244353 ); // System.out.println(x1); System.out.println((((numerator / gcd )%998244353 *(x1%998244353 ))%998244353 ) ); }static int anst=Integer.MAX_VALUE; static StringBuilder sb1=new StringBuilder(); public static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) { Queue<Integer> q = new LinkedList<Integer>(); q.add(i1);Queue<Integer> aq=new LinkedList<Integer>(); aq.add(0); while(!q.isEmpty()){ int i=q.poll(); int val=aq.poll(); if(i==n){ return val; } if(h[i]!=null){ for(Integer j:h[i]){ if(vis[j]==0){ q.add(j);vis[j]=1; aq.add(val+1);} } } }return -1; } static int i(String a) { return Integer.parseInt(a); } static long l(String a) { return Long.parseLong(a); } static String[] inp() throws IOException { BufferedReader s = new BufferedReader(new InputStreamReader(System.in)); return s.readLine().trim().split("\\s+"); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long modInverse(int a, int m) { { // If a and m are relatively prime, then modulo inverse // is a^(m-2) mode m return (power(a, m - 2, m)); } } // To compute x^y under modulo m static long power(int x, int y, int m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } // Function to return gcd of a and b } class Student { int l;int r; public Student(int l, int r) { this.l = l; this.r = r; } // Constructor // Used to print student details in main() public String toString() { return this.l+" "; } } class Sortbyroll implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b){ if(a.l==b.l) return a.r-b.r; return b.l-a.l; } } class Sortbyroll1 implements Comparator<Student> { // Used for sorting in ascending order of // roll number public int compare(Student a, Student b){ if(a.r==b.r) return a.l-b.l; return b.l-a.l; } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 11
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
0168f1bf8d389907ef873964b6253109
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.BufferedReader; import java.io.Reader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyInput in = new MyInput(inputStream); PrintWriter out = new PrintWriter(outputStream); CArrayBeauty solver = new CArrayBeauty(); solver.solve(1, in, out); out.close(); } static class CArrayBeauty { static final int mod = 998244353; public void solve(int testNumber, MyInput in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int[] a = in.nextIntArray(n); Arrays.sort(a); long ans = 0; long[][] dp = new long[n + 1][k + 1]; for (int i = 1; i <= 100000 / (k - 1); i++) { dp[0][0] = 1; int cur = 0; for (int j = 0; j < n; j++) { while (a[j] - a[cur] >= i) cur++; for (int l = 0; l <= k; l++) dp[j + 1][l] = dp[j][l]; for (int l = 0; l < k; l++) { dp[j + 1][l + 1] += dp[cur][l]; if (dp[j + 1][l + 1] >= mod) dp[j + 1][l + 1] -= mod; } } // if (dp[n][k] != 0) // dump(i, dp[n][k]); ans += dp[n][k]; } out.println(ans % mod); } } static class MyInput { private final BufferedReader in; private static int pos; private static int readLen; private static final char[] buffer = new char[1024 * 8]; private static char[] str = new char[500 * 8 * 2]; private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; private static boolean[] isLineSep = new boolean[256]; static { for (int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; } public MyInput(InputStream is) { in = new BufferedReader(new InputStreamReader(is)); } public int read() { if (pos >= readLen) { pos = 0; try { readLen = in.read(buffer); } catch (IOException e) { throw new RuntimeException(); } if (readLen <= 0) { throw new MyInput.EndOfFileRuntimeException(); } } return buffer[pos++]; } public int nextInt() { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if (str[0] == '-') { i = 1; } for (; i < len; i++) ret = ret * 10 + str[i] - '0'; if (str[0] == '-') { ret = -ret; } return ret; } public char nextChar() { while (true) { final int c = read(); if (!isSpace[c]) { return (char) c; } } } int reads(int len, boolean[] accept) { try { while (true) { final int c = read(); if (accept[c]) { break; } if (str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char) c; } } catch (MyInput.EndOfFileRuntimeException e) { } return len; } public int[] nextIntArray(final int n) { final int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } static class EndOfFileRuntimeException extends RuntimeException { } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
8daa0e4f5a06ad838dc68ed3d84bc97c
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.util.*; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.OutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; public class ArrayBeauty { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { int N = 1005; int n,k,i,j; int mod = 998244353; int[] a = new int[N]; int[][] f = new int[N][N]; public void solve(InputReader in, PrintWriter out) { int o,t,sol=0; n = in.nextInt(); k = in.nextInt(); for (i = 1; i <=n; ++i) a[i] = in.nextInt(); Arrays.sort(a,1,n+1); for (o = 1; o * (k - 1) <= 100005; o++) { f[0][0]=1; t=0; for(i=1;i<=n;i=i+1) { while(a[t+1]+o<=a[i]) t++; f[i][0]=f[i-1][0]; for(j=1;j<=i&&j<=k;j=j+1) f[i][j]=(f[i-1][j]+f[t][j-1])%mod; } sol=(sol+f[n][k])%mod; } out.println(sol); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
895a4741d4613911674576be9e64fd45
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; final int mod = 998244353; int add(int x, int y) { x += y; return x >= mod ? (x - mod) : x; } void solve() { int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int[][] dp = new int[2][n + 1]; int res = 0; for (int minDelta = 1; minDelta * (k - 1) + a[0] <= a[n - 1]; minDelta++) { Arrays.fill(dp[0], 0); dp[0][0] = 1; for (int it = 0; it < k; it++) { int sum = dp[0][0]; dp[1][0] = 0; int posIter = 0; for (int lastValuePos = 0; lastValuePos < n; lastValuePos++) { while (posIter < lastValuePos && a[posIter] + minDelta <= a[lastValuePos]) { posIter++; sum = add(sum, dp[0][posIter]); } dp[1][lastValuePos + 1] = sum; } int[] tmp = dp[0]; dp[0] = dp[1]; dp[1] = tmp; } for (int lastPos = 0; lastPos <= n; lastPos++) { res = add(res, dp[0][lastPos]); } } out.println(res); } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new A().runIO(); } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
0aaa4f29c1deb7905b99eca398483449
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.concurrent.ThreadLocalRandom; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ijxjdjd */ 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); BeautifulArray solver = new BeautifulArray(); solver.solve(1, in, out); out.close(); } static class BeautifulArray { long MOD = 998244353; public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); int[] arr = new int[N + 1]; for (int i = 1; i <= N; i++) { int a = in.nextInt(); arr[i] = a; } arr[0] = -10000000; ArrayUtils.sort(arr); long[] less = new long[100000 / (K - 1) + 1]; int[] low = new int[N + 1]; for (int i = 100000 / (K - 1); i >= 0; i--) { for (int id = 1; id <= N; id++) { while (low[id] < id && arr[id] - arr[low[id]] >= i) { low[id]++; } } long[][] dp = new long[K + 1][N + 1]; Arrays.fill(dp[1], 1); dp[1][0] = 0; for (int v = 1; v <= N; v++) { dp[1][v] += dp[1][v - 1]; } for (int k = 2; k <= K; k++) { for (int v = 1; v <= N; v++) { dp[k][v] += dp[k - 1][low[v] - 1]; dp[k][v] += dp[k][v - 1]; dp[k][v] %= MOD; } } less[i] = dp[K][N] - dp[K][0]; } long ans = 0; ans += less[100000 / (K - 1)] * (100000) / (K - 1); for (int i = 0; i < (100000) / (K - 1); i++) { ans += (less[i] - less[i + 1]) * i; ans %= MOD; } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class ArrayUtils { public static void shuffle(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) MathUtils.mod(ThreadLocalRandom.current().nextInt(), (i + 1)); swap(arr, i, rand); } } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void sort(int[] arr) { shuffle(arr); Arrays.sort(arr); //get rid of quicksort cases } } static class MathUtils { public static long mod(long a, long mod) { return (a + (Math.abs(a) + mod - 1) / mod * mod) % mod; } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
f6845c8bae943e678fe16548c6bb5a48
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
// upsolve with rainboy import java.io.*; import java.util.*; public class CF1188C extends PrintWriter { CF1188C() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1188C o = new CF1188C(); o.main(); o.flush(); } static final int MD = 998244353; void main() { int n = sc.nextInt(); int k = sc.nextInt(); int[] aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = sc.nextInt(); Arrays.sort(aa); int[] dp = new int[n]; int ans = 0; for (int x = 1; x * (k - 1) <= aa[n - 1] - aa[0]; x++) { Arrays.fill(dp, 1); for (int h = 1; h < k; h++) { for (int i = 1; i < n; i++) dp[i] = (dp[i] + dp[i - 1]) % MD; for (int j = n - 1, i = j; j >= 0; j--) { while (i >= 0 && aa[j] - aa[i] < x) i--; dp[j] = i >= 0 ? dp[i] : 0; } } for (int i = 0; i < n; i++) ans = (ans + dp[i]) % MD; } println(ans); } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
3f8033fd29922a51bbf2e7510cc0b075
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Arrays; public class CF1188C { public static void main(String[] args) throws Exception { boolean local = System.getProperty("ONLINE_JUDGE") == null; boolean async = false; Charset charset = Charset.forName("ascii"); FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset); Task task = new Task(io, new Debug(local)); if (async) { Thread t = new Thread(null, task, "dalt", 1 << 27); t.setPriority(Thread.MAX_PRIORITY); t.start(); t.join(); } else { task.run(); } if (local) { io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M"); } io.flush(); } public static class Task implements Runnable { final FastIO io; final Debug debug; int inf = (int) 1e8; public Task(FastIO io, Debug debug) { this.io = io; this.debug = debug; } @Override public void run() { solve(); } public void solve() { Modular modular = new Modular(998244353); int n = io.readInt(); int k = io.readInt(); int[] data = new int[n + 1]; data[0] = -inf; for (int i = 1; i <= n; i++) { data[i] = io.readInt(); } Arrays.sort(data); int[][] dp = new int[k + 1][n + 1]; int[][] prefix = new int[k + 1][n + 1]; dp[0][0] = -inf; Arrays.fill(prefix[0], 1); int[] lastIndex = new int[n + 1]; int total = 0; for (int i = 1; i <= 100000; i++) { if (100000 < i * (k - 1)) { break; } for (int j = 1; j <= n; j++) { lastIndex[j] = lastIndex[j - 1]; while (lastIndex[j] < n && data[lastIndex[j] + 1] + i <= data[j]) { lastIndex[j]++; } } for (int j = 1; j <= k; j++) { for (int t = 1; t <= n; t++) { dp[j][t] = prefix[j - 1][lastIndex[t]]; prefix[j][t] = modular.plus(prefix[j][t - 1], dp[j][t]); } } total = modular.plus(total, prefix[k][n]); } io.cache.append(total); } } /** * Mod operations */ public static class Modular { int m; public Modular(int m) { this.m = m; } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int mul(int x, int y) { return valueOf((long) x * y); } public int mul(long x, long y) { x = valueOf(x); y = valueOf(y); return valueOf(x * y); } public int plus(int x, int y) { return valueOf(x + y); } public int plus(long x, long y) { x = valueOf(x); y = valueOf(y); return valueOf(x + y); } @Override public String toString() { return "mod " + m; } } public static class FastIO { public final StringBuilder cache = new StringBuilder(); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() throws IOException { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } public boolean hasMore() { skipBlank(); return next != -1; } } public static class Debug { private boolean allowDebug; public Debug(boolean allowDebug) { this.allowDebug = allowDebug; } public void assertTrue(boolean flag) { if (!allowDebug) { return; } if (!flag) { fail(); } } public void fail() { throw new RuntimeException(); } public void assertFalse(boolean flag) { if (!allowDebug) { return; } if (flag) { fail(); } } private void outputName(String name) { System.out.print(name + " = "); } public void debug(String name, int x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, long x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, double x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, int[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, long[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, double[] x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.toString(x)); } public void debug(String name, Object x) { if (!allowDebug) { return; } outputName(name); System.out.println("" + x); } public void debug(String name, Object... x) { if (!allowDebug) { return; } outputName(name); System.out.println(Arrays.deepToString(x)); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
1594ca44705cd736f0abfa7d8d4a72d2
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int MOD = 998244353; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); // ways[i][j] = number of ways to build a chain by adding j elements to the chain // starting at i or later int[][] ways = new int[k + 2][n + 1]; long ans = 0; for (int d = 1; d * (k - 1) <= a[n - 1] - a[0]; d++) { for (int[] arr : ways) { Arrays.fill(arr, 0); } ways[0][n] = 1; for (int len = 0; len <= k; len++) { int j = n; for (int i = n - 1; i >= 0; i--) { while (j > i && a[j - 1] - a[i] >= d) { --j; } // take it ways[len + 1][i] += ways[len][j]; if (ways[len + 1][i] >= MOD) { ways[len + 1][i] -= MOD; } // don't take it ways[len][i] += ways[len][i + 1]; if (ways[len][i] >= MOD) { ways[len][i] -= MOD; } } } ans += ways[k][0]; if (ans >= MOD) { ans -= MOD; } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
64868705aa53f1682ab85afec6aaa839
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int MOD = 998244353; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); // ways[i][j] = number of ways to build a chain by adding j elements // to the chain starting at i or later int[][] ways = new int[n + 1][k + 1]; long ans = 0; for (int d = 1; d * (k - 1) <= a[n - 1] - a[0]; d++) { ways[n][0] = 1; int j = n; for (int i = n - 1; i >= 0; i--) { while (j > i && a[j - 1] - a[i] >= d) { --j; } // don't take it System.arraycopy(ways[i + 1], 0, ways[i], 0, ways[i].length); // take it for (int len = 0; len < k; len++) { ways[i][len + 1] += ways[j][len]; if (ways[i][len + 1] >= MOD) { ways[i][len + 1] -= MOD; } } } ans += ways[0][k]; if (ans >= MOD) { ans -= MOD; } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
46bdf252c64a0e4655d95663d1b99fcb
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int MOD = 998244353; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); int[][] ways = new int[n + 1][k + 1]; long ans = 0; for (int d = 1; d * (k - 1) <= a[n - 1] - a[0]; d++) { // ways[i][j] = number of ways to build a chain by adding j elements to the chain // starting at i or later ways[n][0] = 1; int j = n; for (int i = n - 1; i >= 0; i--) { while (j > i && a[j - 1] - a[i] >= d) { --j; } Arrays.fill(ways[i], 0); // take it for (int len = 0; len < k; len++) { ways[i][len + 1] += ways[j][len]; if (ways[i][len + 1] >= MOD) { ways[i][len + 1] -= MOD; } } // don't take it for (int len = 0; len <= k; len++) { ways[i][len] += ways[i + 1][len]; if (ways[i][len] >= MOD) { ways[i][len] -= MOD; } } } ans += ways[0][k]; if (ans >= MOD) { ans -= MOD; } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
4635f6004a6a0beb1737fcbc9737aa5f
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int MOD = 998244353; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); // ways[i][j] = number of ways to build a chain by adding j elements to the chain // starting at i or later int[][] ways = new int[n + 1][k + 2]; long ans = 0; for (int d = 1; d * (k - 1) <= a[n - 1] - a[0]; d++) { for (int[] arr : ways) { Arrays.fill(arr, 0); } ways[n][0] = 1; for (int len = 0; len <= k; len++) { int j = n; for (int i = n - 1; i >= 0; i--) { while (j > i && a[j - 1] - a[i] >= d) { --j; } // take it ways[i][len + 1] += ways[j][len]; if (ways[i][len + 1] >= MOD) { ways[i][len + 1] -= MOD; } // don't take it ways[i][len] += ways[i + 1][len]; if (ways[i][len] >= MOD) { ways[i][len] -= MOD; } } } ans += ways[0][k]; if (ans >= MOD) { ans -= MOD; } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
975d1ae88d92dd3f67f27a00f3ba145f
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int MOD = 998244353; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); // ways[i][j] = number of ways to build a chain by adding j elements to the chain // starting at i or later int[] ways = new int[n + 1]; int[] nways = new int[n + 1]; long ans = 0; for (int d = 1; d * (k - 1) <= a[n - 1] - a[0]; d++) { Arrays.fill(ways, 0); ways[n] = 1; for (int len = 0; len <= k; len++) { Arrays.fill(nways, 0); int j = n; for (int i = n - 1; i >= 0; i--) { while (j > i && a[j - 1] - a[i] >= d) { --j; } nways[i] += ways[j]; if (nways[i] >= MOD) { nways[i] -= MOD; } ways[i] += ways[i + 1]; if (ways[i] >= MOD) { ways[i] -= MOD; } } int[] t = ways; ways = nways; nways = t; } ans += nways[0]; if (ans >= MOD) { ans -= MOD; } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
d786b56419aec4fc2b0e1293b7180058
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int MOD = 998244353; int n = in.nextInt(); int k = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } Arrays.sort(a); // ways[i][j] = number of ways to build a chain that starts // at i or later and contains exactly j elements int[][] ways = new int[n + 1][k + 1]; long ans = 0; for (int d = 1; d * (k - 1) <= a[n - 1] - a[0]; d++) { ways[n][0] = 1; int j = n; for (int i = n - 1; i >= 0; i--) { while (j > i && a[j - 1] - a[i] >= d) { --j; } // don't take element i System.arraycopy(ways[i + 1], 0, ways[i], 0, ways[i].length); // take it for (int len = 0; len < k; len++) { ways[i][len + 1] += ways[j][len]; if (ways[i][len + 1] >= MOD) { ways[i][len + 1] -= MOD; } } } ans += ways[0][k]; if (ans >= MOD) { ans -= MOD; } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
e591dbc2d84bf1c1e9de23ecbe4b212a
train_001.jsonl
1562339100
Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n &gt; 1$$$)  — $$$\min\limits_{1 \leq i &lt; j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); C1188 solver = new C1188(); solver.solve(1, in, out); out.close(); } static class C1188 { int mod = 998244353; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int k = in.scanInt(); int[] ar = new int[n + 1]; for (int i = 1; i <= n; i++) ar[i] = in.scanInt(); ar[0] = Integer.MIN_VALUE / 3; Arrays.sort(ar); long ans = 0; int[][] dp = new int[k + 1][n + 1]; for (int what = 1; what * (k - 1) <= (ar[n]); what++) { for (int i = 0; i <= k; i++) Arrays.fill(dp[i], 0); dp[0][0] = 1; for (int i = 1; i <= k; i++) { int ptr = 0; for (int j = 1; j <= n; j++) dp[i - 1][j] = (dp[i - 1][j] + dp[i - 1][j - 1]) % mod; for (int j = 1; j <= n; j++) { while (ar[j] - ar[ptr] >= what) ptr++; dp[i][j] = (dp[i - 1][ptr - 1]) % mod; } } for (int j = 1; j <= n; j++) ans = (ans + dp[k][j]) % mod; } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"]
5 seconds
["8", "9"]
NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.
Java 8
standard input
[ "dp" ]
624bf3063400fd0c2c466295ff63469b
The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).
2,500
Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.
standard output
PASSED
5d6f03c9e9f46b24399c091d6c34eb93
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
//package com.company.CompititivePrograming; import java.io.*; import java.util.ArrayList; public class AirConditioner { static class Pair { long arrivalTime, reqMin, reqMax; Pair(long arrivalTime, long reqMin, long reqMax) { this.reqMax = reqMax; this.arrivalTime = arrivalTime; this.reqMin = reqMin; } } public static void main(String args[]) throws IOException { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); for (int t = Integer.parseInt(br.readLine()); t > 0; t--) { String items[] = br.readLine().split(" "); long n = Long.parseLong(items[0]); long intialTemp = Long.parseLong(items[1]); ArrayList<Pair> al = new ArrayList<>(); for (int i = 0; i < n; i++) { items = br.readLine().split(" "); al.add(new Pair(Long.parseLong(items[0]), Long.parseLong(items[1]), Long.parseLong(items[2]))); } long possibleMin = intialTemp; long possibleMax = intialTemp; long prevTime = 0; boolean f = true; for (int i = 0; i < n; i++) { long time = al.get(i).arrivalTime; long rMin = al.get(i).reqMin; long rMax = al.get(i).reqMax; long timediff = Math.abs(prevTime - time); if (!(possibleMin - timediff <= rMax && possibleMax + timediff >= rMin)) { f = false; break; } possibleMin = Math.max(possibleMin - timediff, rMin); possibleMax = Math.min(possibleMax + timediff, rMax); prevTime = time; } if (f) { out.write("YES" + "\n"); } else { out.write("NO" + "\n"); } out.flush(); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
ce22ca7300d3ed940825f2c0e56f6cc1
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.*; public class C { private static int n = 0; private static int m = 0; private static int[] time = null; private static int[] lb = null; private static int[] ub = null; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int q = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < q; i++) { String[] strArr = br.readLine().split(" "); n = Integer.parseInt(strArr[0]); m = Integer.parseInt(strArr[1]); time = new int[n]; lb = new int[n]; ub = new int[n]; for (int j = 0; j < n; j++) { String[] strArr2 = br.readLine().split(" "); time[j] = Integer.parseInt(strArr2[0]); lb[j] = Integer.parseInt(strArr2[1]); ub[j] = Integer.parseInt(strArr2[2]); } sb.append(isPossible()).append("\n"); n = 0; m = 0; time = null; lb = null; ub = null; } bw.write(sb.toString()); bw.flush(); bw.close(); br.close(); } private static String isPossible() { String answer = "YES"; int prevLb = lb[n - 1]; int prevUb = ub[n - 1]; for (int i = n - 1; i >= 0; i--) { if(i != 0){ int timeDiff = time[i] - time[i - 1]; int possibleLb = prevLb - timeDiff; int possibleUb = prevUb + timeDiff; prevLb = Math.max(lb[i - 1], possibleLb); prevUb = Math.min(ub[i - 1], possibleUb); if(prevLb > prevUb){ answer = "NO"; break; } }else{ int timeDiff = time[i]; int possibleLb = prevLb - timeDiff; int possibleUb = prevUb + timeDiff; if(possibleLb > m || m > possibleUb){ answer = "NO"; break; } } } return answer; } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
983ac2e48913ee5ff5a66982c7ef17a7
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Random; import java.io.PrintWriter; /* Solution Created: 18:48:01 15/02/2020 Custom Competitive programming helper. */ public class Main { public static void solve(Reader in, Writer out) { int q = in.nextInt(); while(q-->0) { int n = in.nextInt(); int m = in.nextInt(); int curTime = 0; boolean sat = true; int hp = m, lp = m; for(int i = 0; i<n; i++) { int t = in.nextInt(), l = in.nextInt(), h = in.nextInt(); int changes = t-curTime; if(hp+changes<l||lp-changes>h) sat = false; hp = Math.min(h, hp+changes); lp = Math.max(l, lp-changes); curTime = t; } out.println(sat?"YES":"NO"); } } public static void main(String[] args) { Reader in = new Reader(); Writer out = new Writer(); solve(in, out); out.exit(); } static class Graph { private ArrayList<Integer> con[]; private boolean[] visited; public Graph(int n) { con = new ArrayList[n]; for (int i = 0; i < n; ++i) con[i] = new ArrayList(); visited = new boolean[n]; } public void reset() { Arrays.fill(visited, false); } public void addEdge(int v, int w) { con[v].add(w); } public void dfs(int cur) { visited[cur] = true; for (Integer v : con[cur]) { if (!visited[v]) { dfs(v); } } } public void bfs(int cur) { Queue<Integer> q = new LinkedList<>(); q.add(cur); visited[cur] = true; while (!q.isEmpty()) { cur = q.poll(); for (Integer v : con[cur]) { if (!visited[v]) { visited[v] = true; q.add(v); } } } } } static class Reader { static BufferedReader br; static StringTokenizer st; private int charIdx = 0; private String s; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char nextChar() { if (s == null || charIdx >= s.length()) { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } s = st.nextToken(); charIdx = 0; } return s.charAt(charIdx++); } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] nS(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } public static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } static class Solution { public static void solve(Reader in, Writer out) { } } static class Sort { static Random random = new Random(); public static void sortArray(int[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(long[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(String[] s) { shuffle(s); Arrays.sort(s); } public static void sortArray(char[] s) { shuffle(s); Arrays.sort(s); } private static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(String[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); String t = s[i]; s[i] = s[j]; s[j] = t; } } private static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } } static class Util{ static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int upperBound(long[] a, long v) { int l=0, h=a.length-1, ans = -1; while(l<h) { int mid = (l+h)/2; if(a[mid]<=v) { ans = mid; l = mid+1; }else h = mid-1; } return ans; } public static int lowerBound(long[] a, long v) { int l=0, h=a.length-1, ans = -1; while(l<h) { int mid = (l+h)/2; if(v<=a[mid]) { ans = mid; h = mid-1; }else l = mid-1; } return ans; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static long modAdd(long a, long b, long mod) { return (a%mod+b%mod)%mod; } public static long modMul(long a, long b, long mod) { return ((a%mod)*(b%mod))%mod; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
2cbdd5332245dda6caa2850dafb96d81
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
//package Round620; import java.util.Scanner; /** * @author sguar <shugangcao@gmail.com> * welcome to kuaishou * Created on 2020-02-12 */ public class C { public static void main(String[] args) { new C().run(); } private void run() { Scanner cin = new Scanner(System.in); //PrintWriter out = new PrintWriter(System.out); int t = cin.nextInt(); while (t > 0) { t--; int n = cin.nextInt(); int temperature = cin.nextInt(); Customer[] customers = new Customer[n]; for (int i = 0; i < n; i++) { customers[i] = new Customer(cin.nextInt(), cin.nextInt(), cin.nextInt()); } int lastTime = 0; int lowerTemperature = temperature; int highTemperature = temperature; boolean ok = true; for (Customer customer : customers) { //System.out.println(customer); int timeInterval = customer.time - lastTime; lastTime = customer.time; lowerTemperature -= timeInterval; highTemperature += timeInterval; if (lowerTemperature > customer.highTemperature || highTemperature < customer.lowerTemperature) { ok = false; break; } lowerTemperature = Math.max(lowerTemperature, customer.lowerTemperature); highTemperature = Math.min(highTemperature, customer.highTemperature); } //System.out.println(lowerTemperature + "," + highTemperature); if (ok) { System.out.println("YES"); } else { System.out.println("NO"); } } //out.close(); } class Customer implements Comparable<Customer>{ int time; int lowerTemperature; int highTemperature; public Customer(int time, int lowerTemperature, int highTemperature) { this.time = time; this.lowerTemperature = lowerTemperature; this.highTemperature = highTemperature; } @Override public String toString() { return time + "," + lowerTemperature + "," + highTemperature; } @Override public int compareTo(Customer o) { return this.time - o.time; } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
5992afa58df6f0fe22d5a0fa6e119ff0
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
/** * Created by trung.pham on 14/7/19. */ import java.util.*; import java.io.*; public class C_Round_620_Div2 { public static long MOD = 998244353; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int q = in.nextInt(); for (int z = 0; z < q; z++) { int n = in.nextInt(); int m = in.nextInt(); int cur = 0; int low = m; int high = m; boolean ok = true; for (int i = 0; i < n; i++) { int t = in.nextInt(); int l = in.nextInt(); int h = in.nextInt(); int val = t - cur; low -= val; high += val; if (l > high || h < low) { ok = false; //break; } high = Integer.min(high, h); low = Integer.max(low, l); cur = t; } if (ok) { out.println("YES"); } else { out.println("NO"); } } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * (val * a); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
dbbb375ad33ae221113f49cbc201200f
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static long gcd(long n, long m){ if(m > n) return gcd(m,n); if(m == 0) return n; return gcd(m, n%m);} public static long lcm(long m, long n){ return (m/gcd(m,n))*n;} static int mod = 1000000007; static int INF = Integer.MAX_VALUE; static int[] dx = {0,0,1,-1}; static int[] dy = {1,-1,0,0}; static int[] dx8 = {0,0,1,-1,1,1,-1,-1}; static int[] dy8 = {1,-1,0,0,1,-1,-1,1}; public static void main(String[] args){ FastScanner scanner = new FastScanner(); int q = scanner.nextInt(); while(q > 0){ q--; int n = scanner.nextInt(); int m = scanner.nextInt(); int[] t = new int[n]; int[] l = new int[n]; int[] h = new int[n]; for(int i = 0; i < n; i++){ t[i] = scanner.nextInt(); l[i] = scanner.nextInt(); h[i] = scanner.nextInt(); } int min = m; int max = m; boolean flag = true; int time = 0; for(int i = 0; i < n; i++){ max += t[i]-time; min -= t[i]-time; if(max < l[i] || min > h[i]){ flag = false; break; } max = Math.min(max,h[i]); min = Math.max(min,l[i]); time = t[i]; } if(flag){ System.out.println("YES"); }else{ System.out.println("NO"); } } } static class People implements Comparable<People>{ int t; int low; int high; People(int t, int low, int high){ this.t = t; this.low = low; this.high = high; } public int compareTo(People p){ return t-p.t; } } static class Pair2 implements Comparable<Pair2>{ long first; long second; Pair2(long first, long second){ this.first = first; this.second = second; } @Override public int compareTo(Pair2 p){ return Long.valueOf(first).compareTo(Long.valueOf(p.first)); } } static class Edge2 implements Comparable<Edge2>{ int from; int to; double cost; Edge2(int from, int to, double cost){ this.from = from; this.to = to; this.cost = cost; } public int compareTo(Edge2 e){ return Double.compare(cost,e.cost); } } // tar の方が数字が大きいかどうか static boolean compare(String tar, String src) { if (src == null) return true; if (src.length() == tar.length()) { int len = tar.length(); for (int i = 0; i < len; i++) { if (src.charAt(i) > tar.charAt(i)) { return false; } else if (src.charAt(i) < tar.charAt(i)) { return true; } } return tar.compareTo(src) > 0 ? true : false; } else if (src.length() < tar.length()) { return true; } else if (src.length() > tar.length()) { return false; } return false; } static class RMQ { private int size_, dat[]; private int query_(int a, int b, int k, int l, int r) { if(r <= a || b <= l) return 2147483647; if(a <= l && r <= b) return dat[k]; int lc = query_(a, b, 2 * k, l, (l + r) / 2); int rc = query_(a, b, 2 * k + 1, (l + r) / 2, r); return Math.min(lc, rc); } RMQ(int s) { for(size_ = 1; size_ < s;) size_ *= 2; dat = new int[size_ * 2]; for(int i = 0; i < size_ * 2; i++) dat[i] = 2147483647; } public void update(int pos, int x) { pos += size_; dat[pos] = x; while(pos > 1) { pos /= 2; dat[pos] = Math.min(dat[2 * pos], dat[2 * pos + 1]); } } public int query(int l, int r) { return query_(l, r, 1, 0, size_); } } static int size = 2100000; static long[] fac = new long[size]; static long[] finv = new long[size]; static long[] inv = new long[size]; //繰り返し二乗法 public static long pow(long x, long n){ long ans = 1; while(n > 0){ if((n & 1) == 1){ ans = ans * x; ans %= mod; } x = x * x % mod; n >>= 1; } return ans; } public static long div(long x, long y){ return (x*pow(y, mod-2))%mod; } //fac, inv, finvテーブルの初期化、これ使う場合はinitComb()で初期化必要 public static void initComb(){ fac[0] = finv[0] = inv[0] = fac[1] = finv[1] = inv[1] = 1; for (int i = 2; i < size; ++i) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - (mod / i) * inv[(int) (mod % i)] % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } //nCk % mod public static long comb(int n, int k){ return fac[n] * finv[k] % mod * finv[n - k] % mod; } //n! % mod public static long fact(int n){ return fac[n]; } //(n!)^-1 with % mod public static long finv(int n){ return finv[n]; } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ //return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート //return first * 1.0 / second > p.first * 1.0 / p.second ? 1 : -1; // first/secondの昇順にソート //return first * 1.0 / second < p.first * 1.0 / p.second ? 1 : -1; // first/secondの降順にソート //return second * 1.0 / first > p.second * 1.0 / p.first ? 1 : -1; // second/firstの昇順にソート //return second * 1.0 / first < p.second * 1.0 / p.first ? 1 : -1; // second/firstの降順にソート //return Math.atan2(second, first) > Math.atan2(p.second, p.first) ? 1 : -1; // second/firstの昇順にソート //return first + second > p.first + p.second ? 1 : -1; //first+secondの昇順にソート //return first + second < p.first + p.second ? 1 : -1; //first+secondの降順にソート //return first - second < p.first - p.second ? 1 : -1; //first-secondの降順にソート //return second - first < p.second - p.first ? 1 : -1; //first-secondの昇順にソート //return second - first < p.second - p.first ? -1 : 1; //second-firstの昇順にソート //return Math.atan2(second,first) > Math.atan2(p.second, p.first) ? 1 : -1; } } private static 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());} } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
116107fe616324757bb19e7238cac8f9
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.Scanner; import java.util.StringTokenizer; public class temp { String rev(String a) { String ans = ""; for(int i=a.length()-1;i>=0;i--) ans+=a.charAt(i); return ans; } void solve() throws IOException { FastReader sc = new FastReader(); int tt = sc.nextInt(); while(tt-->0) { int N = sc.nextInt(); int M = sc.nextInt(); long curL = M; long curH = M; long last = 0; boolean flag = true; for (int i = 0; i < N; i++) { long t = sc.nextInt(); long l = sc.nextInt(); curL -= (t - last); curH += (t - last); last = t; long h = sc.nextInt(); curL = Math.max(curL, l); curH = Math.min(curH, h); if (curL > curH) { flag = false; } } if (flag) { System.out.println("YES"); } else { System.out.println("NO"); } } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub new temp().solve(); } 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
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
871a65749c419df8fa897b681717c44c
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.*; import java.io.*; public class ac { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int q=sc.nextInt(); while(q-->0){ int n=sc.nextInt(); int m=sc.nextInt(); int t[]=new int[n]; int l[]=new int[n]; int r[]=new int[n]; for(int i=0;i<n;i++){ t[i]=sc.nextInt(); l[i]=sc.nextInt(); r[i]=sc.nextInt(); } int low=m,high=m,f=0,prev=0; for(int i=0;i<n;i++){ high += t[i] - prev; low -= t[i] - prev; if(high<l[i] || low>r[i]){ System.out.println("NO"); f=1; break; } low=(int)Math.max(low,l[i]); high=(int)Math.min(high,r[i]); prev=t[i]; } if(f==0){ System.out.println("YES"); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
fdf4160870cb87ad3d7821f4e8e3e39b
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.Scanner; public class a { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { int count = scanner.nextInt(); int temp = scanner.nextInt(); int up = temp; int low = temp; int nowTime = 0; boolean check = true; for (int j = 0; j < count; j++) { int time = scanner.nextInt(); int lowerBound = scanner.nextInt(); int upperBound = scanner.nextInt(); if (low > upperBound){ if (low-upperBound>time-nowTime){ check = false; } else{ up = upperBound; low = Math.max(lowerBound, low-(time-nowTime)); nowTime=time; } } else if (up<lowerBound){ if (lowerBound-up>time-nowTime){ check = false; } else{ low = lowerBound; up = Math.min(upperBound, up+time-nowTime); nowTime=time; } } else{ up = Math.min(upperBound, up+time-nowTime); low = Math.max(lowerBound, low-time+nowTime); nowTime = time; } } if (check){ System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
838807cafab963080a0a195346a82b65
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.StringTokenizer; public class c620 { static PrintWriter out; static BufferedReader in; static StringTokenizer st; public static void main(String[] args) throws FileNotFoundException { //out = new PrintWriter("test.out"); //in = new BufferedReader(new FileReader("test.in")); out = new PrintWriter(System.out); in = new BufferedReader(new InputStreamReader(System.in)); new c620().Run(); out.close(); } String ns() { try { if (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } catch (Exception e) { return null; } } int nextint() { return Integer.valueOf(ns()); } int N; int v; int t; int timeSum; int maxT; int minT; //int vt; int lo; int hi; visiter [] vis; public void Run() { N = nextint(); while (N-- > 0) { v = nextint(); t = nextint(); vis = new visiter[v]; for (int i = 0; i < v; i++) { vis[i] = new visiter(nextint(), nextint(), nextint()); } maxT = t; minT = t; for (int i = 0; i < v; i++) { if (i == 0) timeSum = vis[i].vt; else timeSum = vis[i].vt - vis[i-1].vt; maxT += timeSum; minT -= timeSum; if (minT <= vis[i].hi && maxT >= vis[i].lo){ maxT = Math.min(maxT, vis[i].hi); minT = Math.max(minT, vis[i].lo); } else {out.println("no"); break;} if (minT > maxT){ out.println("no"); break;} if (i == v-1){ out.println("yes"); } } } } static class visiter{ int vt; int lo; int hi; visiter(int a, int b, int c){ this.vt = a; this.lo = b; this.hi = c; } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
4e8b79a298a4d19e376e6720394e411a
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
/*****Author: Satyajeet Singh************************************/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static ArrayList<Integer> graph[]; static int pptr=0,pptrmax=0; static String st[]; /*****************************************Solution Begins***************************************/ public static void main(String args[]) throws Exception{ int tt=pi(); while(tt-->0){ int n=pi(); long m=pl(); long min=m; long max=m; long p=0; boolean flag=true; for(int i=0;i<n;i++){ long t=pl() - p; long l=pl(); long h=pl(); long c1=min-t; long c4=max+t; // debug(c1,c4); if(c4<l || c1>h){ flag=false; } min=Math.max(l,c1); max=Math.min(h,c4); p+=t; //debug(min,max); } if(flag)out.println("YES"); else out.println("NO"); } /****************************************Solution Ends**************************************************/ clr(); } static void clr(){ out.flush(); out.close(); } static void nl() throws Exception{ pptr=0; st=br.readLine().split(" "); pptrmax=st.length; } static void nls() throws Exception{ pptr=0; st=br.readLine().split(""); pptrmax=st.length; } static int pi() throws Exception{ if(pptr==pptrmax) nl(); return Integer.parseInt(st[pptr++]); } static long pl() throws Exception{ if(pptr==pptrmax) nl(); return Long.parseLong(st[pptr++]); } static double pd() throws Exception{ if(pptr==pptrmax) nl(); return Double.parseDouble(st[pptr++]); } static String ps() throws Exception{ if(pptr==pptrmax) nl(); return st[pptr++]; } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.00000000000"); out.println(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static int countBit(long mask){ int ans=0; while(mask!=0){ mask&=(mask-1); ans++; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; for(int i=0;i<n;i++) graph[i]=new ArrayList<>(); } static void addEdge(int a,int b){ graph[a].add(b); } // static void addEdge(int a,int b,int c){ // graph[a].add(new Pair(b,c)); // } /*********************************************PAIR********************************************************/ static class Pair{ int u; int v; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class Pairl{ long u; long v; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o){ System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c){ long x=1,y=a%c; while(b > 0){ if(b%2 == 1) x=(x*y)%c; y = (y*y)%c; b = b>>1; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y){ if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; b = (x < y) ? x : y; r = b; while(a % b != 0){ r = a % b; a = b; b = r; } return r; } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
ab795595c9af57d5f86f5355a2992c69
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; import java.util.TreeSet; public class Q1 { public static void main(String[] args) { mYScanner in = new mYScanner(); int t = in.nextInt(); for(int i = 0;i<t;i++) { int n = in.nextInt(); long m = in.nextLong(); long low = m; long high = m; long time = 0; long[][] data = new long[n][3]; boolean x = true; for(int j = 0;j<n;j++) { for(int k = 0;k<3;k++) data[j][k] = in.nextLong(); low -=(data[j][0]-time); high+=(data[j][0]-time); if(high<data[j][1] || low>data[j][2]) x=false; else { low = Math.max(low,data[j][1]); high = Math.min(high,data[j][2]); } time = data[j][0]; } if(x) System.out.println("YES"); else System.out.println("NO"); } } } class mYScanner { BufferedReader br ; StringTokenizer st; public mYScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
8920d6bbd6af1e740eb9f5f033981b9d
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
/** * BaZ :D */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class ACMIND { static MyScanner scan; static PrintWriter pw; static long MOD = 1_000_000_007; static long INF = 1_000_000_000_000_000_000L; static long inf = 2_000_000_000; public static void main(String[] args) { new Thread(null, null, "BaZ", 1 << 27) { public void run() { try { solve(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static void solve() throws IOException { //initIo(true); initIo(false); StringBuilder sb = new StringBuilder(); int t = ni(); while (t-->0) { int n = ni(), m = ni(); long max = m, min = m, prev_time = 0; int ans = 0; for(int i=0;i<n;++i) { long time = ni(), l = ni(), r = ni(); if(ans==-1) { continue; } long max_now = max + (time - prev_time); long min_now = min - (time - prev_time); if(max(l, min_now) <= min(r, max_now)) { min = max(l, min_now); max = min(r, max_now); prev_time = time; } else { ans = -1; } } if(ans==-1) { pl("NO"); } else { pl("YES"); } } pw.flush(); pw.close(); } static void initIo(boolean isFileIO) throws IOException { scan = new MyScanner(isFileIO); if(isFileIO) { pw = new PrintWriter("/Users/amandeep/Desktop/output.txt"); } else { pw = new PrintWriter(System.out, true); } } static int ni() throws IOException { return scan.nextInt(); } static long nl() throws IOException { return scan.nextLong(); } static double nd() throws IOException { return scan.nextDouble(); } static String ne() throws IOException { return scan.next(); } static String nel() throws IOException { return scan.nextLine(); } static void pl() { pw.println(); } static void p(Object o) { pw.print(o+" "); } static void pl(Object o) { pw.println(o); } static void psb(StringBuilder sb) { pw.print(sb); } static void pa(String arrayName, Object arr[]) { pl(arrayName+" : "); for(Object o : arr) p(o); pl(); } static void pa(String arrayName, int arr[]) { pl(arrayName+" : "); for(int o : arr) p(o); pl(); } static void pa(String arrayName, long arr[]) { pl(arrayName+" : "); for(long o : arr) p(o); pl(); } static void pa(String arrayName, double arr[]) { pl(arrayName+" : "); for(double o : arr) p(o); pl(); } static void pa(String arrayName, char arr[]) { pl(arrayName+" : "); for(char o : arr) p(o); pl(); } static void pa(String listName, List list) { pl(listName+" : "); for(Object o : list) p(o); pl(); } static void pa(String arrayName, Object[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(Object o : arr[i]) p(o); pl(); } } static void pa(String arrayName, int[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(int o : arr[i]) p(o); pl(); } } static void pa(String arrayName, long[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(long o : arr[i]) p(o); pl(); } } static void pa(String arrayName, char[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(char o : arr[i]) p(o); pl(); } } static void pa(String arrayName, double[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(double o : arr[i]) p(o); pl(); } } static void pa(String arrayName, boolean[][] arr) { pl(arrayName+" : "); for(int i=0;i<arr.length;++i) { for(boolean o : arr[i]) p(o); pl(); } } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(boolean readingFromFile) throws IOException { if(readingFromFile) { br = new BufferedReader(new FileReader("/Users/amandeep/Desktop/input.txt")); } else { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextLine()throws IOException { return br.readLine(); } String next() throws IOException { if(st==null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
72c836d9d7877053740eacf2b832a089
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main (String[] args) { int t; Scanner scan=new Scanner(System.in); t=scan.nextInt(); OUTER: while(t--!=0) { int n; long initial_temp; n=scan.nextInt(); long temp[]=new long[n+1]; long range[][]=new long[n+1][2]; range[0][0]=scan.nextLong(); range[0][1]=range[0][0]; for(int i=1;i<=n;i++) { temp[i]=scan.nextLong(); range[i][0]=scan.nextLong(); range[i][1]=scan.nextLong(); } long l1,h1; l1=range[n][0]-(temp[n]-temp[n-1]); h1=range[n][1]+(temp[n]-temp[n-1]); for(int i=n-1;i>0;i--) { long intervals[][]=new long[2][2]; intervals[0][0]=range[i][0]; intervals[0][1]=range[i][1]; intervals[1][0]=l1; intervals[1][1]=h1; long l = intervals[0][0]; long r = intervals[0][1]; // Check rest of the intervals // and find the intersection for (int u = 1; u < 2; u++) { // If no intersection exists if (intervals[u][0] > r || intervals[u][1] < l) { System.out.println("NO"); continue OUTER; } // Else update the intersection else { l = Math.max(l, intervals[u][0]); r = Math.min(r, intervals[u][1]); } } l1=l; h1=r; l1=l1-(temp[i]-temp[i-1]); h1=h1+(temp[i]-temp[i-1]); } if(range[0][0]<=h1 && range[0][0]>=l1) { //System.out.println(l1+" "+h1); System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
e1b3e6fbbcfc368052179d61afed6a17
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces{ public static pair update(pair curr,long a,long b) { curr.s=Math.max(curr.s,a); curr.e=Math.min(curr.e,b); return curr; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tst=Integer.parseInt(br.readLine()); while(tst-->0) { String line = br.readLine(); String[] strs = line.trim().split("\\s+"); long n=Long.parseLong(strs[0]); long m=Long.parseLong(strs[1]); // System.out.println(tst+" "+n+" "+m); pair curr=new pair(); long prev=0; curr.s=m; curr.e=m; boolean flag=false; for(int i=0;i<n;i++) { String line1 = br.readLine(); String strs1[] = line1.trim().split("\\s+"); long t=Long.parseLong(strs1[0]); long a=Long.parseLong(strs1[1]); long b=Long.parseLong(strs1[2]); if(flag==true) { continue; } long diff=t-prev; curr.s-=diff; curr.e+=diff; // System.out.println(curr.s+" "+curr.e+" "+a+" "+b); if(!((a>=curr.s && a<=curr.e)||(b>=curr.s && b<=curr.e)) && !((a<=curr.s && b>=curr.s)||(a<=curr.e && b>=curr.e))) { System.out.println("NO"); flag=true; // break; } curr=update(curr,a,b); prev=t; } if(flag==false) { System.out.println("YES"); } } br.close(); } static class pair { long s; long e; } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
0dc5220f029cffadc75805ce92f053d6
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); while(t-->0) { boolean sangam=true; String s[]=bf.readLine().split(" "); long n=Long.parseLong(s[0]); long m=Long.parseLong(s[1]); long currentlower=m; long currentupper=m; long time1=0L; for(int i=0;i<n;i++) { String s1[]=bf.readLine().split(" "); long time=Long.parseLong(s1[0]); long lower=Long.parseLong(s1[1]); long upper=Long.parseLong(s1[2]); long change=time-time1; currentlower=currentlower-change; currentupper=currentupper+change; // System.out.println("1 "+currentlower+" "+currentupper+" "+change); if((currentlower<=lower && lower<=currentupper) || (currentlower<=upper && upper<=currentupper) || (lower<=currentlower && currentlower<=upper) || (lower<=currentupper && currentupper<=upper)) { // System.out.println("sangam "+i); } else { sangam=false; // break; } currentlower=Math.max(currentlower,lower); currentupper=Math.min(currentupper,upper); // System.out.println("2 "+currentlower+" "+currentupper+" "+change); time1=time; } if(sangam) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
ee482ed7ab1a31cab79b9af0de812332
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
//package com.pb.codeforces.practice; import java.util.Scanner; public class CF1304C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-- > 0) { int n = in.nextInt(); long s = in.nextInt(); long e = s; long pt = 0; boolean possible = true; int i = 0; for(;i<n; i++) { long ct = in.nextInt(); long min = in.nextInt(); long max = in.nextInt(); long ts = s - (ct - pt); long te = e + (ct - pt); if(possible && (max < ts || min > te)) { possible = false;} s = Math.max(ts, min); e = Math.min(te, max); pt = ct; } if(possible) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
68199d11b7e8ad8b916956b09aed6156
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.*; import java.util.*; public class Sol{ final public static int INF = Integer.MAX_VALUE; public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int q = sc.nextInt(); while(q-->0) { int n = sc.nextInt(); int m= sc.nextInt(); int state = 0; int r = m; int l = m; int p[][] = new int[n][3]; for(int i=0; i<n; i++) { p[i][0] = sc.nextInt(); p[i][1] = sc.nextInt(); p[i][2] = sc.nextInt(); } boolean pos = true; for(int i=0; i<n; i++) { if(p[i][1]<=l&&p[i][2]>=l||p[i][1]<=r&&p[i][2]>=r) { int t = p[i][0]-state; l = Math.max(l-t, p[i][1]); r = Math.min(r+t,p[i][2]); state = p[i][0]; }else if(l<=p[i][1]&&r>=p[i][2]) { state = p[i][0]; l = p[i][1]; r = p[i][2]; }else if(p[i][1]>r) { int t = p[i][0]-state; l = p[i][1]; r = Math.min(r+t, p[i][2]); if(r<p[i][1]) { pos = false; break; } state = p[i][0]; }else if(p[i][2]<l) { int t = p[i][0]-state; r = p[i][2]; l = Math.max(l-t, p[i][1]); if(l>p[i][2]) { pos = false; break; } state = p[i][0]; } //System.out.println(r + " best right " + l + " best left"); } if(!pos) System.out.println("NO"); else System.out.println("YES"); } out.close(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
dfb6d7453f0dc4bff82448958d4b35fd
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * https://codeforces.com/contest/1304/problem/C */ public class C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = Integer.parseInt(in.nextLine()); for (int i = 0; i < q; i++) { String[] strings = in.nextLine().split(" "); int n = Integer.parseInt(strings[0]); int m = Integer.parseInt(strings[1]); List<Visitor> visitors = new ArrayList<>(n); for (int j = 0; j < n; j++) { strings = in.nextLine().split(" "); visitors.add(new Visitor(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2]))); } System.out.println(getAnswer(m, visitors)); } } private static String getAnswer(int m, List<Visitor> visitors) { for (int i = 1; i < visitors.size(); i++) { Visitor prev = visitors.get(i - 1); Visitor cur = visitors.get(i); if (prev.t == cur.t) { if (prev.l > cur.h || cur.l > prev.h) { return "NO"; } prev.l = Math.max(prev.l, cur.l); prev.h = Math.min(prev.h, cur.h); visitors.remove(i); i--; } } int min = m; int max = m; for (int i = 0; i < visitors.size(); i++) { Visitor visitor = visitors.get(i); int time = i == 0 ? visitor.t : visitor.t - visitors.get(i - 1).t; min = min - time; max = max + time; if (min > visitor.h || visitor.l > max) { return "NO"; } min = Math.max(min, visitor.l); max = Math.min(max, visitor.h); } return "YES"; } static class Visitor { int t; int l; int h; Visitor(int t, int l, int h) { this.t = t; this.l = l; this.h = h; } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
a84004e682b29f4560bfb109f232c3d5
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { //static final long MOD = 998244353L; //static final long INF = -1000000000000000007L; static final long MOD = 1000000007L; //static final int INF = 1000000007; static long[] factorial; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); long M = sc.nl(); long[] range = new long[]{M,M}; //minimum and maximal temperature inclusive long[][] nums = new long[N][3]; for (int i = 0; i < N; i++) { for (int j = 0; j < 3; j++) nums[i][j] = sc.nl(); } nums = sort(nums); long time = 0; String ans = "YES"; for (int i = 0; i < N; i++) { long past = nums[i][0]-time; //time passes range[0] -= past; range[1] += past; if (range[1] < nums[i][1] || range[0] > nums[i][2]) { ans = "NO"; break; } //pw.println(Arrays.toString(range)); if (range[0] <= nums[i][1] && nums[i][2] <= range[1]) { range[0] = nums[i][1]; range[1] = nums[i][2]; } else if (nums[i][1] <= range[0] && range[1] <= nums[i][2]) { //change nothing } else if (nums[i][1] <= range[0] && range[0] <= nums[i][2]) { range[1] = nums[i][2]; } else if (range[0] <= nums[i][1] && nums[i][1] <= range[1]) { range[0] = nums[i][1]; } //pw.println(Arrays.toString(range)); time += past; } pw.println(ans); } pw.close(); } public static long dist(long[] p1, long[] p2) { return (Math.abs(p2[0]-p1[0])+Math.abs(p2[1]-p1[1])); } //Find the GCD of two numbers public static long gcd(long a, long b) { if (a < b) return gcd(b,a); if (b == 0) return a; else return gcd(b,a%b); } //Fast exponentiation (x^y mod m) public static long power(long x, long y, long m) { if (y < 0) return 0L; long ans = 1; x %= m; while (y > 0) { if(y % 2 == 1) ans = (ans * x) % m; y /= 2; x = (x * x) % m; } return ans; } public static int[][] shuffle(int[][] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return b[0]-a[0]; //descending order } }); return array; } public static long[][] sort(long[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] < b[0]) return -1; else return 1; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
166185f75557eeb7e2582b18f34cf793
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* */ import java.util.*; import java.io.*; public class C2 { public static void main(String omkar[]) throws Exception { //BufferedReader infile = new BufferedReader(new FileReader("cowdate.in")); BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int Q = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); outer:for(int qw=0; qw < Q; qw++) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); Cust[] arr = new Cust[N]; for(int i=0; i < N; i++) { st = new StringTokenizer(infile.readLine()); int t = Integer.parseInt(st.nextToken()); int l = Integer.parseInt(st.nextToken()); int h = Integer.parseInt(st.nextToken()); arr[i] = new Cust(t,l,h); } Arrays.sort(arr); int boof = arr[0].time; int currL = M-boof; int currR = M+boof; if(currL > arr[0].high || currR < arr[0].low) { sb.append("NO\n"); continue outer; } currL = Math.max(currL, arr[0].low); currR = Math.min(currR, arr[0].high); for(int i=1; i < N; i++) { int time = arr[i].time-arr[i-1].time; int temp1 = currL-time; int temp2 = currR+time; if(temp1 > arr[i].high || temp2 < arr[i].low) { sb.append("NO\n"); continue outer; } if(temp1 < arr[i].low) currL = arr[i].low; else currL = temp1; // if(temp2 > arr[i].high) currR = arr[i].high; else currR = temp2; } sb.append("YES\n"); } System.out.print(sb); } public static Cust[] compress(Cust[] arr) { int N = arr.length; ArrayList<Integer> dex = new ArrayList<Integer>(); dex.add(0); for(int i=1; i < N; i++) if(arr[i].time != arr[i-1].time) dex.add(i); ArrayList<Cust> ls = new ArrayList<Cust>(); dex.add(N); int newN = dex.size(); for(int a=0; a < newN-1; a++) { int l = dex.get(a); int r = dex.get(a+1); int low = arr[l].low; int high = arr[l].high; for(int i=l; i < r; i++) { low = Math.max(low, arr[i].low); high = Math.min(high, arr[i].high); } ls.add(new Cust(arr[l].time, low, high)); } Cust[] arrt = new Cust[ls.size()]; for(int i=0; i < ls.size(); i++) arrt[i] = ls.get(i); return arrt; } public static boolean can(int time, int target, int curr) { return time >= Math.abs(target-curr); } } class Cust implements Comparable<Cust> { public int time; public int low; public int high; public Cust(int a, int b, int c) { time = a; low = b; high = c; } public int compareTo(Cust oth) { return time-oth.time; } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
5caa36d9cb50f4ad63049772f9261f83
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static class pair{ int x; int y; } 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){ String line=br.readLine(); String[] strs=line.trim().split(" "); int n=Integer.parseInt(strs[0]); int m=Integer.parseInt(strs[1]); int[][] arr=new int[n][3]; for(int i=0;i<n;i++){ line=br.readLine(); strs=line.trim().split(" "); arr[i][0]=Integer.parseInt(strs[0]); arr[i][1]=Integer.parseInt(strs[1]); arr[i][2]=Integer.parseInt(strs[2]); } int c=0; int l1=m-arr[0][0]; int r1=m+arr[0][0]; for(int i=0;i<n;i++){ if(r1<arr[i][1]||l1>arr[i][2]){ System.out.println("NO"); c=1; break; }else if(r1<=arr[i][2]&&l1>=arr[i][1]|| r1>=arr[i][2]&&l1<=arr[i][1]){ if(r1<=arr[i][2]&&l1>=arr[i][1]){ if(i+1<n){ int diff=arr[i+1][0]-arr[i][0]; l1-=diff; r1+=diff; } }else{ l1=arr[i][1]; r1=arr[i][2]; if(i+1<n){ int diff=arr[i+1][0]-arr[i][0]; l1-=diff; r1+=diff; } } }else{ if(l1>=arr[i][1]&&l1<=arr[i][2]){ r1=arr[i][2]; if(i+1<n){ int diff=arr[i+1][0]-arr[i][0]; l1-=diff; r1+=diff; } }else{ l1=arr[i][1]; if(i+1<n){ int diff=arr[i+1][0]-arr[i][0]; l1-=diff; r1+=diff; } } } // System.out.println(l1+" "+r1); } if(c==0){ System.out.println("YES"); } // int l1=Integer.MIN_VALUE,r1=-1,l2=-1,r2=-1; // boolean q1=false; // boolean q2=false; // int c=0; // for(int i=n-1;i>0;i--){ // if(l1==Integer.MIN_VALUE){ // int diff=arr[i][0]-arr[i-1][0]; // l1=arr[i][1]-diff; // r1=arr[i][1]+diff; // l2=arr[i][2]-diff; // r2=arr[i][2]+diff; // if(r1<arr[i-1][1]||l1>arr[i-1][2]){ // q1=true; // }else if(r1<=arr[i-1][2]&&l1>=arr[i-1][1]|| // r1>=arr[i-1][2]&&l1<=arr[i-1][1]){ // if(r1<=arr[i-1][2]&&l1>=arr[i-1][1]){ // }else{ // l1=arr[i-1][1]; // r1=arr[i-1][2]; // } // }else{ // if(l1>=arr[i-1][1]&&l1<=arr[i-1][2]){ // r1=arr[i-1][2]; // }else{ // l1=arr[i-1][1]; // } // } // if(r2<arr[i-1][1]||l2>arr[i-1][2]){ // q2=true; // }else if(r2<=arr[i-1][2]&&l2>=arr[i-1][1]|| // r2>=arr[i-1][2]&&l2<=arr[i-1][1]){ // if(r2<=arr[i-1][2]&&l2>=arr[i-1][1]){ // }else{ // l2=arr[i-1][1]; // r2=arr[i-1][2]; // } // }else{ // if(l2>=arr[i-1][1]&&l2<=arr[i-1][2]){ // r2=arr[i-1][2]; // }else{ // l2=arr[i-1][1]; // } // } // if(q1&&q2){ // System.out.println("NO"); // c=1; // break; // } // }else{ // if(q1&&q2){ // System.out.println("NO"); // c=1; // break; // } // if(!q1){ // // System.out.println("Hello"); // if(r1<arr[i-1][1]||l1>arr[i-1][2]){ // q1=true; // }else if(r1<=arr[i-1][2]&&l1>=arr[i-1][1]|| // r1>=arr[i-1][2]&&l1<=arr[i-1][1]){ // // System.out.println("Hello"); // if(r1<=arr[i-1][2]&&l1>=arr[i-1][1]){ // }else{ // l1=arr[i-1][1]; // r1=arr[i-1][2]; // } // }else{ // if(l1>=arr[i-1][1]&&l1<=arr[i-1][2]){ // r1=arr[i-1][2]; // }else{ // l1=arr[i-1][1]; // } // } // } // if(!q2){ // // System.out.println("Hello"); // if(r2<arr[i-1][1]||l2>arr[i-1][2]){ // q2=true; // }else if(r2<=arr[i-1][2]&&l2>=arr[i-1][1]|| // r2>=arr[i-1][2]&&l2<=arr[i-1][1]){ // if(r2<=arr[i-1][2]&&l2>=arr[i-1][1]){ // }else{ // l2=arr[i-1][1]; // r2=arr[i-1][2]; // } // }else{ // if(l2>=arr[i-1][1]&&l2<=arr[i-1][2]){ // r2=arr[i-1][2]; // }else{ // l2=arr[i-1][1]; // } // } // } // } // // System.out.println(l1+" "+r1+" "+l2+" "+r2); // } // if(c==1){ // continue; // } // if(n==1){ // l1=arr[0][1]; // r1=arr[0][2]; // l2=arr[0][1]; // r2=arr[0][2]; // } // int v1=m-arr[0][0]; // int v2=m+arr[0][0]; // if(!q1){ // if(r1<v1||l1>v2){ // }else{ // System.out.println("YES"); // c=1; // } // } // if(!q2){ // System.out.println("Hello"); // if(c==0){ // if(r2<v1||l2>v2){ // }else{ // System.out.println("YES"); // c=1; // } // } // } // if(c==0){ // System.out.println("NO"); // } } } static String findSum(String str1, String str2) { // Before proceeding further, make sure length // of str2 is larger. if (str1.length() > str2.length()){ String t = str1; str1 = str2; str2 = t; } // Take an empty String for storing result String str = ""; // Calculate length of both String int n1 = str1.length(), n2 = str2.length(); // Reverse both of Strings str1=new StringBuilder(str1).reverse().toString(); str2=new StringBuilder(str2).reverse().toString(); int carry = 0; for (int i = 0; i < n1; i++) { // Do school mathematics, compute sum of // current digits and carry int sum = ((int)(str1.charAt(i) - '0') + (int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); // Calculate carry for next step carry = sum / 10; } // Add remaining digits of larger number for (int i = n1; i < n2; i++) { int sum = ((int)(str2.charAt(i) - '0') + carry); str += (char)(sum % 10 + '0'); carry = sum / 10; } // Add remaining carry if (carry > 0) str += (char)(carry + '0'); // reverse resultant String str = new StringBuilder(str).reverse().toString(); return str; } static String multiply(String num1, String num2) { int len1 = num1.length(); int len2 = num2.length(); if (len1 == 0 || len2 == 0) return "0"; // will keep the result number in vector // in reverse order int result[] = new int[len1 + len2]; // Below two indexes are used to // find positions in result. int i_n1 = 0; int i_n2 = 0; // Go from right to left in num1 for (int i = len1 - 1; i >= 0; i--) { int carry = 0; int n1 = num1.charAt(i) - '0'; // To shift position to left after every // multipliccharAtion of a digit in num2 i_n2 = 0; // Go from right to left in num2 for (int j = len2 - 1; j >= 0; j--) { // Take current digit of second number int n2 = num2.charAt(j) - '0'; // Multiply with current digit of first number // and add result to previously stored result // charAt current position. int sum = n1 * n2 + result[i_n1 + i_n2] + carry; // Carry for next itercharAtion carry = sum / 10; // Store result result[i_n1 + i_n2] = sum % 10; i_n2++; } // store carry in next cell if (carry > 0) result[i_n1 + i_n2] += carry; // To shift position to left after every // multipliccharAtion of a digit in num1. i_n1++; } // ignore '0's from the right int i = result.length - 1; while (i >= 0 && result[i] == 0) i--; // If all were '0's - means either both // or one of num1 or num2 were '0' if (i == -1) return "0"; // genercharAte the result String String s = ""; while (i >= 0) s += (result[i--]); return s; } public static int comb(int val){ long v=1; for(int i=1;i<=val;i++){ v*=i; } long v2=1; for(int i=1;i<=val-2;i++){ v2*=i; } long a=v/v2; a=a/2; return (int)a; } public static class Comp implements Comparator<pair>{ public int compare(pair a,pair b){ if(a.x!=b.x){ return b.x-a.x; }else{ return a.y-b.y; } } } public static int gcd(int a,int b){ if (b == 0) return a; return gcd(b, a % b); } public static int lcm(int a,int b){ int x=Math.max(a,b); int y=Math.min(a,b); long ans=x; while(ans%y!=0){ ans+=x; } if(ans>Integer.MAX_VALUE){ return -1; } return (int)ans; } public static long fact(int n){ long ans=1; for(int i=1;i<=n;i++){ ans*=i; } return ans; } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
e577cc8c5693c82e95e6aed13899b589
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class _testing { static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters toc compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } public static void main(String[] args) throws IOException { Scanner scn = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int t = scn.nextInt(); while (t-- > 0) { int n = scn.nextInt(); int ptemp = scn.nextInt(); ; int pt = 0; int pst = ptemp; int pen = ptemp; int time[] = new int[n]; int st[] = new int[n]; int en[] = new int[n]; for (int i = 0; i < n; i++) { time[i] = scn.nextInt(); st[i] = scn.nextInt(); en[i] = scn.nextInt(); } boolean ok = true; for (int i = 0; i < n; i++) { int diff = time[i] - pt; if (pen + diff < st[i] || pst - diff > en[i]) { ok = false; break; } pst = Math.max(st[i], pst - diff); pen = Math.min(en[i], pen + diff); pt = time[i]; } if (ok) { sb.append("YES" + "\n"); } else { sb.append("NO" + "\n"); } } System.out.println(sb); } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
dd8ef521f7101d9bfb999d1511a7a8f0
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.*; import java.util.Arrays; public class solve { public static void main(String args[]) { Scanner in=new Scanner(System.in); int q=in.nextInt(); while(q!=0) { q--; int n=in.nextInt(); int m=in.nextInt(); int t[]=new int[n]; int l[]=new int[n]; int h[]=new int[n]; for(int i=0;i<n;i++) { t[i]=in.nextInt(); l[i]=in.nextInt(); h[i]=in.nextInt(); } int flag=0; int min=m,max=m; int t1=0; for(int i=0;i<n;i++) { if(l[i]>max) { if(l[i]-max>(t[i]-t1)) { flag=-1; break; } else { max=Math.min(h[i],max+(t[i]-t1)); min=l[i]; t1=t[i]; } } else if(l[i]<=max) { if(h[i]<=min) { if(min-h[i]>t[i]-t1) { flag=-1; break; } else { min=Math.max(l[i],min-(t[i]-t1)); max=h[i]; t1=t[i]; } } else { min=Math.max(l[i],min-(t[i]-t1)); max=Math.min(h[i],max+(t[i]-t1)); t1=t[i]; } } } if(flag==0) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
8ced0ec25644c60d00d9cad81dc7047d
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import org.w3c.dom.ls.LSOutput; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Hello { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numTestCases = scanner.nextInt(); while (numTestCases-- > 0) { int n = scanner.nextInt(); int initialTime = scanner.nextInt(); int[] l = new int[n]; int[] r = new int[n]; int[] t = new int[n]; for(int i = 0; i < n; i++) { t[i] = scanner.nextInt(); l[i] = scanner.nextInt(); r[i] = scanner.nextInt(); } int prev = 0; int min = initialTime; int max = initialTime; boolean works = true; for(int i = 0; i < n; i++) { max += t[i] - prev; min -= t[i] - prev; if(min > r[i] || max < l[i]) { works = false; break; } max = Math.min(max, r[i]); min = Math.max(min, l[i]); prev = t[i]; } if(works) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
229734fc4dc9ea19e050bf95124b34e7
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { Compare compare = new Compare(); Scanner scanner = new Scanner(System.in); int q = scanner.nextInt(); for (int i = 0; i < q; i++) { int n = scanner.nextInt(); int m = scanner.nextInt(); Integer Time1 = scanner.nextInt(); Integer L = scanner.nextInt(); Integer H = scanner.nextInt(); Integer Time2 = Time1; boolean echec = false; Integer S = compare.Max(m - Time1, L); Integer K = compare.Min(m + Time1, H); int j = 0; while (j < n - 1 && !echec) { if (S > K) { System.out.println("NO"); for (int k = j; k < n - 1; k++) { scanner.nextInt(); scanner.nextInt(); scanner.nextInt(); echec = true; } } else { Time1 = Time2; Time2 = scanner.nextInt(); L = scanner.nextInt(); H = scanner.nextInt(); S = compare.Max(S - Time2 + Time1, L); K = compare.Min(K + Time2 - Time1, H); } j++; } if (j == n - 1 && !echec) { if (S > K) System.out.println("NO"); else System.out.println("YES"); } } } } class Compare{ Integer Min(Integer a,Integer b){ if (a < b) return a; return b; } Integer Max(Integer a,Integer b){ if (a < b) return b; return a; } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
3ce70f196f16b8a521963d138c7a9a80
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.*; public class AC { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int t,i; t=sc.nextInt(); while(t>0) { t--; int n=sc.nextInt(); int m=sc.nextInt(); int a[][]=new int[n][3]; for(i=0;i<n;i++) { a[i][0]=sc.nextInt(); a[i][1]=sc.nextInt(); a[i][2]=sc.nextInt(); } Arrays.sort(a,Comparator.comparing((int d[])->d[0])); long min=m-a[0][0]; long max=m+a[0][0]; String ans="YES"; if(a[0][1]<min&&a[0][2]<min||a[0][1]>max&&a[0][2]>max) ans="NO"; if(ans.equals("NO")) { System.out.println("NO"); continue; } a[0][1]=(int)Math.max(a[0][1], min); a[0][2]=(int)Math.min(a[0][2], max); for(i=1;i<n;i++) { int d=a[i][0]-a[i-1][0]; min=a[i-1][1]-d; max=a[i-1][2]+d; if(a[i][1]<min&&a[i][2]<min||a[i][1]>max&&a[i][2]>max) { ans="NO"; break; } a[i][1]=(int)Math.max(a[i][1], min); a[i][2]=(int)Math.min(a[i][2], max); } System.out.println(ans); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
accdcd4dc3577bbe016ff4a03de1685b
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jaynil */ 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); CAirConditioner solver = new CAirConditioner(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CAirConditioner { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int t[] = new int[n + 1]; int l[] = new int[n + 1]; int h[] = new int[n + 1]; int min = m; int max = m; for (int i = 1; i <= n; i++) { t[i] = in.nextInt(); l[i] = in.nextInt(); h[i] = in.nextInt(); } for (int i = 1; i <= n; i++) { min = min - (t[i] - t[i - 1]); max = max + t[i] - t[i - 1]; // out.println(min + " " + max); if ((min < l[i] && max < l[i]) || (max > h[i] && min > h[i])) { out.println("NO"); return; } if (min <= l[i]) { min = l[i]; } if (max >= h[i]) { max = h[i]; } } out.println("YES"); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
9ca9448c8debec0e867fdb06897c3d3a
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.Scanner; public class WorkFile { public static void main(String[] args) { Scanner s = new Scanner(System.in); int q = s.nextInt(); StringBuilder res = new StringBuilder(); while (q-->0) { int n = s.nextInt(), m = s.nextInt(); long t1 = 0, min = m, max = m, k = 0; for (int i=0; i<n; i++) { int t2 = s.nextInt(); int l = s.nextInt(), h = s.nextInt(); if (k==1) continue; long diff = t2-t1; min-=diff; max+=diff; min = Math.max(min,l); max = Math.min(max,h); if (min>max) { k=1; continue; } t1=t2; } if (k==1) res.append("NO\n"); else res.append("YES\n"); } System.out.println(res); } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
5f7c3cc9629cfa7e3b49c82b1477017e
train_001.jsonl
1581771900
Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.
256 megabytes
import java.util.Scanner; public class WorkFile { public static void main(String[] args) { Scanner s = new Scanner(System.in); int q = s.nextInt(); while (q-->0) { int n = s.nextInt(), m = s.nextInt(); long t1 = 0, min = m, max = m, k = 0; for (int i=0; i<n; i++) { int t2 = s.nextInt(); int l = s.nextInt(), h = s.nextInt(); if (k==1) continue; long diff = t2-t1; min-=diff; max+=diff; min = Math.max(min,l); max = Math.min(max,h); if (min>max) { k=1; continue; } t1=t2; } if (k==1) System.out.println("NO"); else System.out.println("YES"); } } }
Java
["4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way: At $$$0$$$-th minute, change the state to heating (the temperature is 0). At $$$2$$$-nd minute, change the state to off (the temperature is 2). At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied). At $$$6$$$-th minute, change the state to off (the temperature is 3). At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied). At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
Java 8
standard input
[ "dp", "greedy", "two pointers", "implementation", "sortings" ]
a75b8b9b99b800762645ef7c3bc29905
Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.
1,500
For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).
standard output
PASSED
9e2860bb251bc04b53304b1b90b2674f
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.util.*; import java.io.*; public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int N = sc.nextInt(); int K = sc.nextInt(); int[] heights = new int[200001]; for (int i = 0; i < N; i++) { int H = sc.nextInt(); heights[H]++; } int breakHeight = 0; int curSum = 0; int chops = 0; int curAdd = 0; for (int i = 200000; i >= 1; i--) { curSum += curAdd; /*System.out.println(i); System.out.println(heights[i]); System.out.println(curSum); System.out.println(curAdd); System.out.println(chops); System.out.println();*/ if (heights[i] == N) { breakHeight = i; break; } if (2*heights[i] + curSum + heights[i-1] + 2*curAdd > K) { //System.out.println("Chopping: " + i); heights[i-1] += curAdd; heights[i-1] += heights[i]; //System.out.println("curAdd: " + curAdd); //System.out.println(heights[i-1]); curSum = 0; chops++; curAdd = 0; } else { curAdd += heights[i]; } } if (curSum > 0) {chops++;} System.out.println(chops); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
e47a8b60a3f1a92eaed7190fdb987058
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.util.Arrays; import java.util.Scanner; import java.util.Stack; public class MakeEqual { static class whonum{ int height,num; } public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int hlim = sc.nextInt(); Stack<whonum> stak = new Stack<whonum>(); int[] tower = new int[n]; for(int k = 0; k < n; k++){ tower[k] = sc.nextInt(); } Arrays.sort(tower); int cur = -1; int num = 0; for (int k = 0; k < n; k++){ if (cur == -1){ cur = tower[k]; } if (tower[k] != cur){ whonum add = new whonum(); add.height = cur; add.num = num; stak.add(add); cur = tower[k]; num = 0; } num++; } whonum finaladd = new whonum(); finaladd.height = cur; finaladd.num = num; stak.add(finaladd); int cuts = 0; int mod = 0; while (stak.size() > 1){ whonum large = stak.pop(); whonum small = stak.pop(); mod += large.num; if (mod > hlim){ cuts++; mod = large.num; } large.height--; if (large.height == small.height) { whonum add = new whonum(); add.num = large.num + small.num; add.height = small.height; stak.add(add); }else{ stak.add(small); stak.add(large); } } if (mod > 0){ cuts++; } System.out.println(cuts); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
0dba2fd173bfb73b2a9e9f901a253c99
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class CF1065C { static long maxH = (long)(2*(Math.pow(10,5))+5); public static void main(String[] args) { FastReader fr = new FastReader(); long n = fr.nextLong(); long k = fr.nextLong(); long[] countArr = new long[(int)(maxH+5)]; long minH = Long.MAX_VALUE; long maxiH = Long.MIN_VALUE; for(int i=0;i<n;i++) { int val = (int)fr.nextLong(); countArr[val]++; minH = Math.min(minH, val); maxiH = Math.max(maxiH, val); } if(minH == maxiH) { System.out.println("0"); return; } long pos = (maxH+1); long sum = 0; long c = 0; long slices = 0; long x = 0; long h = 0; while(true) { //System.out.println("sum : "+sum+" pos : "+pos + " c : "+c); x = sum - (c * (pos-1)); if(x > k) { slices++; sum = pos * c; h = pos; } if(pos == minH) break; --pos; c = c + countArr[(int)(pos)]; sum = sum + (countArr[(int)pos] * (pos)); } if(h != minH) slices++; System.out.println(slices); } static int getGreaterThanCount(TreeSet<Long> treeSet, long value) { return treeSet.tailSet(value).size(); } //Better IO Class static class FastReader { BufferedReader br; StringTokenizer st; 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(); } public long nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public Float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { System.out.println(e); } return str; } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
6b4cd93d091711cd3fbe9d9f200ef084
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { private static Reader in; private static PrintWriter out; static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } private static void solve() { int n = in.nextInt(), K = in.nextInt(); int[] h = new int[n]; int[] height_range = new int[200001]; TreeMap<Integer, Integer> tmap = new TreeMap<>(); for (int i=0; i<n; i++) {h[i] = in.nextInt(); tmap.compute(h[i], (k, v) -> v==null ? 1 : v+1);} Arrays.sort(h); int base_height = h[0], max_height = h[h.length-1]; if (base_height == max_height) {out.printf("%d\n", 0); return;} height_range[0] = n; int[][] arr = new int[tmap.size()][2]; int arr_ind = 0; for (Map.Entry<Integer, Integer> entry : tmap.entrySet()) { arr[arr_ind][0] = entry.getKey(); arr[arr_ind++][1] = entry.getValue(); } int ind = arr.length-1; height_range[arr[ind][0]-1] = arr[ind][1]; ind--; int i; for (i=arr[ind+1][0]-2; i>=1; i--) { if (ind < 0) break; if (arr[ind][0]<=i) height_range[i] = height_range[i+1]; else if (i < arr[ind][0]) {height_range[i] = height_range[i+1] + arr[ind][1]; ind--;} } while (i>=1) { height_range[i] = height_range[i+1]; i--; } int cuts = 1, curren_cost = 0; for (i=base_height; i<max_height; i++) { if (curren_cost + height_range[i] <= K) curren_cost += height_range[i]; else { cuts++; curren_cost = height_range[i]; } } out.println(cuts); } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(System.out); solve(); out.close(); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
e989f8278c236568b2f8f3166553b2d7
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { private static Reader in; private static PrintWriter out; static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } private static void solve() { int n = in.nextInt(), K = in.nextInt(); int[] h = new int[n]; int[] height_range = new int[200001]; TreeMap<Integer, Integer> tmap = new TreeMap<>(); for (int i=0; i<n; i++) {h[i] = in.nextInt(); tmap.compute(h[i], (k, v) -> v==null ? 1 : v+1);} Arrays.sort(h); int base_height = h[0], max_height = h[h.length-1]; if (base_height == max_height) {out.printf("%d\n", 0); return;} height_range[0] = n; int[][] arr = new int[tmap.size()][2]; int arr_ind = 0; for (Map.Entry<Integer, Integer> entry : tmap.entrySet()) { arr[arr_ind][0] = entry.getKey(); arr[arr_ind++][1] = entry.getValue(); } int ind = arr.length-1; height_range[arr[ind][0]-1] = arr[ind][1]; ind--; int i; for (i=arr[ind+1][0]-2; i>=1; i--) { if (ind < 0) break; if (arr[ind][0]<=i) height_range[i] = height_range[i+1]; else if (i < arr[ind][0]) {height_range[i] = height_range[i+1] + arr[ind][1]; ind--;} } while (i>=1) { height_range[i] = height_range[i+1]; i--; } int cuts = 1, curren_cost = 0; for (i=base_height; i<max_height; i++) { if (curren_cost + height_range[i] <= K) curren_cost += height_range[i]; else { cuts++; curren_cost = height_range[i]; } } out.println(cuts); } public static void main(String[] args) throws IOException { in = new Reader(); out = new PrintWriter(System.out); solve(); out.close(); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
25480ad494d5aa118b823334b648b969
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; PrintWriter out; public FastReader(boolean fileInput) throws IOException { Reader reader = fileInput ? new FileReader("balls.in") : new InputStreamReader(System.in); //Writer writer = fileIO ? new FileWriter("output.txt") : new OutputStreamWriter(System.out); Writer writer = new OutputStreamWriter(System.out); br = new BufferedReader(reader); out = new PrintWriter(new BufferedWriter(writer)); } 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 read = new FastReader(false); int n = read.nextInt(); int k = read.nextInt(); int[] arr = new int[n]; long[] cnt = new long[200010]; int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (int i=0;i<n;i++){ arr[i] = read.nextInt(); cnt[arr[i]]++; min = Math.min(min, arr[i]); max = Math.max(max, arr[i]); } if(max == min){ System.out.println(0); }else{ for(int i = 200001;i>=0;i--){ cnt[i] = cnt[i+1] + cnt[i]; } long slice = 0; long sum = 0; for(int i = 200001;i>min;i--){ if(sum + cnt[i] <= k){ sum += cnt[i]; }else{ slice++; sum = cnt[i]; } } if(sum > 0) slice++; System.out.println(slice); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
2acd699da21ce93c367125caab6a9acc
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.util.Scanner; public class CCC { public static void main(String args[]) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int k=scan.nextInt(); int height[]=new int[200001]; long cost=0l; int min=Integer.MAX_VALUE; int max=0; for(int i=0;i<n;i++) { int add=scan.nextInt(); min=Math.min(min, add); height[add]++; max=Math.max(max, height[add]); } int cur=0; for(int i=199999;i>=1;i--) { height[i]+=height[i+1]; } if(max==n){ System.out.println(0); return; } for(int i=200000;i>=0;i--) { if(height[i]==n){ break; } if((cur+height[i])<=k){ cur+=height[i]; }else{ cur=height[i]; cost++; } //System.out.println(cur); } System.out.println(cost+1); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
2e83219cef613006712bee153878fb25
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); //////////////////////////////////////////////////////////////////////// int num[] = new int[200001]; int arr[] = new int[200001]; int n = sc.nextInt(); long k = sc.nextLong(); num[0] = sc.nextInt(); int mx = num[0]; int mn = num[0]; for (int i = 1; i < n; i++) { num[i] = sc.nextInt(); mx = Math.max(num[i], mx); mn = Math.min(num[i], mn); } for (int i = 0; i < n; i++) { arr[num[i] - mn]++; } for (int i = mx-1; i >= 1; i--) { arr[i] += arr[i + 1]; } long cur = 0; int cnt = 0; for (int i = mx; i >= 1; i--) { if (cur + arr[i] <= k) { cur += arr[i]; } else { cnt++; cur = arr[i]; } } if(cur>0){ cnt++; } out.println(cnt); //////////////////////////////////////////////////////////////////////// out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { 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(); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
efaea7dee21d0d6d250e9c0bdb5ad7a4
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; public class TaskC { public static void main(String[] args) { new TaskC(System.in, System.out); } static class Solver implements Runnable { int n, k, lim; int[] heights; long[] cnt; InputReader in; PrintWriter out; void solve() throws IOException { n = in.nextInt(); k = in.nextInt(); heights = in.nextIntArray(n); lim = (int) 2e5 + 5; cnt = new long[lim]; int max = 0; for (int h : heights) { cnt[h]++; max = Math.max(max, h); } for (int j = 0; j < 2; j++) { for (int i = max; i > 0; i--) cnt[i] += cnt[i + 1]; } int slices = 0; if (query(max) == n) { out.println(0); return; } // for (int i = 0; i <= max; i++) // System.out.println("i : " + i + ", q(i) : " + query(i)); for (int h = max; h > 0;) { long total = query(h); int temp = h - 1; long x; // System.out.println("** h : " + h + ", tot : " + total); while (temp > 0 && total + (x = query(temp)) <= k) { // System.out.println("temp : " + temp + ", tot : " + (total + x)); total += x; temp--; if (query(temp) == n) break; } slices++; h = temp; if (query(h) == n) break; } out.println(slices); } long query(int ind) { if (ind == 0) return 0; return cnt[ind] - cnt[ind + 1]; } void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } // uncomment below line to change to BufferedReader // public Solver(BufferedReader in, PrintWriter out) public Solver(InputReader in, PrintWriter out) { this.in = in; this.out = out; } @Override public void run() { try { solve(); } catch (IOException e) { e.printStackTrace(); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } public InputReader(InputStream stream) { this.stream = stream; } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } static long min(long... arr) { long min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static long max(long... arr) { long max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } static int min(int... arr) { int min = arr[0]; for (int i = 1; i < arr.length; i++) min = Math.min(min, arr[i]); return min; } static int max(int... arr) { int max = arr[0]; for (int i = 1; i < arr.length; i++) max = Math.max(max, arr[i]); return max; } } static class Utils { static boolean nextPermutation(int[] arr) { for (int a = arr.length - 2; a >= 0; --a) { if (arr[a] < arr[a + 1]) { for (int b = arr.length - 1; ; --b) { if (arr[b] > arr[a]) { int t = arr[a]; arr[a] = arr[b]; arr[b] = t; for (++a, b = arr.length - 1; a < b; ++a, --b) { t = arr[a]; arr[a] = arr[b]; arr[b] = t; } return true; } } } } return false; } } public TaskC(InputStream inputStream, OutputStream outputStream) { // uncomment below line to change to BufferedReader // BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Thread thread = new Thread(null, new Solver(in, out), "TaskC", 1 << 29); try { thread.start(); thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { in.close(); out.flush(); out.close(); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
3508a380fa3f0a4fc83128c82e338902
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class CF1065C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long k = sc.nextLong(); int[] towers = new int[n]; for (int i = 0; i < n; i++) { towers[i] = sc.nextInt(); } Arrays.sort(towers); List<Integer> slice = new ArrayList(); int lastH = towers[0]; for (int i = 0; i < n; i++) { if(towers[i] > lastH){ for(int j = 0; j < towers[i] - lastH; j++){ slice.add(n-i); } lastH = towers[i]; } } int index = slice.size() - 1; int sliceNum = 0; int result = 0; if(index >= 0){ while(true){ sliceNum += slice.get(index); if(sliceNum > k){ result++; sliceNum = slice.get(index); } if(index == 0){ if(sliceNum != 0){ result++; } break; } index--; } } System.out.println(result); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
b33ee9bf84f43aba3045a12166fc1ddd
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.util.*; import java.io.*; public class C { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); pw.close(); } static class Solver { static long mod = (long) (1e9); public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.ni(); int k = br.ni(); Integer[] in = br.nIa(n); Arrays.sort(in); int[] heights = new int[200001]; for (int i = n - 1; i > -1; i--) { heights[in[i]]++; } for (int i = heights.length - 1; i > 0; i--) { heights[i - 1] += heights[i]; } int out = 0; int temp = 0; for (int i = heights.length - 1; i > 0; i--) { if (i == in[0]) { if (heights[in[n-1]] == n) { break; } out++; break; } if (temp + heights[i] > k) { out++; temp = heights[i]; } else { temp += heights[i]; } } pw.println(out); } static long gcd(long a, long b) { if (a > b) return gcd(b, a); if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long pow(long a, long b) { if (b == 0) return 1L; long val = pow(a, b / 2); if (b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } } static class Point implements Comparable<Point> { int a; int b; Point(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Point o) { return this.a - o.a; } public boolean equals(Object obj) { if (obj instanceof Point) { Point other = (Point) obj; return a == other.a && b == other.b; } return false; } public int hashCode() { return 65536 * a + b + 4733 * 0; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } ArrayList<Integer>[] ng(int n, int e) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int i = 0; i < e; i++) { int a = ni() - 1; int b = ni() - 1; adj[a].add(b); adj[b].add(a); } return adj; } Integer[] nIa(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } Long[] nLa(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } String[] nsa(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nt(); } return arr; } String nt() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(nt()); } long nl() { return Long.parseLong(nt()); } double nd() { return Double.parseDouble(nt()); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
f959a57054fd74847148379b2ae322c2
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.util.Scanner; /** * Contest: Educational Codeforces Round 52 * * @author Arturs Licis */ public class ProblemC { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long k = sc.nextLong(); long[] h = new long[200_000 + 1]; long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; for (int i = 0; i < n; i++) { long hi = sc.nextLong(); h[(int) hi]++; min = Math.min(min, hi); max = Math.max(max, hi); } int i = (int) max; long currCnt = 0; long rem = k; long cuts = 0; while (i > min) { if (h[i] != 0) currCnt += h[i]; if (rem - currCnt >= 0) { rem -= currCnt; } else { cuts++; // cut previous one rem = k; rem -= currCnt; } i--; } if (rem != k) cuts++; System.out.println(cuts); System.out.flush(); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
cc89fdfcb4dab879bcd8151e10226900
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { private static Scanner sc; private static Printer pr; static boolean []visited; static int []color; static int []pow=new int[(int)3e5+1]; static int []count; static boolean check=true; static ArrayList<Integer>[]list; private static long aLong=(long)(Math.pow(10,9)+7); static final long div=998244353; static int answer=0; private static void solve() throws IOException { int n=sc.nextInt();long k=sc.nextLong(); int []arr=new int[200010]; int min=(int )1e9;int max=0,number=0; for (int i=0;i<n;i++){ number=sc.nextInt(); arr[number]++; max=Math.max(max,number); min=Math.min(min,number); } //System.out.println("max:"+max+"min:"+min); for (int i=max-1;i>min;i--) arr[i]+=arr[i+1]; long sum=0,count=0; for (int i=max;i>min;i--){ sum+=arr[i]; if (sum>k){ count++; sum=arr[i]; } } if (sum>0)count++; pr.println(count); } public static int countSubtree(int cur,int parent){ int count=1; for (int n:list[cur]){ if (n!=parent){ count+=countSubtree(n,cur); } } if (count%2==0&&parent!=0){ answer++; return 0; }else if (count%2==0) return 0; return count; } static int add(int a,int b ){ if (a+b>=div) return (int)(a+b-div); return (int)a+b; } public static int isBipartite(ArrayList<Integer>[]list,int src){ color[src]=0; Queue<Integer>queue=new LinkedList<>(); int []ans={0,0}; queue.add(src); while (!queue.isEmpty()){ ans[color[src=queue.poll()]]++; for (int v:list[src]){ if (color[v]==-1){ queue.add(v); color[v]=color[src]^1; }else if (color[v]==color[src]) check=false; } } return add(pow[ans[0]],pow[ans[1]]); } public static int powerMod(long b, long e){ long ans=1; while (e-->0){ ans=ans*b%div; } return (int)ans; } public static int dfs(int s){ int ans=1; visited[s]=true; for (int k:list[s]){ if (!visited[k]){ ans+=dfs(k); } } return ans; } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static long []primeFactor(int n){ long []prime=new long[n+1]; prime[1]=1; for (int i=2;i<=n;i++) prime[i]=((i&1)==0)?2:i; for (int i=3;i*i<=n;i++){ if (prime[i]==i){ for (int j=i*i;j<=n;j+=i){ if (prime[j]==j) prime[j]=i; } } } return prime; } public static StringBuilder binaryradix(long number){ StringBuilder builder=new StringBuilder(); long remainder; while (number!=0) { remainder = number % 2; number >>= 1; builder.append(remainder); } builder.reverse(); return builder; } public static int binarySearch(long[] a, int index,long target) { int l = index; int h = a.length - 1; while (l<=h) { int med = l + (h-l)/2; if(a[med] - target <= target) { l = med + 1; } else h = med - 1; } return h; } public static int val(char c){ return c-'0'; } public static long gcd(long a,long b) { if (a == 0) return b; return gcd(b % a, a); } private static class Pair implements Comparable<Pair> { long x; long y; Pair() { this.x = 0; this.y = 0; } Pair(long x, long y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) return false; Pair other = (Pair) obj; if (this.x == other.x && this.y == other.y) { return true; } return false; } @Override public int compareTo(Pair other) { if (this.x != other.x) return Long.compare(this.x, other.x); return Long.compare(this.y*other.x, this.x*other.y); } } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pr = new Printer(System.out); solve(); pr.close(); // sc.close(); } private static class Scanner { BufferedReader br; Scanner (InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } private boolean isPrintable(int ch) { return ch >= '!' && ch <= '~'; } private boolean isCRLF(int ch) { return ch == '\n' || ch == '\r' || ch == -1; } private int nextPrintable() { try { int ch; while (!isPrintable(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } return ch; } catch (IOException e) { throw new NoSuchElementException(); } } String next() { try { int ch = nextPrintable(); StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (isPrintable(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } int nextInt() { try { // parseInt from Integer.parseInt() boolean negative = false; int res = 0; int limit = -Integer.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } int multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } long nextLong() { try { // parseLong from Long.parseLong() boolean negative = false; long res = 0; long limit = -Long.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Long.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } long multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { int ch; while (isCRLF(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (!isCRLF(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } void close() { try { br.close(); } catch (IOException e) { // throw new NoSuchElementException(); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class List { String Word; int length; List(String Word, int length) { this.Word = Word; this.length = length; } } private static class Printer extends PrintWriter { Printer(PrintStream out) { super(out); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
ae098154732b85f0430f18fda041c9b2
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
//package math_codet; import java.io.*; import java.util.*; /****************************************** * AUTHOR: AMAN KUMAR SINGH * * INSTITUITION: KALYANI GOVERNMENT ENGINEERING COLLEGE * ******************************************/ public class lets_do { InputReader in; PrintWriter out; Helper_class h; final long mod = 1000000007; public static void main(String[] args) throws java.lang.Exception{ new lets_do().run(); } void run() throws Exception{ in=new InputReader(); out = new PrintWriter(System.out); h = new Helper_class(); int t = 1; while(t-->0) solve(); out.flush(); out.close(); } void solve(){ int n = h.ni(); long k = h.nl(); int[] arr = new int[n]; long[] height = new long[200005]; int i = 0; int min = Integer.MAX_VALUE; int max = 0; long sum = 0; for(i = 0; i < n; i++){ arr[i] = h.ni(); min = Math.min(min, arr[i]); max = Math.max(max, arr[i]); height[1] += 1; height[arr[i] + 1] -= 1; } if(max == min) { h.pn(0); return; } long sum2[] = new long[200005]; long sum1[] = new long[200005]; for(i = 0; i <= max; i++){ sum += height[i]; sum2[i] = sum; } int cnt = 0; sum = 0; for(i = max; i > min; i--) { if(sum + sum2[i] > k) { cnt++; sum = sum2[i]; } else { sum += sum2[i]; } } h.pn(cnt + 1); } final Comparator<Entity> com=new Comparator<Entity>(){ public int compare(Entity x, Entity y){ int xx=Integer.compare(x.a, y.a); if(xx==0){ int xxx=Integer.compare(x.b,y.b); return xxx; } else return xx; } }; class Entity{ int a; int b; Entity(int p, int q){ a=p; b=q; } } class Helper_class{ long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} long mul(long a,long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; a*=b; if(a>=mod)a%=mod; return a; } long modPow(long a, long p){ long o = 1; while(p>0){ if((p&1)==1)o = mul(o,a); a = mul(a,a); p>>=1; } return o; } long add(long a, long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; if(b<0)b+=mod; a+=b; if(a>=mod)a-=mod; return a; } } class InputReader{ BufferedReader br; StringTokenizer st; public InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public InputReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
9f14925fc217debf18974552f290ba7d
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
//package math_codet; import java.io.*; import java.util.*; /****************************************** * AUTHOR: AMAN KUMAR SINGH * * INSTITUITION: KALYANI GOVERNMENT ENGINEERING COLLEGE * ******************************************/ public class lets_do { InputReader in; PrintWriter out; Helper_class h; final long mod = 1000000007; public static void main(String[] args) throws java.lang.Exception{ new lets_do().run(); } void run() throws Exception{ in=new InputReader(); out = new PrintWriter(System.out); h = new Helper_class(); int t = 1; while(t-->0) solve(); out.flush(); out.close(); } void solve(){ int n = h.ni(); long k = h.nl(); int[] arr = new int[n]; long[] height = new long[200005]; int i = 0; int min = Integer.MAX_VALUE; int max = 0; long sum = 0; for(i = 0; i < n; i++){ arr[i] = h.ni(); min = Math.min(min, arr[i]); max = Math.max(max, arr[i]); height[1] += 1; height[arr[i] + 1] -= 1; } if(max == min) { h.pn(0); return; } long sum2[] = new long[200005]; long sum1[] = new long[200005]; for(i = 0; i <= max; i++){ sum += height[i]; sum2[i] = sum; //if(i < 50 && i >= 12) //h.pn(sum2[i]+" "+i); } sum = 0; for(i = min; i < max; i++){ sum += sum2[i]; sum1[i] = sum; // if(i >= min - 1&& i < 100) //h.pn(sum1[i]+" "+i); } int cnt = 0; sum = 0; for(i = max; i > min; i--) { if(sum + sum2[i] > k) { cnt++; sum = sum2[i]; } else { sum += sum2[i]; } //h.pn(sum); } h.pn(cnt + 1); } final Comparator<Entity> com=new Comparator<Entity>(){ public int compare(Entity x, Entity y){ int xx=Integer.compare(x.a, y.a); if(xx==0){ int xxx=Integer.compare(x.b,y.b); return xxx; } else return xx; } }; class Entity{ int a; int b; Entity(int p, int q){ a=p; b=q; } } class Helper_class{ long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n(){return in.next();} String nln(){return in.nextLine();} int ni(){return Integer.parseInt(in.next());} long nl(){return Long.parseLong(in.next());} double nd(){return Double.parseDouble(in.next());} long mul(long a,long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; a*=b; if(a>=mod)a%=mod; return a; } long modPow(long a, long p){ long o = 1; while(p>0){ if((p&1)==1)o = mul(o,a); a = mul(a,a); p>>=1; } return o; } long add(long a, long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; if(b<0)b+=mod; a+=b; if(a>=mod)a-=mod; return a; } } class InputReader{ BufferedReader br; StringTokenizer st; public InputReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public InputReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next(){ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String str = ""; try{ str = br.readLine(); }catch (IOException e){ e.printStackTrace(); } return str; } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
02dad0f3cf89608a6ef63a583f4d02de
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { class pair { int f,s; pair(int fi,int se) { f=fi; s=se; } } void merge1(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } void merge3(int arr[],int arr1[],int arr2[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; int L1[]=new int[n1]; int R1[]=new int[n2]; int L2[]=new int[n1]; int R2[]=new int[n2]; //long L3[]=new long[n1]; //long R3[]=new long[n2]; for (int i=0; i<n1; ++i) { L[i] = arr[l + i]; L1[i]=arr1[l+i]; L2[i]=arr2[l+i]; //L3[i]=arr3[l+i]; } for (int j=0; j<n2; ++j) { R[j] = arr[m + 1+ j]; R1[j]=arr1[m+1+j]; R2[j]=arr2[m+1+j]; //R3[j]=arr3[m+1+j]; } int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; //arr3[k]=L3[i]; i++; } else { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; //arr3[k]=R3[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; //arr3[k]=L3[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; //arr3[k]=R3[j]; j++; k++; } } void sort3(int arr[],int arr1[],int arr2[], int l, int r) { if (l < r) { int m = (l+r)/2; sort3(arr,arr1,arr2, l, m); sort3(arr ,arr1,arr2, m+1, r); merge3(arr,arr1,arr2,l, m, r); } } void merge2(int arr[],int arr1[],int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; int L1[]=new int[n1]; int R1[]=new int[n2]; for (int i=0; i<n1; ++i) { L[i] = arr[l + i]; L1[i]=arr1[l+i]; } for (int j=0; j<n2; ++j) { R[j] = arr[m + 1+ j]; R1[j]=arr1[m+1+j]; } int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; arr1[k]=L1[i]; i++; } else { arr[k] = R[j]; arr1[k]=R1[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; arr1[k]=L1[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; arr1[k]=R1[j]; j++; k++; } } void sort2(int arr[],int arr1[],int l, int r) { if (l < r) { int m = (l+r)/2; sort2(arr,arr1, l, m); sort2(arr ,arr1, m+1, r); merge2(arr,arr1,l, m, r); } } void merge4(int arr[],int arr1[],int arr2[],int arr3[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; int L1[]=new int[n1]; int R1[]=new int[n2]; int L2[]=new int[n1]; int R2[]=new int[n2]; int L3[]=new int[n1]; int R3[]=new int[n2]; for (int i=0; i<n1; ++i) { L[i] = arr[l + i]; L1[i]=arr1[l+i]; L2[i]=arr2[l+i]; L3[i]=arr3[l+i]; } for (int j=0; j<n2; ++j) { R[j] = arr[m + 1+ j]; R1[j]=arr1[m+1+j]; R2[j]=arr2[m+1+j]; R3[j]=arr3[m+1+j]; } int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; arr3[k]=L3[i]; i++; } else { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; arr3[k]=R3[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; arr1[k]=L1[i]; arr2[k]=L2[i]; arr3[k]=L3[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; arr1[k]=R1[j]; arr2[k]=R2[j]; arr3[k]=R3[j]; j++; k++; } } void sort4(int arr[],int arr1[],int arr2[],int arr3[], int l, int r) { if (l < r) { int m = (l+r)/2; sort4(arr,arr1,arr2,arr3, l, m); sort4(arr ,arr1,arr2,arr3, m+1, r); merge4(arr,arr1,arr2,arr3,l, m, r); } } public int justsmall(long a[],int l,int r,long x) { int p=-1; while(l<=r) { int mid=(l+r)/2; if(a[mid]<=x) { p=mid; l=mid+1; } else r=mid-1; } return p; } public int justlarge(long a[],int l,int r,long x) { int p=0; while(l<=r) { int mid=(l+r)/2; if(a[mid]<x) { l=mid+1; } else { p=mid; r = mid - 1; } } return p; } int gcd(int x,int y) { if(x%y==0) return y; else return(gcd(y,x%y)); } int fact(int n) { int ans=1; for(int i=1;i<=n;i++) ans*=i; return ans; } long bintoint(String s) { long a=0; int l=s.length(); int k=0; for(int i=l-1;i>=0;i--) { char c=s.charAt(i); if(c=='1') { a=a+(long)Math.pow(2,k); } k++; } return a; } String inttobin(long x) { String s=""; while(x!=0) { long k=x%2; if(k==1) s="1"+s; else s="0"+s; x=x/2; } return s; } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<26).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n=in.ni(); long k=in.nl(); long a[]=new long[200005]; long b[]=new long[200005]; long c[]=new long[200005]; int min=10000000; for(int i=0;i<n;i++) { int x=in.ni(); min=Math.min(min,x); a[x]++; } for(int i=200003;i>=0;i--) { b[i]=b[i+1]+a[i]; } for(int i=200003;i>=0;i--) { c[i]=c[i+1]+b[i]; } long x=0; int count=0; for(int i=200003;i>=min+1;i--) { if(c[i-1]-x<=k) continue; else { //System.out.println(i); x=c[i]; count++; } } if(c[min]-x>n) count++; out.println(count); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
62815aee7bec362c77aac7d6ab09d510
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { Debug debug = new Debug(); int n = in.nextInt(); int K = in.nextInt(); int[] h = new int[(int) (2e5 + 10)]; int min = h.length; for (int i = 0; i < n; ++i) { int c = in.nextInt(); ++h[c]; min = Math.min(min, c); } for (int i = h.length - 2; i >= 0; --i) h[i] += h[i + 1]; // debug.tr(Arrays.copyOfRange(h,1, 5)); int ans = 0; int cur = h.length - 1; while (cur > 0 && h[cur] == 0) --cur; int sum = 0; while (cur > min) { sum = 0; while (sum <= K && cur > min) sum += h[cur--]; if (sum > K) ++cur; ++ans; if (cur == min) break; } out.println(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; public InputReader(InputStream var1) { this.stream = var1; } private int pread() { if (this.pnumChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.pnumChars) { this.curChar = 0; try { this.pnumChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.pnumChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int var1; for (var1 = this.pread(); this.isSpaceChar(var1); var1 = this.pread()) { ; } byte var2 = 1; if (var1 == 45) { var2 = -1; var1 = this.pread(); } int var3 = 0; do { if (var1 == 44) { var1 = this.pread(); } if (var1 < 48 || var1 > 57) { throw new InputMismatchException(); } var3 *= 10; var3 += var1 - 48; var1 = this.pread(); } while (!this.isSpaceChar(var1)); return var3 * var2; } private boolean isSpaceChar(int var1) { return var1 == 32 || var1 == 10 || var1 == 13 || var1 == 9 || var1 == -1; } } static class Debug { PrintWriter out; boolean oj; boolean system; long timeBegin; Runtime runtime; public Debug(PrintWriter out) { oj = System.getProperty("ONLINE_JUDGE") != null; this.out = out; this.timeBegin = System.currentTimeMillis(); this.runtime = Runtime.getRuntime(); } public Debug() { system = true; oj = System.getProperty("ONLINE_JUDGE") != null; OutputStream outputStream = System.out; this.out = new PrintWriter(outputStream); this.timeBegin = System.currentTimeMillis(); this.runtime = Runtime.getRuntime(); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
ee31fefea192bb17fcfb9f6976220dc5
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vadim */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.ni(); int k = in.ni(); int[] a = in.na(n); int[] h = new int[200007]; int max = 0; int min = 2000007; for (int i = 0; i < n; i++) { max = Math.max(max, a[i]); min = Math.min(min, a[i]); h[a[i]]++; } int[] hsum = new int[200007]; for (int i = max; i >= min; i--) { hsum[i] = h[i] + hsum[i + 1]; } int sum = 0; int ans = 0; for (int i = max; i > min; i--) { if (sum + hsum[i] > k) { ans++; sum = hsum[i]; } else { sum += hsum[i]; } } if (sum > 0) ans += 1; out.println(ans); } } static class InputReader extends BufferedReader { public InputReader(InputStream st) { super(new InputStreamReader(st)); } public int ni() { try { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (c >= 0 && !isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new RuntimeException(); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } catch (IOException e) { throw new RuntimeException(e); } } public String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } static boolean isWhiteSpace(int c) { return c >= 0 && c <= 32; } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
3f02da3f0e0a44ceb7e0f664e78ff526
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.stream.IntStream; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.util.Random; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author dmytro.prytula */ 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); CViravnivaemVisoti solver = new CViravnivaemVisoti(); solver.solve(1, in, out); out.close(); } static class CViravnivaemVisoti { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), k = in.nextInt(); int[] h = in.nextArr(n); GeekInteger.save_sort(h); reverce(h); int ans = 0; int[] gh = new int[n - 1]; int curSum = 0; for (int i = 0; i < gh.length; i++) { gh[i] = (h[i] - h[i + 1]) * (i + 1); // if ((h[i] - h[i + 1]) != 0) for (int j = 1; j <= (h[i] - h[i + 1]); j++) { curSum += i + 1; if (k - curSum < 0) { ans++; curSum = i + 1; } if (k - curSum == 0) { ans++; curSum = 0; } } } if (curSum > 0) ans++; out.println(ans); } private void reverce(int[] a) { for (int i = 0, j = a.length - 1; i < j; i++, j--) { int c = a[i]; a[i] = a[j]; a[j] = c; } } } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); swap(arr, i, j); } return arr; } public static void swap(int[] arr, int i, int j) { arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextToken() { 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(nextToken()); } public int[] nextArr(int size) { return Arrays.stream(new int[size]).map(c -> nextInt()).toArray(); } } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
3d3e0f24b37d69a93fd9db91c593876f
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class vk18 { public static void main(String[] stp) throws Exception { Scanner scan = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()),i; long k=Long.parseLong(st.nextToken()); Integer a[]=new Integer[200001]; Arrays.fill(a,0); st = new StringTokenizer(br.readLine()); int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE; for(i=0;i<n;i++) { int p=Integer.parseInt(st.nextToken()); a[p]++; max=Math.max(max,p); min=Math.min(min,p); } for(i=max-1;i>=min;i--) a[i]+=a[i+1]; long sum=0,count=0; for(i=max;i>min;i--) { sum+=a[i]; if(sum > k) { count++; sum=a[i]; } } if(sum > 0) count++; pw.println(count); pw.flush(); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output
PASSED
68465af8d7d422b290439b0e9be197da
train_001.jsonl
1539269400
There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$). Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] heights = new int[200001]; for (int i = 0; i < n; i++) { heights[scanner.nextInt()] += 1; } int cuts = 0; int availableSpaceInCut = k; for (int j = 200000; heights[j] != n; j--) { if (availableSpaceInCut < heights[j]) { cuts += 1; availableSpaceInCut = k - heights[j]; } else { availableSpaceInCut -= heights[j]; } heights[j - 1] += heights[j]; } if (availableSpaceInCut != k) { cuts += 1; } System.out.println(cuts); } }
Java
["5 5\n3 1 2 2 4", "4 5\n2 3 4 5"]
2 seconds
["2", "2"]
NoteIn the first example it's optimal to make $$$2$$$ slices. The first slice is on height $$$2$$$ (its cost is $$$3$$$), and the second one is on height $$$1$$$ (its cost is $$$4$$$).
Java 8
standard input
[ "greedy" ]
676729309dfbdf4c9d9d7c457a129608
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n \le k \le 10^9$$$) — the number of towers and the restriction on slices, respectively. The second line contains $$$n$$$ space separated integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 2 \cdot 10^5$$$) — the initial heights of towers.
1,600
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
standard output