exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | b88cf621201f707cf3a0bf49509ea626 | train_000.jsonl | 1519058100 | Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Rextester{
static double distance(double x1,double y1,double x2,double y2){
return Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2,2));
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int R = new Integer(st.nextToken());
int cx = new Integer(st.nextToken());
int cy = new Integer(st.nextToken());
int ex = new Integer(st.nextToken());
int ey = new Integer(st.nextToken());
double dist = distance(cx,cy,ex,ey);
if(dist>=R){
System.out.println((double)cx+" "+(double)cy+" "+(double)R);
}
else{
double d = R+dist;
double radius = d/2;
if(ex==cx){
if(Math.abs(cy-(ey+radius))>Math.abs(cy-(ey-radius))){
System.out.println((double)ex+" "+((double)ey-radius)+" "+radius);
}
else{
System.out.println((double)ex+" "+((double)ey+radius)+" "+radius);
}
}
else{
double m = ((double)cy-ey)/((double)cx-ex);
double sin = m/Math.sqrt(1+m*m);
double cos = 1/Math.sqrt(1+m*m);
double difx = radius*cos;
double dify = radius*sin;
if(distance(cx,cy,ex+difx,ey+dify)>distance(cx,cy,ex-difx,ey-dify)){
System.out.println(((double)ex-difx)+" "+((double)ey-dify)+" "+radius);
}
else{
System.out.println(((double)ex+difx)+" "+((double)ey+dify)+" "+radius);
}
}
}
}
} | Java | ["5 3 3 1 1", "10 5 5 5 15"] | 1 second | ["3.7677669529663684 3.7677669529663684 3.914213562373095", "5.0 5.0 10.0"] | null | Java 11 | standard input | [
"geometry"
] | 29d4ca13888c0e172dde315b66380fe5 | The single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105). | 1,600 | Print three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range. | standard output | |
PASSED | f44cfb581d76ad65b9fdda31da34a69e | train_000.jsonl | 1519058100 | Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
public class File {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Flat radius:
double R = sc.nextDouble();
// Flat coordinates:
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
// Fafa coordinates:
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
if (!contains(x1, y1, R, x2, y2)) {
System.out.println(x1 + " " + y1 + " " + R);
return;
}
// If Fafa is in the center of the flat.
if (x1 == x2 && y1 == y2) {
double dR = R / 2.0;
double dx = x1;
double dy = y2 - dR;
System.out.println(dx + " " + dy + " " + dR);
return;
}
// Get slope of x2, y2 from origin.
// Be careful of 0's.
// Slope = x2 / y2
double distance = getLength(x1, y1, x2, y2);
double diameter = distance + R;
double answerR = diameter / 2.0;
// Similar triangles.
/*
x2 - answerX
/
x2 - x1
equals to
answerR
/
distance
AND,
y2 - answerY
/
y2 - y1
equals to
answerR
/
distance
=>
(x1 - answerX) = (x2 - x1) * (answerR) / distance
answerX = x1 - (x2 - x1) * (answerR) / distance
answerY = y1 - (y2 - y1) * (answerR) / distance
*/
double answerX = x2 - (x2 - x1) * answerR / distance;
double answerY = y2 - (y2 - y1) * answerR / distance;
System.out.println(answerX + " " + answerY + " " + answerR);
}
public static double getLength(double x1, double y1, double x2, double y2) {
double d_x = Math.abs(x1 - x2);
double d_y = Math.abs(y1 - y2);
return Math.sqrt(d_x*d_x + d_y*d_y);
}
public static boolean contains(double x1, double y1, double R, double x2, double y2) {
double d_x = Math.abs(x2 - x1);
double d_y = Math.abs(y2 - y1);
double distance = Math.sqrt(d_x*d_x + d_y*d_y);
return distance < R;
}
} | Java | ["5 3 3 1 1", "10 5 5 5 15"] | 1 second | ["3.7677669529663684 3.7677669529663684 3.914213562373095", "5.0 5.0 10.0"] | null | Java 11 | standard input | [
"geometry"
] | 29d4ca13888c0e172dde315b66380fe5 | The single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105). | 1,600 | Print three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range. | standard output | |
PASSED | 1913f6f8d99b197d72886208f6b61c5f | train_000.jsonl | 1519058100 | Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
public class File {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Flat radius:
double R = sc.nextDouble();
// Flat coordinates:
double x1 = sc.nextDouble();
double y1 = sc.nextDouble();
// Fafa coordinates:
double x2 = sc.nextDouble();
double y2 = sc.nextDouble();
if (!contains(x1, y1, R, x2, y2)) {
System.out.println(x1 + " " + y1 + " " + R);
return;
}
// If Fafa is in the center of the flat.
if (x1 == x2 && y1 == y2) {
double dR = R / 2.0;
double dx = x1;
double dy = y2 - dR;
System.out.println(dx + " " + dy + " " + dR);
return;
}
// Get slope of x2, y2 from origin.
// Be careful of 0's.
// Slope = x2 / y2
double distance = getLength(x1, y1, x2, y2);
double diameter = distance + R;
double answerR = diameter / 2.0;
// (x2 - answerX) / answerR = (x2 - x1) / distance
// =>
// answerX = x2 - answerR * (x2 - x1) / distance
// answerY = y2 - answerR * (y2 - y1) / distance
double answerX = x2 - answerR * (x2 - x1) / distance;
double answerY = y2 - answerR * (y2 - y1) / distance;
System.out.println(answerX + " " + answerY + " " + answerR);
}
public static double getLength(double x1, double y1, double x2, double y2) {
double d_x = Math.abs(x1 - x2);
double d_y = Math.abs(y1 - y2);
return Math.sqrt(d_x*d_x + d_y*d_y);
}
public static boolean contains(double x1, double y1, double R, double x2, double y2) {
double d_x = Math.abs(x2 - x1);
double d_y = Math.abs(y2 - y1);
double distance = Math.sqrt(d_x*d_x + d_y*d_y);
return distance < R;
}
} | Java | ["5 3 3 1 1", "10 5 5 5 15"] | 1 second | ["3.7677669529663684 3.7677669529663684 3.914213562373095", "5.0 5.0 10.0"] | null | Java 11 | standard input | [
"geometry"
] | 29d4ca13888c0e172dde315b66380fe5 | The single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105). | 1,600 | Print three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range. | standard output | |
PASSED | 76299006f2f0dea9f4c3f02dfecd092b | train_000.jsonl | 1299340800 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeD
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
}
static int[][] dpFollow;
static Boolean[][] dp;
static int[] numeros;
static int n;
static boolean dp(int anterior, int indice)
{
if(indice == n)
return true;
if(dp[anterior - 1000][indice] != null)
return dp[anterior - 1000][indice];
char[] numero = (numeros[indice] + "").toCharArray();
for(int i = 0; i < numero.length; i++)
{
char real = numero[i];
for(char j = i == 0 ? '1' : '0'; j <= '9'; j++)
{
numero[i] = j;
int siguiente = Integer.parseInt(new String(numero));
if(siguiente >= 1000 && siguiente <= 2011 && siguiente >= anterior)
if(dp(siguiente, indice + 1))
{
dpFollow[anterior - 1000][indice] = siguiente;
return dp[anterior - 1000][indice] = true;
}
numero[i] = real;
}
}
return dp[anterior - 1000][indice] = false;
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
n = sc.nextInt();
numeros = new int[n];
for(int i = 0; i < n; i++)
numeros[i] = sc.nextInt();
dp = new Boolean[1200][n + 1];
dpFollow = new int[1200][n + 1];
if(dp(1000, 0))
{
int posicion = 0;
int anterior = 1000;
while(posicion < n)
{
System.out.println(dpFollow[anterior - 1000][posicion]);
anterior = dpFollow[anterior - 1000][posicion];
posicion++;
}
}
else
System.out.println("No solution");
}
} | Java | ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"] | 1 second | ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"] | null | Java 7 | standard input | [
"implementation",
"greedy",
"brute force"
] | c175d010d75c391d0b25391fecff007c | The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999). | 1,700 | Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). | standard output | |
PASSED | 99e937d93af32c25bba0b1e198446c94 | train_000.jsonl | 1299340800 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Closeable;
import java.util.Iterator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Jacob Jiang
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
ExtendedPrintWriter out = new ExtendedPrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, QuickScanner in, ExtendedPrintWriter out) {
int n = in.nextInt();
int[] answer = new int[n];
int previous = 1000;
for (int i = 0; i < n; i++) {
int thisNumber = Integer.MAX_VALUE;
char[] number = in.next().toCharArray();
for (int pos = 0; pos < 4; pos++) {
char oldChar = number[pos];
for (char newChar = '0'; newChar <= '9'; newChar++) {
if (pos == 0 && newChar == '0') {
continue;
}
number[pos] = newChar;
int result = Integer.parseInt(String.valueOf(number));
if (result >= previous && result <= 2011) {
thisNumber = Math.min(thisNumber, result);
}
}
number[pos] = oldChar;
}
if (thisNumber == Integer.MAX_VALUE) {
out.println("No solution");
return;
}
answer[i] = previous = thisNumber;
}
for (int i : answer) {
out.println(i);
}
}
}
class QuickScanner implements Iterator<String>, Closeable {
BufferedReader reader;
StringTokenizer tokenizer;
boolean endOfFile = false;
public QuickScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = null;
}
public boolean hasNext() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
checkNext();
} catch (NoSuchElementException ignored) {
}
}
return !endOfFile;
}
private void checkNext() {
if (endOfFile) {
throw new NoSuchElementException();
}
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
endOfFile = true;
throw new NoSuchElementException();
}
}
public String next() {
checkNext();
return tokenizer.nextToken();
}
public void remove() {
throw new UnsupportedOperationException();
}
public int nextInt() {
return Integer.parseInt(next());
}
public void close() {
try {
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class ExtendedPrintWriter extends PrintWriter {
public ExtendedPrintWriter(Writer out) {
super(out);
}
public ExtendedPrintWriter(OutputStream out) {
super(out);
}
}
| Java | ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"] | 1 second | ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"] | null | Java 7 | standard input | [
"implementation",
"greedy",
"brute force"
] | c175d010d75c391d0b25391fecff007c | The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999). | 1,700 | Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). | standard output | |
PASSED | 43d33cc4dc26b9657d7eb0e82016b8b5 | train_000.jsonl | 1299340800 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
char[][] y = new char[n][];
for (int i = 0; i < n; i++)
y[i] = in.readCharWord();
if (makeResult(y, n - 1, c2011)){
for (int i = 0; i < n; i++)
out.println(new String(y[i]));
}
else
out.println("No solution");
}
public boolean makeResult(char[][] y, int x, char[] last){
if (x < 0)
return true;
char[] answer = new char[4];
answer[0] = 0;
for (int i = 0; i < 4; i++){
char c = y[x][i];
for (int j = i == 0 ? 1 : 0; j < 10; j++){
y[x][i] = (char) ('0' + j);
if (cmp(y[x], last) <= 0 && cmp(y[x], answer) > 0)
answer = Arrays.copyOf(y[x], 4);
}
y[x][i] = c;
}
y[x] = Arrays.copyOf(answer, 4);
return cmp(y[x], c1000) >= 0 && cmp(y[x], c2011) <= 0 && makeResult(y, x - 1, y[x]);
}
int cmp(char[] a, char[] b){
for (int i = 0; i < 4; i++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
return 0;
}
final char[] c1000 = {'1', '0', '0', '0'}, c2011 = {'2', '0', '1', '1'};
}
class InputReader {
public InputReader(InputStream inputStream){
in = new BufferedReader(new InputStreamReader(inputStream));
}
public InputReader(Reader reader){
in = new BufferedReader(reader);
}
public String nextLine(){
String res = null;
try {
res = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
public String readWord(){
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
public char[] readCharWord(){
return readWord().toCharArray();
}
public int readInt(){
return Integer.parseInt(readWord());
}
private StringTokenizer tokenizer;
private BufferedReader in;
}
class OutputWriter {
public OutputWriter(OutputStream outputStream){
out = new PrintWriter(new OutputStreamWriter(outputStream));
}
public OutputWriter(Writer writer){
out = new PrintWriter(writer);
}
public void print(Object...args){
int size = args.length;
for (int i = 0; i < size; i++)
out.print(args[i]);
}
public void println(Object...args){
print(args);
out.println();
}
public void close(){
out.close();
}
private PrintWriter out;
}
| Java | ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"] | 1 second | ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"] | null | Java 7 | standard input | [
"implementation",
"greedy",
"brute force"
] | c175d010d75c391d0b25391fecff007c | The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999). | 1,700 | Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). | standard output | |
PASSED | a4a6fd52bc86caecac74e3d686dfac50 | train_000.jsonl | 1299340800 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. | 256 megabytes | import java.util.*;
public class QFF {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int n=input.nextInt(),i,max1;
String alls[] = new String [n];
int tmp,j;
boolean start=false,end=false;
int[][] all = new int[n][4];
int flag=0;
for(i=0;i<n;i++){
flag=0;
tmp=input.nextInt();
all[i][3]=tmp%10;
tmp=tmp/10;
all[i][2]=tmp%10;
tmp=tmp/10;
all[i][1]=tmp%10;
tmp=tmp/10;
all[i][0]=tmp%10;
if(all[0][0]>=2)all[0][0]=1;
else if(i==0 && all[0][1]!=0){
all[0][1]=0;
}
else if(i==0 && all[0][2]!=0){
all[0][2]=0;
}
else if(i==0 && all[0][3]!=0){
all[0][3]=0;
}
if(i!=0) start=true;
if(start){
if(all[i][0]>=3){
if(all[i][1]>all[i-1][1]){
all[i][0]=all[i-1][0];
flag=1;
}
else if(all[i][1]<all[i-1][1]){
all[i][0]=all[i-1][0]+1;
flag=1;
}
else if(all[i][2]>all[i-1][2]){
all[i][0]=all[i-1][0];
flag=1;
}
else if(all[i][2]<all[i-1][2]){
all[i][0]=all[i-1][0]+1;
flag=1;
}
else if(all[i][3]>all[i-1][3]){
all[i][0]=all[i-1][0];
flag=1;
}
else if(all[i][3]<all[i-1][3]){
all[i][0]=all[i-1][0]+1;
flag=1;
}
else{
all[i][0]=all[i-1][0];
flag=1;
}
}
if(all[i][0]<all[i-1][0] && flag==0){
all[i][0]++;
}
else if(all[i][0]==all[i-1][0] && flag==0){
if(all[i][1]>all[i-1][1] && all[i][2]>=all[i-1][2] && all[i][3]>=all[i-1][3]){
all[i][1]=all[i-1][1];
}
else if(all[i][1]>all[i-1][1] && all[i][2]>all[i-1][2] && all[i][3]<=all[i-1][3]){
all[i][1]=all[i-1][1];
}
else if(all[i][1]>all[i-1][1] && all[i][2]<=all[i-1][2] && all[i][3]>all[i-1][3]){
if(all[i][1]!=all[i-1][1]+1){
all[i][1]=all[i-1][1]+1;
}else{
if(all[i][2]!=0){
all[i][2]=0;
}else{
all[i][3]=0;
}
}
}
else if(all[i][1]>all[i-1][1] && all[i][2]<all[i-1][2] && all[i][3]==all[i-1][3]){
if(all[i][1]!=all[i-1][1]+1){
all[i][1]=all[i-1][1]+1;
}else{
if(all[i][2]!=0){
all[i][2]=0;
}else{
all[i][3]=0;
}
}
}
else if(all[i][1]>all[i-1][1] && all[i][2]<=all[i-1][2] && all[i][3]<all[i-1][3]){
if(all[i][1]!=all[i-1][1]+1){
all[i][1]=all[i-1][1]+1;
}else{
if(all[i][2]!=0){
all[i][2]=0;
}else{
all[i][3]=0;
}
}
}
else if(all[i][1]<all[i-1][1] && all[i][2]>=all[i-1][2] && all[i][3]>=all[i-1][3]){
all[i][1]=all[i-1][1];
}
else if(all[i][1]<all[i-1][1] && all[i][2]>all[i-1][2] && all[i][3]<all[i-1][3]){
all[i][1]=all[i-1][1];
}
else if(all[i][1]<all[i-1][1] && all[i][2]<all[i-1][2] && all[i][3]>all[i-1][3]){
if(all[i-1][1]!=9){
all[i][1]=all[i-1][1]+1;
}else{
all[i][0]=all[i-1][0]+1;
}
}
else if(all[i][1]<all[i-1][1] && all[i][2]==all[i-1][2] && all[i][3]<all[i-1][3]){
if(all[i-1][1]!=9){
all[i][1]=all[i-1][1]+1;
}else{
all[i][0]=all[i-1][0]+1;
}
}
else if(all[i][1]<all[i-1][1] && all[i][2]<all[i-1][2] && all[i][3]==all[i-1][3]){
if(all[i-1][1]!=9){
all[i][1]=all[i-1][1]+1;
}else{
all[i][0]=all[i-1][0]+1;
}
}
else if(all[i][1]<all[i-1][1] && all[i][2]<all[i-1][2] && all[i][3]<all[i-1][3]){
if(all[i-1][1]!=9){
all[i][1]=all[i-1][1]+1;
}else{
all[i][0]=all[i-1][0]+1;
}
}
else if(all[i][1]==all[i-1][1] && all[i][2]>all[i-1][2] && all[i][3]>=all[i-1][3]){
all[i][2]=all[i-1][2];
}
else if(all[i][1]==all[i-1][1] && all[i][2]==all[i-1][2] && all[i][3]>=all[i-1][3]){
all[i][3]=all[i-1][3];
}
else if(all[i][1]==all[i-1][1] && all[i][2]>all[i-1][2] && all[i][3]<all[i-1][3]){
if(all[i][2]!=all[i-1][2]+1){
all[i][2]=all[i-1][2]+1;
}else{
if(all[i][3]!=0){
all[i][3]=0;
}
}
}
else if(all[i][1]==all[i-1][1] && all[i][2]<all[i-1][2] && all[i][3]>=all[i-1][3]){
all[i][2]=all[i-1][2];
}
else if(all[i][1]==all[i-1][1] && all[i][2]==all[i-1][2] && all[i][3]<all[i-1][3]){
all[i][3]=all[i-1][3];
}
else if(all[i][1]==all[i-1][1] && all[i][2]<all[i-1][2] && all[i][3]<all[i-1][3]){
if(all[i-1][2]!=9){
all[i][2]=all[i-1][2]+1;
}else{
all[i][1]=all[i-1][1]+1;
}
}
}
else if(all[i][0]>all[i-1][0] && flag==0){
if(all[i][1]>all[i-1][1]){
all[i][0]=all[i-1][0];
}
else if(all[i][1]==all[i-1][1] && all[i][2]>all[i-1][2]){
all[i][0]=all[i-1][0];
}
else if(all[i][1]==all[i-1][1] && all[i][2]==all[i-1][2] && all[i][3]>=all[i-1][3]){
all[i][0]=all[i-1][0];
}
else if(all[i][1]!=0){
all[i][1]=0;
}
else if(all[i][2]!=0){
all[i][2]=0;
}
else if(all[i][3]!=0){
all[i][3]=0;
}
}
}
}
for(i=0;i<n;i++){
if(all[i][0]>=3){
System.out.println("No solution");
System.exit(0);
}
if(all[i][0]==2 && (all[i][1]>0 || all[i][2]>1)){
System.out.println("No solution");
System.exit(0);
}
if(all[i][0]==2 && all[i][2]==1 && all[i][2]>1){
System.out.println("No solution");
System.exit(0);
}
if(i!=n-1){
if((all[i][3]+all[i][2]*10+all[i][1]*100+all[i][0]*1000)>(all[i+1][3]+all[i+1][2]*10+all[i+1][1]*100+all[i+1][0]*1000)){
System.out.println("No solution");
System.exit(0);
}
}
}
for(i=0;i<n;i++){
System.out.print(all[i][0]);
System.out.print(all[i][1]);
System.out.print(all[i][2]);
System.out.println(all[i][3]);
}
}
} | Java | ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"] | 1 second | ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"] | null | Java 7 | standard input | [
"implementation",
"greedy",
"brute force"
] | c175d010d75c391d0b25391fecff007c | The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999). | 1,700 | Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). | standard output | |
PASSED | 79687ebc2c8f1ceb1f55bac75b4e79d5 | train_000.jsonl | 1299340800 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Code implements Runnable {
public static void main(String[] args) throws IOException {
new Thread(new Code()).start();
}
private void solve() throws IOException {
int n = nextInt();
String[] dates = new String[n];
for(int i = 0; i < n; ++i) {
dates[i] = nextToken();
String ans = "2012";
for(int j = 0; j < 4; ++j) {
for(char t = '0'; t <= '9'; ++t) {
StringBuilder tmp = new StringBuilder(dates[i]);
tmp.setCharAt(j, t);
if(tmp.charAt(0) != '0' && (i == 0 || tmp.toString().compareTo(dates[i - 1]) >= 0) &&
tmp.toString().compareTo(ans) < 0)
ans = tmp.toString();
}
}
if(!ans.equals("2012")) dates[i] = ans;
else {
writer.println("No solution");
return;
}
}
for(int i = 0; i < n; ++i) writer.println(dates[i]);
}
private class Pair<E extends Comparable, V extends Comparable> implements Comparable<Pair<E, V>> {
public Pair(E first, V second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair<E, V> obj) {
if(first == obj.first) return second.compareTo(obj.second);
return first.compareTo(obj.first);
}
@Override
public boolean equals(Object obj) {
Pair other = (Pair)obj;
return first.equals(other.first) && second.equals(other.second);
}
public E first;
public V second;
}
@Override
public void run() {
try {
if(in.equals("")) reader = new BufferedReader(new InputStreamReader(System.in));
else reader = new BufferedReader(new FileReader(in));
if(out.equals("")) writer = new PrintWriter(new OutputStreamWriter(System.out));
else writer = new PrintWriter(new FileWriter(out));
solve();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine());
return st.nextToken();
}
private String in = "", out = "";
private BufferedReader reader;
private PrintWriter writer;
private StringTokenizer st;
} | Java | ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"] | 1 second | ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"] | null | Java 7 | standard input | [
"implementation",
"greedy",
"brute force"
] | c175d010d75c391d0b25391fecff007c | The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999). | 1,700 | Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). | standard output | |
PASSED | 17bf933fb452e4287e36d808228eaa20 | train_000.jsonl | 1299340800 | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it. | 256 megabytes | import java.util.Random;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.File;
import java.math.BigInteger;
public class Task{
static final boolean readFromFile = false;
static final String fileInputName = "input.txt",
fileOutputName = "output.txt";
public static void main(String args[]){
FileInputStream fileInputStream;
FileOutputStream fileOutputStream;
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
if (readFromFile){
try{
fileInputStream = new FileInputStream(new File(fileInputName));
fileOutputStream = new FileOutputStream(new File(fileOutputName));
}catch (FileNotFoundException e){
throw new RuntimeException(e);
}
}
PrintWriter out = new PrintWriter((readFromFile)?fileOutputStream:outputStream);
InputReader in = new InputReader((readFromFile)?fileInputStream:inputStream);
Solver s = new Solver(in, out);
s.solve();
out.close();
}
}
class Solver{
private PrintWriter out;
private InputReader in;
public void solve(){
int n = in.nextInt();
int a[] = new int[n+1];
a[0]=1000;
for (int i=0;i<n;i++){
int b = in.nextInt();
int mn = 1;
boolean found = false;
int t = 0;
for (int p=0;p<4;p++){
for (int c=0;c<=9;c++)
if (p!=3 || c!=0){
int d = b/(mn*10)*mn*10 + b%mn + c*mn;
if (d>=1000 && d<=2011 && d>=a[i]){
if (!found){
t = d;
found = true;
}
else
t = Math.min(t, d);
}
}
mn *= 10;
}
if (!found){
out.println("No solution");
return;
}
a[i+1]=t;
}
for (int i=1;i<=n;i++)
out.println(a[i]);
}
Solver(InputReader in, PrintWriter out){
this.in = in;
this.out = out;
}
}
class InputReader{
StringTokenizer tok;
BufferedReader buf;
InputReader(InputStream in){
tok = null;
buf = new BufferedReader(new InputStreamReader(in));
}
InputReader(FileInputStream in){
tok = null;
buf = new BufferedReader(new InputStreamReader(in));
}
public String next(){
while (tok==null || !tok.hasMoreTokens()){
try{
tok = new StringTokenizer(buf.readLine());
}catch (IOException e){
throw new RuntimeException(e);
}
}
return tok.nextToken();
}
public int 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());
}
public String nextLine(){
try{
return buf.readLine();
}catch (IOException e){
return null;
}
}
} | Java | ["3\n1875\n1936\n1721", "4\n9999\n2000\n3000\n3011", "3\n1999\n5055\n2000"] | 1 second | ["1835\n1836\n1921", "1999\n2000\n2000\n2011", "No solution"] | null | Java 7 | standard input | [
"implementation",
"greedy",
"brute force"
] | c175d010d75c391d0b25391fecff007c | The first input line contains an integer n (1 ≤ n ≤ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≤ yi ≤ 9999). | 1,700 | Print n numbers z1, z2, ..., zn (1000 ≤ zi ≤ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes). | standard output | |
PASSED | 5724a31830057dfe111ef69ecdd87722 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import static java.lang.Integer.parseInt;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
static long[][] trees;
public static void main(String[] args) throws Throwable{
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
int N=parseInt(in.readLine().trim());
trees=new long[N][];
for(int i=0;i<N;i++) {
StringTokenizer st=new StringTokenizer(in.readLine());
trees[i]=new long[]{parseInt(st.nextToken()), parseInt(st.nextToken())};
}
mem=new int[N][2];
for(int i=0;i<N;i++) {
mem[i][0]=-1;
mem[i][1]=-1;
}
if(N>1)
System.out.println(f(1, false)+1);
else
System.out.println(1);
}
static int[][] mem;
static int f(int i, boolean der) {
if(i>=trees.length-1)
return 1;
if(mem[i][der?0:1]>=0)
return mem[i][der?0:1];
int max=f(i+1,false);
if(der) {
if(trees[i][0]-trees[i-1][0]>trees[i-1][1]+trees[i][1])
max=Math.max(max, f(i+1, false)+1);
}
else
if(trees[i][0]-trees[i-1][0]>trees[i][1])
max=Math.max(max, f(i+1, false)+1);
if(trees[i+1][0]-trees[i][0]>trees[i][1])
max=Math.max(max, f(i+1, true)+1);
return mem[i][der?0:1]=max;
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 7870221167d44be7e0bb8ff095da91c7 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Problem545C {
public static void main(String[] args) {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
new Problem545C().solve(in, out);
out.close();
}
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] x = new int[n];
int[] h = new int[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextInt();
h[i] = in.nextInt();
}
int[][] dp = new int[n + 1][3];
dp[0][0] = 1;
dp[0][1] = 0;
dp[0][2] = 1;
for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(x[i] - h[i] > x[i - 1] ? dp[i - 1][0] + 1 : 0,
Math.max(x[i] - h[i] > x[i - 1] ? dp[i - 1][1] + 1 : 0, x[i] - h[i] > x[i - 1] + h[i - 1] ? dp[i - 1][2] + 1 : 0));
dp[i][1] = Math
.max(x[i] > x[i - 1] ? dp[i - 1][0] : 0, Math.max(x[i] > x[i - 1] ? dp[i - 1][1] : 0, x[i] > x[i - 1] + h[i - 1] ? dp[i - 1][2] : 0));
dp[i][2] = Math.max(x[i] > x[i - 1] ? dp[i - 1][0] + 1 : 0,
Math.max(x[i] > x[i - 1] ? dp[i - 1][1] + 1 : 0, x[i] > x[i - 1] + h[i - 1] ? dp[i - 1][2] + 1 : 0));
}
out.println(Math.max(dp[n - 1][0], Math.max(dp[n - 1][1], dp[n - 1][2])));
}
static class InputReader {
public BufferedReader br;
public StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 03e16cd05ee4cdda25af43ed925563f2 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
public class WoodCutters {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long n=sc.nextInt();
long[] position=new long[(int) (n+1)];
long[] height=new long[(int) (n+1)];
for(int i=1;i<=n;i++)
{
position[i]=sc.nextInt();
height[i]=sc.nextInt();
}
long answer=1;
for(int i=2;i<=n-1;i++)
{
if(position[i-1]<position[i]-height[i])
{
answer++;
continue;
}
if(position[i]+height[i]<position[i+1])
{
answer++;
position[i]+=height[i];
}
}
if(n>=2)
System.out.println(answer+1);
else
System.out.println(answer);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 1478effc9f62bf74b088d0a7864bc90b | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String []args){
Scanner s=new Scanner(System.in);
int n=s.nextInt();
long p[][]=new long[n][2];
int i,j;
for(i=0;i<n;i++){
p[i][0]=s.nextLong();
p[i][1]=s.nextLong();
}
int count=2;
long occup=0;
for(i=1;i<n-1;i++){
if(p[i][0]-p[i][1]-occup>p[i-1][0])
{count++;
occup=0;
}
else if(p[i][0]+p[i][1]<p[i+1][0]){
count++;
occup=p[i][1];
}else
occup=0;
}
if(n==1)
System.out.println(1);
else
System.out.println(count);
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 29b3c96716b1b1722a528ed19d5c06c4 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | //package codeforces;
import java.util.Scanner;
/**
* Created by nitin.s on 30/05/15.
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] x = new int[n];
int[] h = new int[n];
for(int i = 0; i < n; ++i) {
x[i] = in.nextInt();
h[i] = in.nextInt();
}
if(n <= 2) {
System.out.println(n);
return;
}
int I = -9999999;
int[][] dp = new int[n][2];
dp[0][0] = 1;
dp[0][1] = x[0] + h[0] < x[1] ? 1 : I;
for(int i = 1; i < n; ++i) {
dp[i][0] = I;
dp[i][1] = I;
if(x[i - 1] < x[i] - h[i]) {
dp[i][0] = Math.max(dp[i][0], dp[i - 1][0] + 1);
}
if(x[i - 1] + h[i - 1] < x[i] - h[i]) {
dp[i][0] = Math.max(dp[i][0], dp[i - 1][1] + 1);
}
dp[i][0] = Math.max(dp[i][0], dp[i-1][0]);
dp[i][0] = Math.max(dp[i][0], dp[i-1][1]);
if(i == n - 1 || x[i] + h[i] < x[i + 1]) {
dp[i][1] = Math.max(dp[i][1], dp[i - 1][0] + 1);
dp[i][1] = Math.max(dp[i][1], dp[i - 1][1] + 1);
}
}
System.out.println(Math.max(dp[n-1][0], dp[n-1][1]));
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 92d93229d89089904f499cf20421f57a | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | //package c303;
import java.util.Scanner;
public class q3
{
public static void main(String rag[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
long x[]=new long[n];
long h[]=new long[n];
for(int i=0;i<n;i++)
{
x[i]=s.nextLong();
h[i]=s.nextLong();
}
int ans=0;
boolean[] z=new boolean[n];
for(int i=0;i<n;i++)
{
z[i]=false;
if(i==0||i==n-1)
ans++;
else
{
// if(x[i+1]>(x[i]+h[i]))
// {
// ans++;
// z[i]=true;
// }
// else
if(!z[i-1])
{if((x[i-1]<(x[i]-h[i])))
{ans++;
continue;}
}
else
{
if(((x[i-1]+h[i-1])<(x[i]-h[i])))
{
ans++;
continue;
}
}
if(x[i+1]>(x[i]+h[i]))
{
ans++;
z[i]=true;
}
}
}
System.out.println(ans);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 5a71293ec5213af59a6ae5072e85d29e | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
/**
* Created by yakoub on 04/09/15.
*/
public class WoodCutter {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int steady[] = new int[n];
int left[] = new int[n];
int right[] = new int[n];
int prev = scanner.nextInt();
int prevH = scanner.nextInt();
steady[0] = 0;
left[0] = 1;
for (int i = 1; i < n; i++) {
int cur = scanner.nextInt();
int curH = scanner.nextInt();
if ((prev + prevH) < cur) {
if (i == 1)
right[0] = 1;
else
right[i - 1] += 1 + Math.max(steady[i - 2], Math.max(right[i - 2], left[i - 2]));
}
steady[i] = Math.max(steady[i - 1], Math.max(left[i - 1], right[i - 1]));
int curLeftMax = Integer.MIN_VALUE;
if ((cur - curH) > prev) {
curLeftMax = Math.max(left[i - 1], steady[i - 1]) + 1;
if ((prev + prevH) < (cur - curH)) {
curLeftMax = Math.max(curLeftMax, right[i - 1] + 1);
}
}
left[i] = Math.max(curLeftMax, steady[i]);
prev = cur;
prevH = curH;
}
if (n > 1)
right[n - 1] = 1 + Math.max(steady[n - 2], Math.max(right[n - 2], left[n - 2]));
System.out.println(Math.max(steady[n - 1], Math.max(left[n - 1], right[n - 1])));
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 049bc4524261a2b9c05cef19945f372f | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class WoodCutters {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
int[] maxRightPos = new int[n];
int[] positions = new int[n];
int[] heights = new int[n];
int max = 0;
for (int i = 0; i < n; i++) {
StringTokenizer linei = new StringTokenizer(reader.readLine());
int pos = Integer.parseInt(linei.nextToken());
int h = Integer.parseInt(linei.nextToken());
positions[i] = pos;
heights[i] = h;
}
for (int i = 0; i < n; i++) {
if (i == 0) {
maxRightPos[i] = positions[i];
max++;
}
else if (i == n-1) {
max++;
}
else {
if (maxRightPos[i-1] < positions[i] - heights[i]){
maxRightPos[i] = positions[i];
max++;
}
else {
if (positions[i+1] > positions[i] + heights[i]) {
maxRightPos[i] = positions[i] + heights[i];
max++;
}
else {
maxRightPos[i] = positions[i];
}
}
}
}
System.out.println(max);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 08a64d09cd2216adc42ad2c207904d93 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
public class Test
{
private static int[] x = new int[100010];
private static int[] h = new int[100010];
private static int[][] dp = new int[100010][3]; // dp[i][0] 表示向左倒, dp[i][1]表示不动,dp[i][2]表示向右倒
// srm 168 div2
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int i , j , n = scan.nextInt() , max = 1;
for (i = 1;i <= n;i ++)
{
x[i] = scan.nextInt();
h[i] = scan.nextInt();
}
// 初始化第一个点
dp[1][0] = 1;
dp[1][1] = 0;
// 如果存在2个以上的结点
if (n >= 2 && (x[1] + h[1] >= x[2]))
dp[1][2] = - 1;
else
dp[1][2] = 1;
// 递推
for (i = 2;i <= n;i ++)
{
// 计算dp[i][0]
int temp1 = - 1 , temp2 = - 1 , temp3 = - 1 , temp;
// 如果可能可以向左倒
if (x[i - 1] + h[i] < x[i])
{
if (dp[i - 1][0] >= 0)
temp1 = dp[i - 1][0] + 1;
temp2 = dp[i - 1][1] + 1;
if (x[i - 1] + h[i - 1] + h[i] < x[i])
temp3 = dp[i - 1][2] + 1;
temp = Math.max(Math.max(temp1 , temp2) , temp3);
dp[i][0] = temp;
}
else
dp[i][0] = - 1;
temp1 = temp2 = temp3 = - 1;
// 计算dp[i][1]
if (dp[i - 1][0] >= 0)
temp1 = dp[i - 1][0];
temp2 = dp[i - 1][1];
if (dp[i - 1][2] >= 0)
temp3 = dp[i - 1][2];
temp = Math.max(Math.max(temp1 , temp2) , temp3);
dp[i][1] = temp;
// 计算dp[i][2]
if (i == n || (x[i] + h[i] < x[i + 1]))
{
temp1 = temp2 = temp3 = - 1;
if (dp[i - 1][0] >= 0)
temp1 = dp[i - 1][0] + 1;
temp2 = dp[i - 1][1] + 1;
if (dp[i - 1][2] >= 0)
temp3 = dp[i - 1][2] + 1;
temp = Math.max(Math.max(temp1 , temp2) , temp3);
dp[i][2] = temp;
}
else
dp[i][2] = - 1;
if (dp[i][0] > max)
max = dp[i][0];
if (dp[i][1] > max)
max = dp[i][1];
if (dp[i][2] > max)
max = dp[i][2];
}
System.out.println(max);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 88c4ae2950fdd4c3ec866b78c17db772 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | //package srm303;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Woodcuters {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
WoodTree[] trees = new WoodTree[n];
for (int i = 0; i < n; i++) {
String parts[] = br.readLine().split(" ");
trees[i] = new WoodTree(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
}
if (n==1)
{
System.out.println(1);
return;
}
int result = 1;
int tekPos = trees[0].start;
for (int i = 1; i < n - 1; i++) {
if (trees[i].start - trees[i].height > tekPos) {
tekPos = trees[i].start;
result++;
} else if (trees[i].start + trees[i].height < trees[i + 1].start) {
tekPos = trees[i].start + trees[i].height;
result++;
}
else{
tekPos = trees[i].start;
}
}
result++;
System.out.println(result);
}
}
class WoodTree {
int start;
int height;
public WoodTree(int start, int height) {
this.start = start;
this.height = height;
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 1a70705a1f2bc389e5bde86e8fd516f3 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
public class Woodcutters {
public static void main(String[] args) throws IOException {
Scanner kb = new Scanner(System.in);
int numOfTrees = kb.nextInt();
kb.nextLine();
Node[] trees = new Node[numOfTrees];
for (int i = 0; i < numOfTrees; i++) {
int coordinate = kb.nextInt();
int height = kb.nextInt();
trees[i] = new Node(coordinate, height);
}
kb.close();
int treeFall = trees[0].pos;
int ans = 1;
for (int i = 1; i < numOfTrees; i++) {
if (trees[i].pos - trees[i].height > treeFall) {
treeFall = trees[i].pos;
ans++;
} else if (i != numOfTrees - 1 && trees[i].pos + trees[i].height < trees[i + 1].pos){
treeFall = trees[i].pos + trees[i].height;
ans++;
} else if (i == numOfTrees - 1) {
ans++;
} else {
treeFall = trees[i].pos;
}
}
System.out.println(ans);
}
private static class Node {
int pos, height;
public Node(int pos, int height) {
this.pos = pos;
this.height = height;
}
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 8e42e9e92fe9d168f49e7930d55a211c | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Erasyl Abenov
*
*
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
try (PrintWriter out = new PrintWriter(outputStream)) {
TaskB solver = new TaskB();
solver.solve(1, in, out);
}
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int sum = 0;
long last = Integer.MIN_VALUE;
Long a[] = new Long[n];
Long h[] = new Long[n];
for(int i = 0; i < n; ++i){
a[i] = in.nextLong();
h[i] = in.nextLong();
}
for(int i = 0; i < n; ++i){
if(last < a[i] - h[i]){
sum ++;
last = a[i];
}
else if(i == n - 1 || a[i + 1] > a[i] + h[i]){
sum++;
last = a[i] + h[i];
}
else{
last = a[i];
}
}
out.println(sum);
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | a7d53d95a3042b32ace4b8dfab25f545 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
/**
* Created by alex on 19.05.15.
*/
public class C {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long x[] = new long[n];
long h[] = new long[n];
for (int i = 0; i < n; i++) {
x[i] = scanner.nextLong();
h[i] = scanner.nextLong();
}
int ans = Math.min(2, n);
long max = x[0];
for (int i = 1; i < n - 1; i++) {
if (x[i] - h[i] > max) {
ans++;
max = x[i];
} else if (x[i] + h[i] < x[i + 1]) {
ans++;
max = x[i] + h[i];
} else {
max = x[i];
}
}
System.out.println(ans);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | fd3ca8e252e4ee703f1fde44103a9154 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
TaskC a= new TaskC();
a.solve(sc);
}
}
class TaskC{
//int [] dp = new int[10000];
//int [] tree = new int[100005];
public int solve(Scanner sc){
int n=sc.nextInt();
int left_index=0;
int max_result=0;
int x,h;
x=sc.nextInt();
h=sc.nextInt();
left_index=x;
//first tree always left.
max_result++;
if (n==1){
System.out.println(1);
return 0;
}
int i=2;
int needRead=1;
while (i<=n || needRead == 0){
if(needRead==1){
x=sc.nextInt();
h=sc.nextInt();
i++;
}
//try left first;
if (x - left_index > h){
max_result++;
left_index=x;
needRead=1;
continue;//next
}else {
//try right
if( i== n+1){
max_result++;
i++;
break;
}else{
int next_x=sc.nextInt();
int next_h=sc.nextInt();
i++;
if( x+ h < next_x){
//okay.
left_index=x+h;
max_result++;
}else{
left_index=x;
}
x=next_x;
h=next_h;
needRead=0;
}
}
}
System.out.println(max_result);
return 1;
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | b6237122b5948d9a32b394e897bbc932 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.util.Scanner;
public class Woodcutters {
public static void main(String[] args) {
int i,j,s=2;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a=new int[n];
int[] b=new int[n];
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
b[i]=sc.nextInt();
}
for(i=1;i<n-1;i++)
{
if(a[i]-a[i-1]>b[i])
{
s++;
}
else if(a[i+1]-a[i]>b[i])
{
s++;
a[i]+=b[i];
}
}
System.out.println(n==1?1:s);
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 40b7860aaa3d44b5e860ec8d25060901 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution545C {
public static void main(String... bob) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader in = new BufferedReader(new FileReader("Solution545C"));
StringTokenizer testCases = new StringTokenizer(in.readLine());
int numTrees = i(testCases.nextToken());
Tree[] trees = new Tree[numTrees];
for (int i = 0; i < numTrees; i++) {
StringTokenizer data = new StringTokenizer(in.readLine());
trees[i] = new Tree(i(data.nextToken()), i(data.nextToken()));
}
int treeFall = trees[0].pos;
int ans = 1;
for (int i = 1; i < numTrees; i++) {
if (trees[i].pos - trees[i].height > treeFall) {
// System.out.println(treeFall);
treeFall = trees[i].pos;
ans++;
} else if (i != numTrees - 1 && trees[i].pos + trees[i].height < trees[i + 1].pos){
treeFall = trees[i].pos + trees[i].height;
ans++;
} else if (i == numTrees - 1) {
ans++;
} else {
treeFall = trees[i].pos;
}
}
System.out.println(ans);
}
static class Tree {
int pos, height;
public Tree(int pos, int height) {
this.pos = pos;
this.height = height;
}
}
public static int i(String str) {
return Integer.parseInt(str);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 600e74f47aec37ced144d6590144da75 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | /**
* Created by kapilkrishnakumar on 10/21/15.
*/
import java.util.*;
public class WoodCutter {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x[] = new int[n];
int h[] = new int[n];
for (int i = 0; i < n; i++) {
x[i] = sc.nextInt();
h[i] = sc.nextInt();
}
int ans = 1;
int max = x[0];
for (int i = 1; i < n - 1; i++) {
int one = x[i] - h[i];
int two = x[i] + h[i];
if (one > max) {
ans++;
max = x[i];
} else if (two < x[i + 1]) {
ans++;
max = two;
} else {
max = x[i];
}
}
if (n != 1)
ans++;
System.out.println(ans);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 308d99557822c98d5e727a53f6b68154 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
private static class Tree {
int position;
int height;
public Tree(int position, int height) {
this.position = position;
this.height = height;
}
}
public static void main(String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Tree [] trees = new Tree[N];
StringTokenizer tokenizer;
for(int i=0; i<N; i++) {
tokenizer = new StringTokenizer(br.readLine());
int x = Integer.parseInt(tokenizer.nextToken());
int height = Integer.parseInt(tokenizer.nextToken());
trees[i] = new Tree(x, height);
}
if(N == 1) {
System.out.println(1);
return;
}
int counter = 2;
int lastPosition = trees[0].position;
for(int i=1; i<N-1; i++) {
if(trees[i].position - trees[i].height > lastPosition) { // push it to the left
counter++;
lastPosition = trees[i].position;
continue;
}
if(trees[i].position + trees[i].height < trees[i+1].position) {
// push it to the right
counter++;
lastPosition = trees[i].position + trees[i].height;
} else {
lastPosition = trees[i].position;
}
}
System.out.println(counter);
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | edbeb2fe9795544363e211b557054667 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 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.HashMap;
import java.util.List;
public class C {
static int n;
static int[][] trees;
static int[][] max;
public static void main(String[] args) throws IOException {
n = readIntArray()[0];
trees = new int[n][];
for (int i = 0; i < n; i++) {
trees[i] = readIntArray();
}
max = new int[n][3];
if (n == 1 || trees[n-1][0] - trees[n-2][0] > trees[n-1][1])
max[n-1][0] = 1;
max[n-1][1] = 1;
max[n-1][2] = 0;
for (int i = n-2; i >= 0; i--) {
if (i == 0 || trees[i][0] - trees[i-1][0] > trees[i][1])
max[i][0] = Math.max(Math.max(max[i+1][0], max[i+1][1]), max[i+1][2]) + 1;
else
max[i][0] = 0;
if (trees[i + 1][0] - trees[i][0] > trees[i][1])
max[i][1] = Math.max(max[i+1][1], max[i+1][2]) + 1;
if (trees[i + 1][0] - trees[i][0] > trees[i][1] + trees[i + 1][1])
max[i][1] = Math.max(Math.max(max[i+1][1], max[i+1][2]), max[i+1][0]) + 1;
max[i][2] = Math.max(Math.max(max[i+1][0], max[i+1][1]), max[i+1][2]);
}
int ans = Math.max(Math.max(max[0][0], max[0][1]), max[0][2]);
System.out.println(ans);
// System.out.println(System.currentTimeMillis() - start);
}
static InputStreamReader isr = new InputStreamReader(System.in);
static BufferedReader br = new BufferedReader(isr);
static int[] readIntArray() throws IOException {
String[] v = br.readLine().split(" ");
int[] ans = new int[v.length];
for (int i = 0; i < ans.length; i++) {
ans[i] = Integer.valueOf(v[i]);
}
return ans;
}
static long[] readLongArray() throws IOException {
String[] v = br.readLine().split(" ");
long[] ans = new long[v.length];
for (int i = 0; i < ans.length; i++) {
ans[i] = Long.valueOf(v[i]);
}
return ans;
}
static <T> void print(List<T> v) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < v.size(); i++) {
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(v.get(i));
}
System.out.println(sb);
}
}
| Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 794abd22bd3c9ea1f9e2b3a806999172 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
public void foo()
{
MyScanner scan = new MyScanner();
int n = scan.nextInt();
Tree[] t = new Tree[n + 1];
for(int i = 0;i < n;++i)
{
t[i] = new Tree(scan.nextInt(), scan.nextInt());
}
if(1 == n)
{
System.out.println(1);
return;
}
t[n] = new Tree(Integer.MAX_VALUE, 0);
int leftPre = 1;
int midPre = 0;
int rightPre = t[0].x + t[0].h < t[1].x ? 1 : 0;
for(int i = 1;i < n;++i)
{
int left = t[i].x - t[i].h > t[i - 1].x ? Math.max(leftPre, midPre) + 1 : 0;
if(t[i].x - t[i].h > t[i - 1].x + t[i - 1].h)
{
left = Math.max(left, rightPre + 1);
}
int mid = Math.max(leftPre, Math.max(midPre, rightPre));
int right = t[i].x + t[i].h < t[i + 1].x ? mid + 1 : 0;
leftPre = left;
midPre = mid;
rightPre = right;
}
System.out.println(Math.max(leftPre, Math.max(midPre, rightPre)));
}
public static void main(String[] args)
{
new Main().foo();
}
class Tree
{
private int x;
private int h;
public Tree(int aX, int aH)
{
x = aX;
h = aH;
}
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 1a96f5ab75fd4a6938b63007f4676500 | train_000.jsonl | 1432053000 | Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
public void foo()
{
MyScanner scan = new MyScanner();
int n = scan.nextInt();
int[] x = new int[n + 1];
int[] h = new int[n + 1];
for(int i = 0;i < n;++i)
{
x[i] = scan.nextInt();
h[i] = scan.nextInt();
}
x[n] = Integer.MAX_VALUE;
int pre = Integer.MIN_VALUE;
int cnt = 0;
for(int i = 0;i < n;++i)
{
if(x[i] - h[i] > pre)
{
++cnt;
pre = x[i];
}
else if(x[i] + h[i] < x[i + 1])
{
++cnt;
pre = x[i] + h[i];
}
else
{
pre = x[i];
}
}
System.out.println(cnt);
}
public static void main(String[] args)
{
new Main().foo();
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"] | 1 second | ["3", "4"] | NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left — now it occupies segment [ - 1;1] fell the 2-nd tree to the right — now it occupies segment [2;3] leave the 3-rd tree — it occupies point 5 leave the 4-th tree — it occupies point 10 fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Java 7 | standard input | [
"dp",
"greedy"
] | a850dd88a67a6295823e70e2c5c857c9 | The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate. | 1,500 | Print a single number — the maximum number of trees that you can cut down by the given rules. | standard output | |
PASSED | 0c030e8618ef2e4b898a7cf3a3c0a1d5 | train_000.jsonl | 1514037900 | A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars. | 256 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF907A extends PrintWriter {
CF907A() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF907A o = new CF907A(); o.main(); o.flush();
}
void main() {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int x = a * 2;
int y = b * 2;
int z = Math.max(c, d);
if (z <= Math.min(c * 2, d * 2) && d < b) {
println(x);
println(y);
println(z);
} else
println(-1);
}
}
| Java | ["50 30 10 10", "100 50 10 21"] | 2 seconds | ["50\n30\n10", "-1"] | NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20. | Java 11 | standard input | [
"implementation",
"brute force"
] | 56535017d012fdfcc13695dfd5b33084 | You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3. | 1,300 | Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes). | standard output | |
PASSED | 99dc2d0ffae34b62a675ee4ddfd1450e | train_000.jsonl | 1514037900 | A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.io.Closeable;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Flushable;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input in = new Input(inputStream);
Output out = new Output(outputStream);
AMashaAndBears solver = new AMashaAndBears();
solver.solve(1, in, out);
out.close();
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29);
thread.start();
thread.join();
}
static class AMashaAndBears {
public AMashaAndBears() {
}
public boolean like(int person, int car) {
return person<=car&&2*person >= car;
}
public void solve(int testNumber, Input in, Output pw) {
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt(), d = in.nextInt();
for(int i = 1; i<=210; i++) {
for(int j = 1; j<i; j++) {
for(int k = 1; k<j; k++) {
if(like(a, i)&&like(b, j)&&like(c, k)&&like(d, k)&&!like(d, i)&&!like(d, j)) {
pw.println(i+"\n"+j+"\n"+k);
return;
}
}
}
}
pw.println(-1);
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public boolean autoFlush;
public String LineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
autoFlush = false;
LineSeparator = System.lineSeparator();
}
public void println(int i) {
println(String.valueOf(i));
}
public void println(String s) {
sb.append(s);
println();
if(autoFlush||sb.length()>BUFFER_SIZE >> 1) {
flush();
}
}
public void println() {
sb.append(LineSeparator);
}
public void flush() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static class Input {
BufferedReader br;
StringTokenizer st;
public Input(InputStream is) {
this(is, 1<<20);
}
public Input(InputStream is, int bs) {
br = new BufferedReader(new InputStreamReader(is), bs);
st = null;
}
public boolean hasNext() {
try {
while(st==null||!st.hasMoreTokens()) {
String s = br.readLine();
if(s==null) {
return false;
}
st = new StringTokenizer(s);
}
return true;
}catch(Exception e) {
return false;
}
}
public String next() {
if(!hasNext()) {
throw new InputMismatchException();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["50 30 10 10", "100 50 10 21"] | 2 seconds | ["50\n30\n10", "-1"] | NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20. | Java 11 | standard input | [
"implementation",
"brute force"
] | 56535017d012fdfcc13695dfd5b33084 | You are given four integers V1, V2, V3, Vm(1 ≤ Vi ≤ 100) — sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3. | 1,300 | Output three integers — sizes of father bear's car, mother bear's car and son bear's car, respectively. If there are multiple possible solutions, print any. If there is no solution, print "-1" (without quotes). | standard output | |
PASSED | fb2d702e931b378fb21f07855a7aa763 | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class start {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// System.out.println((int)'a'+" "+(int)'A');
int n=Integer.parseInt(bf.readLine());
long x[][]=new long [n][n];
for(int i=0;i<n;i++){
StringTokenizer st = new StringTokenizer(bf.readLine(), " ");
for(int j=0;j<n;j++){
x[i][j]=Integer.parseInt(st.nextToken());
}
}
if(n==1&&x[0][0]==0){
System.out.println("1");
return;
}else if(n==1){
System.out.println(-1);
return;
}
int e=0;
int ii=0;
int jj=0;
for(int j=0;j<n;j++){
for(int i=0;i<n;i++){
if(x[j][i]==0)
{ e=j;
ii=j;
jj=i;
}
}
}
int fu=0;
if(e==n-1){
fu=e-1;
}else{
fu=e+1;
}
long big=0;
for(int i=0;i<n;i++){
big+=x[fu][i];
}
long sml=0;
for(int i=0;i<n;i++){
sml+=x[e][i];
}
if(big-sml<=0){
System.out.println(-1);
return;
}
long nw=big-sml;
x[ii][jj]=nw;
//check
for(int j=0;j<n;j++){
long cur=0;
for(int i=0;i<n;i++){
cur+=x[j][i];
}
if(cur!=big){
System.out.println(-1);
return;
}
}
for(int j=0;j<n;j++){
long cur=0;
for(int i=0;i<n;i++){
cur+=x[i][j];
}
if(cur!=big){
System.out.println(-1);
return;
}
}
long cur=0;
for(int j=0;j<n;j++){
for(int i=0;i<n;i++){
if(i==j)
cur+=x[j][i];
}
}
if(cur!=big){
System.out.println(-1);
return;
}
long cur2=0;
for(int j=0;j<n;j++){
for(int i=0;i<n;i++){
if(i+j==x.length-1)
cur2+=x[j][i];
}
}
if(cur2!=big){
System.out.println(-1);
return;
}
System.out.println(big-sml);
}
} | Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | 96f95e009d4fe175b1c47f00234d651d | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
import java.math.MathContext;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class Main {
public static void main(String[] args) throws IOException{
InputReader in = new InputReader(System.in);
Printer out = new Printer(System.out);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, Printer out) throws IOException{
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Scanner sc = new Scanner(System.in);
int n = in.nextInt();
long[][] set = new long[n+1][n+1];
int x = -1 , y = -1;
int count1 = 0 , count2 = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
set[i][j] = in.nextLong();
set[i][n] += set[i][j];
set[n][j] += set[i][j];
if(set[i][j] == 0){
x = i; y = j;
}
}
if(n == 1){
out.println(1);
return;
}
long sum = 0 , sumr = 0, sumc = 0 , sumd1 = 0, sumd2 = 0;
if(x > 0)
sum += set[0][n];
else if(x == 0)
sum += set[1][n];
for(int i = 0; i < n; i++){
if(sum - set[n][i] != 0)
count1++;
if(sum - set[i][n] != 0)
count2++;
//out.println(count1+" "+count2);
if(count1 > 1 || count2 > 1){
out.println(-1);
return;
}
sumr += set[x][i];
sumc += set[i][y];
sumd1 += set[i][i];
sumd2 += set[n-i-1][i];
}
//out.println(count1+" "+count2 +" "+sum+" "+set[2][n]+" "+set[n][2]);
long res = sum - sumr;
if(res < 0){
out.println(-1);
return;
}
if(x == y && x+y == n-1){
if(sum - sumc == res && sum - sumd1 == res && sum - sumd2 == res && res != 0){
out.println(res);
}else
out.println(-1);
return;
}
if(x == y){
if(sum - sumc == res && sum - sumd1 == res && res != 0 && sum == sumd2){
out.println(res);
}else
out.println(-1);
return;
}
//out.println(sum);
if(x+y == n-1){
if(sum - sumc == res && sum - sumd2 == res && res != 0 && sum == sumd1){
out.println(res);
}else
out.println(-1);
return;
}
if(sum - sumc == res && res != 0 && sum == sumd1 && sum == sumd2){
out.println(res);
}else
out.println(-1);
}
}
// ||||||| INPUT READER ||||||||
static class InputReader {
private byte[] buf = new byte[2048];
private int index;
private int total;
private InputStream in;
public InputReader(InputStream stream){
in = stream;
}
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 long scanlong() throws IOException{
long integer = 0;
int n = scan();
while(isWhiteSpace(n))
n = scan();
int neg = 1;
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
integer *= 10;
integer += n - '0';
n = scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
private 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 doubll = 0;
int n = scan();
int neg = 1;
while(isWhiteSpace(n))
n = scan();
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n) && n != '.'){
if(n >= '0' && n <= '9'){
doubll *= 10;
doubll += n - '0';
n = scan();
}
}
if(n == '.'){
n = scan();
double temp = 1;
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
temp /= 10;
doubll += (n - '0')*temp;
n = scan();
}
}
}
return neg*doubll;
}
private float scanfloat() throws IOException {
float doubll = 0;
int n = scan();
int neg = 1;
while(isWhiteSpace(n))
n = scan();
if(n == '-'){
neg = -1;
n = scan();
}
while(!isWhiteSpace(n) && n != '.'){
if(n >= '0' && n <= '9'){
doubll *= 10;
doubll += n - '0';
n = scan();
}
}
if(n == '.'){
n = scan();
double temp = 1;
while(!isWhiteSpace(n)){
if(n >= '0' && n <= '9'){
temp /= 10;
doubll += (n - '0')*temp;
n = scan();
}
}
}
return neg*doubll;
}
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();
}
public boolean isWhiteSpace(int n){
if(n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
return true;
return false;
}
/// Input module
public int nextInt() throws IOException{
return scanInt();
}
public long nextLong() throws IOException{
return scanlong();
}
public double nextDouble() throws IOException{
return scandouble();
}
public float nextFloat() throws IOException{
return scanfloat();
}
public String next() throws IOException{
return scanstring();
}
}
// output writer
static class Printer{
private final BufferedWriter bw;
public Printer(OutputStream out){
bw = new BufferedWriter(new OutputStreamWriter(out));
}
public void print(Object...objects) throws IOException{
for(int i = 0; i < objects.length; i++){
if(i != 0)
bw.append(' ');
bw.append(objects[i].toString());
}
}
public void print(String str) throws IOException{
bw.append(str);
}
public void println(Object...objects) throws IOException {
print(objects);
bw.append("\n");
}
public void close() throws IOException{
bw.close();
}
public void flush() throws IOException{
bw.flush();
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = in.nextInt();
}
return array;
}
}
}
| Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | b40e1161819ca03043315d2a0f78dfc4 | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF_711B {
public static void main(String args[]) {
MScanner sc = new MScanner();
int n = sc.nextInt();
long[][] arr = new long[n][n];
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = (long)sc.nextInt();
if (arr[i][j] == 0) {
x = i;
y = j;
}
}
}
if (n == 1) {
System.out.println(1);
return;
}
long incorrect = 0, correct = 0;
for (int i = 0; i < n; i++) {
incorrect+=arr[x][i];
correct+=arr[(x+1)%n][i];
}
long k=correct-incorrect;
if(k<=0){
System.out.println(-1);
return;
}
arr[x][y]=k;
for (int i = 0; i < n; i++) {
long temp=0, temp1 = 0 ;
for (int j = 0; j < n; j++) {
temp+=arr[i][j];
temp1+=arr[j][i];
}
if(temp!=correct||temp1!=correct){
System.out.println(-1);
return;
}
}
long diag = 0, diag1 = 0;
for (int i = 0; i < n; i++) {
diag+=arr[i][i];
diag1+=arr[i][n-i-1];
}
if(diag!=correct||diag1!=correct){
System.out.println(-1);
return;
}
System.out.println(k);
}
public static class MScanner {
BufferedReader bf;
StringTokenizer st;
public MScanner() {
bf = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreTokens() ) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | d5eec2c6ba76e10102477fccf9ef8707 | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Q5
{
public static void main(String args[])throws IOException
{
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
int n,i,j;
n=in.readInt();
long a[][]=new long[n+1][n+1];
int r=0,c=0;
boolean flag=true;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=in.readInt();
a[i][n]+=a[i][j];
a[n][j]+=a[i][j];
if(a[i][j]==0)
{
r=i;
c=j;
}
}
}
if(n!=1)
{ long ans=0;
long new0=0,new1=0;
for(i=0;i<n;i++)
{
if(i!=r)
{
ans=a[i][n]-a[r][n];
//out.println(a[i][n]+" "+a[r][n]);
if(ans<=0)
{
flag=false;
}
else
{
a[r][c]=ans;
//out.println(ans);
a[r][n]=0;
a[n][c]=0;
for(i=0;i<n;i++)
{
a[r][n]+=a[r][i];
a[n][c]+=a[i][c];
new0+=a[i][i];
new1+=a[i][n-i-1];
}
}
break;
}
}
if(flag)
{
int ct=1;
for(i=0;i<n;i++)//{
if(a[i][n]==new0&&a[n][i]==new0)
ct+=2;
// out.println(a[i][n]+" "+a[n][i]);}
if(new0==new1)
ct++;
if(ct==(2*n+2))
out.println(a[r][c]);
else
out.println("-1");
// out.println(new0+" "+new1);
}
else
out.println("-1");
}
else
out.println("1");
out.flush();
out.close();
}
}
class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream){this.stream = stream;}
public int read(){
if (numChars==-1) throw new InputMismatchException();
if (curChar >= numChars){
curChar = 0;
try {numChars = stream.read(buf);}
catch (IOException e){throw new InputMismatchException();}
if(numChars <= 0) return -1;
}
return buf[curChar++];
}
public int readInt(){
int c = read();
while(isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {sgn = -1;c = read();}
int res = 0;
do {
if(c<'0'||c>'9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c)); return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public 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);
}
}
| Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | 7af7471c1d6570d668aa3651965f087c | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
long[][] arr = new long[n][n];
long[] rows = new long[n];
long[] cols = new long[n];
long[] diags = new long[2];
int x = 0, y = 0, diag1 = 0, diag2 = 0;
for(int i = 0; i < n; i++) {
String[] line = br.readLine().split("\\s");
for(int j = 0; j < line.length; j++) {
arr[i][j] = Long.parseLong(line[j]);
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
rows[i] += arr[i][j];
cols[i] += arr[j][i];
if(i == j) {
diags[0] += arr[i][j];
}
if(i + j == n - 1) {
diags[1] += arr[i][j];
}
if(arr[i][j] == 0) {
x = i;
y = j;
if(i == j) {
diag1 = 1;
}
if(i + j == n - 1) {
diag2 = 2;
}
}
}
}
if(n == 1) {
System.out.println(1);
} else {
//when 0 does not lie in any diagonal
int countCol = x - 1 >= 0 ? x - 1 : x + 1;
long counter1 = 0;
long counter2 = 0;
for(int i = 0; i < n; i++) {
counter1 += arr[countCol][i];
counter2 += arr[x][i];
}
long value = (Math.abs(counter1 - counter2));
if(value == 0) {
System.out.println("-1");
} else {
arr[x][y] = value;
boolean answer = check(arr, counter1);
System.out.println(answer ? value : "-1");
}
}
}
private static boolean check(long[][] arr, long sum) {
long d1 = 0, d2 = 0;
long[] rows = new long[arr.length];
long[] cols = new long[arr.length];
for(int i = 0; i < arr.length; i++) {
long c1 = 0;
long c2 = 0;
for(int j = 0; j < arr.length; j++) {
c1 += arr[i][j];
c2 += arr[j][i];
if(i == j) {
d1 += arr[i][j];
}
if(i + j == arr.length - 1) {
d2 += arr[i][j];
}
cols[i] += arr[i][j];
rows[i] += arr[i][j];
}
if(c1 != c2) {
return false;
}
}
if(d1 != d2) {
return false;
}
if(d1 != sum || d2 != sum) {
return false;
}
for(int i = 0; i < arr.length - 1; i++) {
for(int j = 1; j < arr.length; j++) {
if(rows[i] != rows[j]) {
return false;
}
if(cols[i] != cols[j]) {
return false;
}
}
}
return true;
}
}
| Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | 029efab3dfd7d38510ddc3d20ff69cef | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import java.lang.*;
public class Submission {
private static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args){
try{
int size = Integer.parseInt(bi.readLine());
BigInteger[][] matrix = new BigInteger[size][size];
if(size == 1){
System.out.println(1);
} else {
//Take input and create matrix with numbers
for (int i = 0; i < size; i++) {
String[] rawInput = bi.readLine().split(" ");
BigInteger[] input = new BigInteger[size];
for (int j = 0; j < size; j++) {
input[j] = new BigInteger(rawInput[j]);
}
matrix[i] = input;
}
//Traverse the matrix to get sum of each row, column, diagonal + get row and column of zero element + main sum of matrix + missing element
BigInteger mainSum = new BigInteger("0");
BigInteger answer = new BigInteger("0");
int zeroRowIndex = 0;
int zeroColIndex = 0;
BigInteger[] rowSum = new BigInteger[size];
BigInteger[] colSum = new BigInteger[size];
//Fill colSum array
for (int i = 0; i < size; i++) {
colSum[i] = new BigInteger("0");
}
BigInteger mainDiagSum = new BigInteger("0");
BigInteger secDiagSum = new BigInteger("0");
boolean mainAffected = false;
boolean secAffected = false;
int secDiagIndex = size - 1;
for (int rowIndex = 0; rowIndex < size; rowIndex++) {
BigInteger currRowSum = new BigInteger("0");
boolean nonZeroRow = true;
for (int colIndex = 0; colIndex < size; colIndex++) {
BigInteger element = matrix[rowIndex][colIndex];
if (element.compareTo(new BigInteger("0")) == 0) {
zeroRowIndex = rowIndex;
zeroColIndex = colIndex;
nonZeroRow = false;
}
currRowSum = currRowSum.add(element);
colSum[colIndex] = colSum[colIndex].add(element);
if (rowIndex == colIndex) {
mainDiagSum = mainDiagSum.add(element);
if (element.compareTo(new BigInteger("0")) == 0) {
mainAffected = true;
}
}
if (colIndex == secDiagIndex) {
secDiagSum = secDiagSum.add(element);
secDiagIndex--;
if (element.compareTo(new BigInteger("0")) == 0) {
secAffected = true;
}
}
}
rowSum[rowIndex] = currRowSum;
if (nonZeroRow) {
mainSum = currRowSum;
}
}
//Get missing element & modify sums to account for them
answer = mainSum.subtract(rowSum[zeroRowIndex]);
rowSum[zeroRowIndex] = rowSum[zeroRowIndex].add(answer);
colSum[zeroColIndex] = colSum[zeroColIndex].add(answer);
if (mainAffected) {
mainDiagSum = mainDiagSum.add(answer);
}
if (secAffected) {
secDiagSum = secDiagSum.add(answer);
}
//Preform all checks
boolean rowCheck = true;
boolean colCheck = true;
boolean diagCheck = true;
for (BigInteger num : rowSum) {
if (num.compareTo(mainSum) != 0) {
rowCheck = false;
}
}
for (BigInteger num : colSum) {
if (num.compareTo(mainSum) != 0) {
colCheck = false;
}
}
if (mainDiagSum.compareTo(mainSum) != 0 || secDiagSum.compareTo(mainSum) != 0) {
diagCheck = false;
}
if (rowCheck && colCheck && diagCheck && answer.compareTo(new BigInteger("0")) == 1) {
System.out.println(answer.toString());
} else {
System.out.println(-1);
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
| Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | c66ad94fc3491031a844e79945b50aa6 | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes |
import java.util.*;
import java.io.*;
import java.math.*;
public class aprail152
{
static class InputReader {
private InputStream stream;
private byte[] inbuf = new byte[1024];
private int start= 0;
private int end = 0;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int readByte() {
if (start == -1) throw new UnknownError();
if (end >= start) {
end= 0;
try {
start= stream.read(inbuf);
} catch (IOException e) {
throw new UnknownError();
}
if (start<= 0) return -1;
}
return inbuf[end++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
public static void main(String args[])
{
InputReader sc=new InputReader(System.in);
int n=sc.nextInt();
int a[][]=new int[n][n];
long d1=0,d2=0;
long r[]=new long[n];
long c[]=new long[n];
int p=0,q=n-1,i1=0,j1=0,f0=0,f1=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
if(a[i][j]==0)
{
i1=i;
j1=j;
}
r[i]+=a[i][j];
c[j]+=a[i][j];
if(Math.abs(i-j)==0)
{
d1+=a[i][j];
if(a[i][j]==0)
f0=1;
}
if(i==p && j==q)
{
d2+=a[i][j];
if(a[i][j]==0)
f1=1;
}
}
p++;q--;
}
Set<Long> s=new HashSet<>();
long max1=0,max2=0;
for(int i=0;i<n;i++)
{
s.add(r[i]);
max1=Math.max(max1,r[i]);
}
long ans=0;
if(s.size()>2 || s.size()==1 || r[i1]==max1)
ans=-1;
else
{
s=new TreeSet<>();
for(int i=0;i<n;i++)
{
s.add(c[i]);
max2=Math.max(max2,c[i]);
}
if(s.size()>2 || s.size()==1 || c[j1]==max2)
ans=-1;
else if(max1!=max2)
ans=-1;
else
{
if((d1==d2 && d1==max1 && f0==0 && f1==0)|| (d1==d2 && d1==r[i1] && f0==1 && f1==1)||(d1==max1 && d2==r[i1] && f0==0 && f1==1)||(d1==r[i1] && d2==max1 && f0==1 && f1==0))
ans=max1-r[i1];
else
ans=-1;
}
}
if(n==1)
ans=1;
System.out.println(ans);
}
}
| Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | ea54c5fc717e9f42dc4397ae4d00bcbf | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
public class B {
int N;
long[][] a;
int y,x;
public boolean check1(){
long[] row = new long[N];
long[] col= new long[N];
long[] dia = new long[2];
for(int i = 0;i < N;i++){
if(i == y)continue;
for(int j = 0;j < N;j++){
row[i] += a[i][j];
}
}
for(int i = 0;i < N;i++){
if(i == x);
for(int j = 0;j < N;j++){
col[i] += a[j][i];
}
}
boolean f1 = true;
for(int i= 0;i < N;i++){
if(i == y && i == x){
f1 = false;
break;
}
dia[0] += a[i][i];
}
boolean f2 = true;
for(int i = 0;i < N;i++){
if(i == y && N - i - 1== x){
f2 = false;
break;
}
dia[1] += a[i][N - i - 1];
}
long max = 0;
long min = (long)1e18 + 7;
if(f1){
max = Math.max(max,dia[0]);
min = Math.min(min,dia[0]);
}
if(f2){
max = Math.max(max,dia[1]);
min = Math.min(min, dia[1]);
}
for(int i = 0;i < N;i++){
if(i == y)continue;
max = Math.max(max, row[i]);
min = Math.min(min, row[i]);
}
for(int i = 0;i < N;i++){
if(i == x)continue;
max = Math.max(max,col[i]);
min = Math.min(min,col[i]);
}
return max == min;
}
public long check2(){
long[] row = new long[N];
long[] col = new long[N];
long[] dia = new long[2];
for(int i = 0;i < N;i++){
for(int j = 0;j < N;j++){
row[i] += a[i][j];
col[j] += a[i][j];
}
}
long d1 = row[(y+1)%N] - row[y];
long d2 = col[(x+1)%N] - col[x];
if(d1 != d2)return -1;
a[y][x] = d1;
for(int i = 0;i < N;i++){
dia[0] += a[i][i];
}
for(int i = 0;i < N;i++){
dia[1] += a[i][N - i - 1];
}
if(dia[0] != dia[1])return -1;
row = new long[N];
col = new long[N];
for(int i = 0;i < N;i++){
for(int j = 0;j < N;j++){
row[i] += a[i][j];
col[j] += a[i][j];
}
}
long pre = dia[0];
for(int i = 0;i < N;i++){
if(pre != row[i])return -1;
}
for(int i = 0;i < N;i++){
if(pre != col[i])return -1;
}
return d1 <= 0 ? -1 : d1;
}
public void solve() {
N = nextInt();
a = new long[N][N];
for(int i = 0;i < N;i++){
for(int j = 0;j < N;j++){
a[i][j] = nextInt();
if(a[i][j] == 0){
y = i;
x = j;
}
}
}
if(N == 1){
out.println(1);
return;
}
if(!check1()){
out.println(-1);
return;
}
long res = check2();
out.println(res);
}
public static void main(String[] args) {
out.flush();
new B().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | 79801bde4de97cc949bd89d91d4e1cbe | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.util.Scanner;
public class Problem711B
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = Integer.parseInt(s.nextLine());
long[][] square = new long[n][n];
int row = 0;
int col = 0;
for (int i = 0; i < n; i++)
{
String[] line = s.nextLine().split(" ");
for (int j = 0; j < n; j++)
{
square[i][j] = Integer.parseInt(line[j]);
if (square[i][j] == 0)
{
row = i;
col = j;
}
}
}
long sum = 0;
long rowSum = 0;
long colSum = 0;
long diag1Sum = 0;
long diag2Sum = 0;
if (n > 1)
for (long i : square[row == 0 ? 1 : 0])
sum += i;
else
sum = 1;
for (long i : square[row])
rowSum += i;
for (int i = 0; i < n; i++)
colSum += square[i][col];
long num = sum - rowSum;
boolean isMagic = true;
square[row][col] = num;
for (int i = 0; i < n && isMagic; i++)
{
long partSum = 0;
for (int j = 0; j < n; j++)
{
partSum += square[i][j];
}
if (partSum != sum)
{
isMagic = false;
break;
}
}
for (int i = 0; i < n && isMagic; i++)
{
long partSum = 0;
for (int j = 0; j < n; j++)
{
partSum += square[j][i];
}
if (partSum != sum)
{
isMagic = false;
break;
}
}
for (int i = 0; i < n; i++)
diag1Sum += square[i][i];
for (int i = 0; i < n; i++)
diag2Sum += square[i][Math.abs(i - n + 1)];
if (diag1Sum != sum || diag2Sum != sum)
isMagic = false;
if (num > 0 && isMagic)
{
System.out.println(num);
}
else
System.out.println(-1);
}
} | Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | fea7da5d9af4162e7ae86c486a066d94 | train_000.jsonl | 1472472300 | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal — and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible? | 256 megabytes | import java.util.Scanner;
public class main {
public static void main(String[] args) {
kvadrat();
}
private static void kvadrat(){
try{
Scanner s = new Scanner(System.in);
long size = s.nextInt();
if(size == 1){
System.out.println(1);
return;
}
long zx = 0;
long zy = 0;
long[] sizeCol = new long[(int)size];
long[] sizeRow = new long[(int)size];
long d1 = 0;
long d2 = 0;
for(long i=0; i<size; i++){
for(long j=0; j<size; j++){
int a = s.nextInt();
sizeCol[(int)i] = sizeCol[(int)i] + a;
sizeRow[(int)j] = sizeRow[(int)j] + a;
if(i==j){
d1 = d1+a;
}
if(i==size-j-1){
d2 = d2+a;
}
if(a==0){
zx=i;
zy=j;
}
}
}
long sum = 0;
for(long k=0; k<size;k++){
if((k!=zx)&&(k!=zy)){
if(sizeCol[(int)k] != sizeRow[(int)k]){
minusOne();
return;
}
else{
if(sum==0){
sum = sizeCol[(int)k];
}else if(sum!=sizeCol[(int)k]){
minusOne();
return;
}
}
}
}
long s2 = sum - sizeCol[(int)zx];
long s3 = sum - sizeRow[(int)zy];
if((s2!=s3)){
minusOne();
return;
}
sizeCol[(int)zx] = sizeCol[(int)zx]+s2;
sizeRow[(int)zy]=sizeRow[(int)zy]+s3;
if((sizeCol[(int)zx]!=sizeRow[(int)zx])||(sizeCol[(int)zy]!=sizeRow[(int)zy])){
minusOne();
return;
}
if(zx == zy){
long s1 = sum - d1;
d1=d1+s1;
if(!((s1==s2))){
minusOne();
return;
}
}
if(zx == size-zy-1){
long s1 = sum - d2;
d2 = d2+s1;
if(!((s1==s2))){
minusOne();
return;
}
}
if((s2>0)&&(d1==d2)&&(d1==sum)){
System.out.println(s2);
return;
}else{
minusOne();
return;
}
}catch(Exception e){
System.err.println(e.getMessage());
}
}
private static void minusOne(){
System.out.println(-1);
}
} | Java | ["3\n4 0 2\n3 5 7\n8 1 6", "4\n1 1 1 1\n1 1 0 1\n1 1 1 1\n1 1 1 1", "4\n1 1 1 1\n1 1 0 1\n1 1 2 1\n1 1 1 1"] | 2 seconds | ["9", "1", "-1"] | NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Java 8 | standard input | [
"constructive algorithms",
"implementation"
] | 3bd5a228ed5faf997956570f96becd73 | The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0. | 1,400 | Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output - 1 instead. If there are multiple solutions, you may print any of them. | standard output | |
PASSED | b637fe5b47e35e5a80801fa6c9b3a393 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
/*
Once a legend said : "Tries matlab string manipulation...for other info, go to page number 352 of the book."
*/
public class Main implements Runnable {
public boolean required(char[] s) {
int flag = 0;
for(int i = 0; i < s.length - 1; ++i) {
if(s[i] == 'R' && s[i + 1] == 'L')
flag = 1;
}
return flag == 0 ? false : true;
}
public void run() {
Maruti800 sc = new Maruti800(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int k = sc.nextInt();
char[] s = sc.next().toCharArray();
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int count = 0;
while(required(s)) {
ArrayList<Integer> curList = new ArrayList<>();
for(int i = 0; i < s.length - 1; ++i) {
if(s[i] == 'R' && s[i + 1] == 'L') {
s[i] = 'L';
s[i + 1] = 'R';
curList.add((i + 1));
i++;
count++;
}
}
list.add(curList);
}
if(list.size() > k || count < k)
out.print("-1");
else {
int extraNeed = k - list.size();
for(ArrayList<Integer> curList : list) {
int rem = min(extraNeed, curList.size() - 1);
extraNeed -= rem;
for(int i = 0; i < rem; ++i) {
out.println("1 " + curList.get(i));
}
out.print((curList.size() - rem) + " ");
for(int i = rem; i < curList.size(); ++i)
out.print(curList.get(i) + " ");
out.println();
}
}
out.close();
}
static class Maruti800 {
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 Maruti800(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 6b37738be245a56e323df45f98438457 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class SolD{
public static void main(String[] args){
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n = sc.nextInt();
long k = sc.nextLong();
String s = sc.next();
char[] chArray = s.toCharArray();
List<List<Integer>> list = new ArrayList<>();
long ans = 0;
long p = 0;
while(true){
List<Integer> arrList = new ArrayList<>();
for(int j=0; j<n-1; j++){
if(chArray[j]=='R' && chArray[j+1]=='L'){
chArray[j]='L';
arrList.add(j+1);
chArray[j+1]='R';
j++;
}
}
if(arrList.isEmpty()) break;
p += arrList.size();
list.add(arrList);
ans++;
}
if(k<ans || k>p){
System.out.println(-1);
return;
}
long extra = k - ans;
StringBuilder r = new StringBuilder("");
for(int i=0; i<list.size(); i++){
int m = list.get(i).size();
int j = 0;
while(extra>0 && j<m-1){
r.append(1+" "+list.get(i).get(j));
r.append("\n");
extra--;
j++;
}
if(j!=m) r.append(m-j + " ");
for( ; j<m; j++){
r.append(list.get(i).get(j)+" ");
}
r.append("\n");
}
System.out.println(r);
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 362d0bc5b304ac79766de46c0c7bc3eb | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main {
static class Task {
int NN = 200005;
int MOD = 1000000007;
int INF = 2000000000;
long INFINITY = 2000000000000000000L;
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
StringBuilder s = new StringBuilder(in.nextLine());
List<List<Integer>> L = new ArrayList<>();
int mn = 0, mx = 0;
while(true) {
boolean found = false;
List<Integer> l = new ArrayList<>();
for(int i=0;i+1<n;++i) {
if(s.charAt(i) =='R' && s.charAt(i+1)=='L') {
found = true;
l.add(i+1);++mx;
s.setCharAt(i, 'L');
s.setCharAt(i+1,'R');++i;
}
}
if(!found){
break;
}
L.add(l);
++mn;
}
if(k < mn || k > mx) {
out.println(-1);
} else {
int rem = k - mn;
for(int i=0;i<L.size();++i) {
List<Integer> l = L.get(i);
int sz = l.size();int extra=0;
for(int j=0;j<rem&&j+1<l.size();++j) {
out.println("1 "+l.get(j));++extra;
}
out.print((l.size() - extra) + " ");
for(int j=extra;j<l.size();++j) {
out.print(l.get(j)+" ");
}
out.println();
rem -= extra;
}
}
}
}
static void prepareIO(boolean isFileIO) {
//long t1 = System.currentTimeMillis();
Task solver = new Task();
// Standard IO
if(!isFileIO) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver.solve(in, out);
//out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
out.close();
}
// File IO
else {
String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in";
String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out";
InputReader fin = new InputReader(IPfilePath);
PrintWriter fout = null;
try {
fout = new PrintWriter(new File(OPfilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
solver.solve(fin, fout);
//fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0);
fout.close();
}
}
public static void main(String[] args) {
prepareIO(false);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public InputReader(String filePath) {
File file = new File(filePath);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 09be004dcd59f0d73aa36019a708b0f6 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Solve5 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve5().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int n = sc.nextInt(), k = sc.nextInt();
char[] c = sc.next().toCharArray();
int steps = 0;
for (int i = 0, j = 0; i < n; i++) {
if (c[i] == 'R') {
++j;
} else {
steps += j;
}
}
if (steps < k) {
pw.println(-1);
} else {
int diff = steps - k;
int[][] a = new int[k][];
TreeSet<Integer> ts = new TreeSet();
for (int j = 0; j < n; j++) {
if (j + 1 < n && c[j] == 'R' && c[j + 1] == 'L') {
ts.add(j);
}
}
for (int i = 0; i < k; i++) {
int p = 1;
if (diff > 0) {
p += Math.min(ts.size() - 1, diff);
diff -= p - 1;
}
a[i] = new int[p];
ArrayList<Integer> temp = new ArrayList();
int ind = 0;
while (p > 0) {
int x = ts.pollFirst();
a[i][ind++] = x + 1;
c[x] = 'L';
c[x + 1] = 'R';
temp.add(x);
--p;
}
for (int j = 0; j < temp.size(); j++) {
int x = temp.get(j);
if (x + 2 < n && c[x + 2] == 'L') {
ts.add(x + 1);
}
if (x - 1 >= 0 && c[x - 1] == 'R') {
ts.add(x - 1);
}
}
}
if (diff > 0) {
pw.println(-1);
} else {
for (int i = 0; i < k; i++) {
pw.print(a[i].length + " ");
for (int j = 0; j < a[i].length; j++) {
pw.print(a[i][j] + (j + 1 == a[i].length ? "\n" : " "));
}
}
}
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
}
return null;
}
public boolean hasNext() throws IOException {
if (st != null && st.hasMoreTokens()) {
return true;
}
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | c4259b6ee1bc4be94b704d2a4a6d3fa5 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1333D extends PrintWriter {
CF1333D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1333D o = new CF1333D(); o.main(); o.flush();
}
static class V {
V next;
int i;
V(int i) {
this.i = i;
}
}
V[] vv;
V head, tail;
byte[] cc; int n;
void add(int i) {
if (i >= 0 && i + 1 < n && cc[i] == 'R' && cc[i + 1] == 'L') {
V v = vv[i];
v.next = null;
if (tail == null)
head = tail = v;
else
tail = tail.next = v;
}
}
void main() {
n = sc.nextInt();
int k = sc.nextInt();
cc = sc.next().getBytes();
int sum = 0, cnt = 0;
for (int i = 0; i < n; i++)
if (cc[i] == 'R')
cnt++;
else
sum += cnt;
if (sum < k) {
println(-1);
return;
}
vv = new V[n];
for (int i = 0; i < n; i++) {
vv[i] = new V(i);
add(i);
}
int[][] ans = new int[k][];
int[] qu = new int[n];
for (int h = 0; h < k; h++) {
int m = k - 1 - h;
V u = head, v = tail; head = tail = null;
cnt = 0;
while (u != null && sum > m) {
int i = u.i;
qu[cnt++] = i; cc[i] = 'L'; cc[i + 1] = 'R';
add(i - 1); add(i + 1);
u = u.next; sum--;
}
if (u != null) {
if (tail == null) {
head = u; tail = v;
} else {
tail.next = u;
tail = v;
}
}
ans[h] = Arrays.copyOf(qu, cnt);
}
if (sum > 0) {
println(-1);
return;
}
for (int h = 0; h < k; h++) {
qu = ans[h];
cnt = qu.length;
print(cnt);
while (cnt-- > 0)
print(" " + (qu[cnt] + 1));
println();
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | a6f6eccf1683975e547ebf673a6addc4 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | // upsolve with kaiboy
import java.io.*;
import java.util.*;
public class CF1333D extends PrintWriter {
CF1333D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1333D o = new CF1333D(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int k = sc.nextInt();
byte[] cc = sc.next().getBytes();
int sum = 0, cnt = 0;
for (int i = 0; i < n; i++)
if (cc[i] == 'R')
cnt++;
else
sum += cnt;
if (sum < k) {
println(-1);
return;
}
byte[] cc_ = Arrays.copyOf(cc, n);
int k_ = 0, sum_ = sum;
while (sum_ > 0) {
k_++;
if (k_ > k || k_ > n * 2) {
println(-1);
return;
}
for (int i = 0; i + 1 < n; i++)
if (cc_[i] == 'R' && cc_[i + 1] == 'L') {
cc_[i] = 'L'; cc_[i + 1] = 'R';
sum_--;
i++;
}
}
int[] qu = new int[n / 2];
while (sum > k && k-- > 0) {
cnt = 0;
for (int i = 0; i + 1 < n && sum > k; i++)
if (cc[i] == 'R' && cc[i + 1] == 'L') {
qu[cnt++] = i;
cc[i] = 'L'; cc[i + 1] = 'R';
sum--;
i++;
}
print(cnt);
while (cnt-- > 0)
print(" " + (qu[cnt] + 1));
println();
}
for (int h = 0; h < n; h++)
for (int i = 0; i + 1 < n; i++)
if (cc[i] == 'R' && cc[i + 1] == 'L') {
println("1 " + (i + 1));
cc[i] = 'L'; cc[i + 1] = 'R';
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | d6cf617e6df1e73af6534c814dc12307 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int i, j;
int n = in.nextInt();
int k = in.nextInt();
boolean arr[] = new boolean[n];
char x[] = in.next().toCharArray();
long count = 0;
for (i = 0; i < n; i++) {
if (x[i] == 'R')
arr[i] = true;
else
count++;
}
long sum = 0;
for (i = 0; i < n; i++) {
if (arr[i])
sum += count;
else
count--;
}
//System.out.println(sum);
int f=0;
if (k > sum) {
System.out.println("-1");
} else {
int temp = k;
while (sum - temp > 0) {
int c = 0;
for (i = 0; i < n - 1; i++) {
if (arr[i] && !arr[i + 1])
c++;
}
//System.out.println(c);
if (sum - temp >= c - 1) {
sb.append(c + " ");
for (i = 0; i < n - 1; i++) {
if (arr[i] && !arr[i + 1]) {
sb.append(i + 1).append(" ");
arr[i] = false;
arr[i + 1] = true;
i++;
}
}
sb.append("\n");
sum -= c;
temp--;
} else {
int z = 0;
sb.append(sum - temp + 1).append(" ");
for (i = 0; i < n - 1; i++) {
if (arr[i] && !arr[i + 1]) {
sb.append(i + 1).append(" ");
arr[i] = false;
arr[i + 1] = true;
i++;
z++;
if (z == sum - temp + 1)
break;
}
}
sb.append("\n");
temp--;
sum = temp;
}
if(temp<=0 && sum>0){
f=1;
break;
}
}
if(f==1){
System.out.println("-1");
System.exit(0);
}
while (temp != 0) {
for (i = 0; i < n - 1; i++) {
if (arr[i] && !arr[i + 1]) {
sb.append("1 ").append(i + 1).append("\n");
arr[i] = false;
arr[i + 1] = true;
i++;
temp--;
}
}
}
System.out.print(sb);
}
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
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();
}
int nextInt() throws IOException {
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;
}
long nextLong() throws IOException {
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;
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | ed95e064cc4a42df5086b2438e680d66 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1333d {
public static void main(String[] args) throws IOException {
int n = rni(), k = ni(), cnt = 0;
char[] s = rcha();
long maxk = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == 'R') {
maxk += n - i - cnt++ - 1;
}
}
// prln(maxk);
if (k > maxk) {
prln(-1);
close();
return;
}
List<List<Integer>> ans = new ArrayList<>();
while (true) {
List<Integer> moves = new ArrayList<>();
char[] new_s = new char[n];
for (int i = 0; i < n; ++i) {
if (i < n - 1 && s[i] == 'R' && s[i + 1] == 'L') {
new_s[i + 1] = 'R';
new_s[i] = 'L';
moves.add(i + 1);
++i;
} else {
new_s[i] = s[i];
}
}
if (moves.size() == 0) {
break;
}
s = new_s;
ans.add(moves);
}
int min_moves = ans.size();
if (k < min_moves) {
prln(-1);
close();
return;
}
// for (List<Integer> moves : ans) {
// prln(moves);
// }
for (int i = 0; i < min_moves; ++i) {
List<Integer> moves = ans.get(i);
int ind = 0, n_moves = moves.size();
while (k > min_moves - i && ind < n_moves) {
pr(1);
pr(' ');
prln(moves.get(ind++));
--k;
}
if (ind < n_moves) {
pr(n_moves - ind);
pr(' ');
for (int j = ind; j < n_moves - 1; ++j) {
pr(moves.get(j));
pr(' ');
}
prln(moves.get(n_moves - 1));
--k;
}
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static void pryesno(boolean b) {prln(b ? "yes" : "no");};
static void pryn(boolean b) {prln(b ? "Yes" : "No");}
static void prYN(boolean b) {prln(b ? "YES" : "NO");}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 2e4c257c537bfd70c2505ae30bddfcf4 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedOutputStream;
import java.util.StringTokenizer;
import java.io.Closeable;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.Flushable;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input in = new Input(inputStream);
Output out = new Output(outputStream);
DChallengesInSchool41 solver = new DChallengesInSchool41();
solver.solve(1, in, out);
out.close();
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29);
thread.start();
thread.join();
}
static class DChallengesInSchool41 {
public DChallengesInSchool41() {
}
public void solve(int kase, Input in, Output pw) {
int n = in.nextInt(), k = in.nextInt();
boolean[] arr = new boolean[n];
String s = in.next();
for(int i = 0; i<n; i++) {
arr[i] = s.charAt(i)=='R';
}
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
boolean changed = true;
int tot = 0;
while(changed) {
changed = false;
ArrayList<Integer> cur = new ArrayList<>();
for(int i = 0; i<n-1; i++) {
if(arr[i]&&!arr[i+1]) {
arr[i] ^= true;
arr[i+1] ^= true;
cur.add(i);
i++;
tot++;
}
}
changed = cur.size()>0;
if(changed) {
ans.add(cur);
}
}
if(k<ans.size()||k>tot) {
pw.println(-1);
return;
}
int cnt = 0;
for(int i = 0; i<ans.size(); i++) {
int j;
ArrayList<Integer> cur = ans.get(i);
for(j = 0; j<cur.size()&&cnt+ans.size()-i<k; j++) {
pw.println(1, cur.get(j)+1);
cnt++;
}
if(j!=cur.size()) {
pw.print(cur.size()-j);
for(int a = j; a<cur.size(); a++) {
pw.print(" "+(cur.get(a)+1));
}
pw.println();
cnt++;
}
}
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public boolean autoFlush;
public String LineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
autoFlush = false;
LineSeparator = System.lineSeparator();
}
public void print(int i) {
print(String.valueOf(i));
}
public void print(String s) {
sb.append(s);
if(autoFlush) {
flush();
}else if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println(int i) {
println(String.valueOf(i));
}
public void println(Object... o) {
for(int i = 0; i<o.length; i++) {
if(i!=0) {
print(" ");
}
print(String.valueOf(o[i]));
}
println();
}
public void println(String s) {
sb.append(s);
println();
if(autoFlush) {
flush();
}else if(sb.length()>BUFFER_SIZE >> 1) {
flushToBuffer();
}
}
public void println() {
sb.append(LineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
static class Input {
BufferedReader br;
StringTokenizer st;
public Input(InputStream is) {
this(is, 1<<20);
}
public Input(InputStream is, int bs) {
br = new BufferedReader(new InputStreamReader(is), bs);
st = null;
}
public boolean hasNext() {
try {
while(st==null||!st.hasMoreTokens()) {
String s = br.readLine();
if(s==null) {
return false;
}
st = new StringTokenizer(s);
}
return true;
}catch(Exception e) {
return false;
}
}
public String next() {
if(!hasNext()) {
throw new InputMismatchException();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 0d323c011191a97dab8c81955f1a3a7c | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class D {
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
String str = in.next();
char[] arr = str.toCharArray();
List<List<Integer>> ansList = new ArrayList<>();
long RLCount = 0;
while (true) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
if (arr[i] == 'R' && arr[i + 1] == 'L') {
RLCount++;
list.add(i + 1);
arr[i] = 'L';
arr[i + 1] = 'R';
i++;
}
}
if (list.isEmpty()) {
break;
}
ansList.add(list);
}
if (ansList.size() > k || RLCount < k) {
out.println(-1);
return;
}
// 类似 10, 7,4
int ansListSize = ansList.size();
for (int cur = 0; cur < ansList.size(); cur++) {
List<Integer> indexList = ansList.get(cur);
int indexSize = indexList.size();
for (int i = 0; i < indexSize; i++) {
if (ansListSize - cur < k) {
out.println(1 + " " + indexList.get(i));
k--;
} else {
out.print(indexSize - i + " ");
for (int j = i; j < indexSize; j++) {
out.print(indexList.get(j) + " ");
}
out.println();
k--;
break;
}
}
}
}
}
private static void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(1, in, out);
out.close();
}
public static void main(String[] args) {
new Thread(null, () -> solve(), "1", 1 << 26).start();
}
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());
}
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | e912064038fe536c38127dbe837c4d21 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws Exception
{
new D().run();
}
LinkedList<Integer> inversionLocations = new LinkedList<Integer>();
int K;
int inversions;
char[] chars;
ArrayList<Integer> toAdd = new ArrayList<Integer>();
public void run() throws Exception
{
BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(file.readLine());
int N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
chars = file.readLine().toCharArray();
inversions = 0;
int R = 0;
int minK = 0;
for(int i = 0;i<chars.length;i++)
{
if(chars[i] == 'L')
{
minK = R;
inversions += R;
}else{
R++;
}
}
for(int i = 0;i<chars.length-1;i++)
{
if(chars[i] == 'R' && chars[i+1] == 'L')
{
inversionLocations.add(i);
}
}
String[] turns = new String[K];
for(int i = 0;i<K;i++)
{
turns[i] = doTurn(i+1);
if(turns[i] == null)
return;
}
if(inversionLocations.isEmpty())
{
PrintWriter pout = new PrintWriter(System.out);
for(String s: turns)
{
pout.println(s);
}
pout.flush();
}else {
System.out.println(-1);
}
}
public String doTurn(int turnNum)
{
toAdd.clear();
StringBuilder turn = new StringBuilder("");
int remainingTurns = K - turnNum;
int fixed = 0;
while(!inversionLocations.isEmpty() && inversions > remainingTurns)
{
fixed++;
int inv = inversionLocations.remove();
//System.out.println("fixing "+inv);
fixInversion(inv);
inversions--;
turn.append(inv+1);
turn.append(" ");
}
if(fixed == 0)
{
System.out.println(-1);
return null;
}
StringBuffer ret = new StringBuffer("");
ret.append(fixed);
ret.append(" ");
ret.append(turn.toString());
inversionLocations.addAll(toAdd);
return ret.toString();
}
public void fixInversion(int i)
{
chars[i] = 'L';
chars[i+1] = 'R';
if(i != 0 && chars[i-1] == 'R')
{
toAdd.add(i-1);
}
if(i+1 != chars.length - 1 && chars[i+2] == 'L')
{
toAdd.add(i+1);
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 22381d41373ec156d44049f5665e90e2 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DChallengesInSchool41 solver = new DChallengesInSchool41();
solver.solve(1, in, out);
out.close();
}
static class DChallengesInSchool41 {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int k = in.scanInt();
char arr[] = in.scanString().toCharArray();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
int count = 0;
while (true) {
ArrayList<Integer> avlTree = new ArrayList<>();
for (int j = 1; j < n; j++) {
if (arr[j] == 'L' && arr[j - 1] == 'R') {
arr[j] = 'R';
arr[j - 1] = 'L';
avlTree.add(j);
j++;
count++;
}
}
if (avlTree.size() != 0) res.add(avlTree);
else break;
}
if (count < k || res.size() > k) {
out.println(-1);
} else {
int curr = res.size();
int need = k - curr;
for (int i = 0; i < res.size(); i++) {
if (need > 0 && res.get(i).size() > 1) {
int j = 0;
int x = 0;
for (j = 0; j < res.get(i).size() - 1 && need > 0; j++) {
out.println(1 + " " + res.get(i).get(j));
x++;
need--;
}
out.print((res.get(i).size() - x) + " ");
for (; j < res.get(i).size(); j++) {
out.print(res.get(i).get(j) + " ");
}
out.println();
} else {
out.print(res.get(i).size() + " ");
for (int j = 0; j < res.get(i).size(); j++) {
out.print(res.get(i).get(j) + " ");
}
out.println();
}
}
}
}
}
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 I = 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') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
public String scanString() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder RESULT = new StringBuilder();
do {
RESULT.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return RESULT.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | d5ab5948ca3d6165058f8515a80d4c9e | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.util.LinkedList;
import java.util.Queue;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 22:09:35 08/04/2020
Custom Competitive programming helper.
*/
public class Main {
public static void solve(Reader in, Writer out) {
int n = in.nextInt(), k = in.nextInt();
char[] a = in.next().toCharArray();
int sz = k+10;
Queue<Integer> v[] = new LinkedList[sz];
for(int i = 0; i<sz; i++) v[i] = new LinkedList<Integer>();
int steps = 0, totalSteps = 0;
while(true) {
for(int i = 0; i<n-1; i++) {
if(a[i]=='R'&&a[i+1]=='L') {
v[steps].add(i);
a[i] = 'L';
a[i+1] = 'R';
totalSteps++;
i++;
}
}
if(v[steps].isEmpty()) break;
if(steps>k) break;
steps++;
}
if(steps<=k&&k<=totalSteps) {
int idx = 0;
for(int i = 0; i<k; i++) {
if(v[idx].isEmpty()) idx++;
if(steps<k) {
out.println(1+" "+(v[idx].poll()+1));
if(!v[idx].isEmpty()) steps++;
}else {
out.print(v[idx].size()+" ");
while(!v[idx].isEmpty()) out.print((v[idx].poll()+1)+" ");
out.println();
}
}
}else out.println(-1);
}
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 Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
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 Util{
private static Random random = new Random();
//##################################################################################################################
//# Factorial computation algorithm #
//##################################################################################################################
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
//##################################################################################################################
//# Mod inverse algorithm #
//##################################################################################################################
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
//##################################################################################################################
//# Euclid's gcd extended algorithm #
//##################################################################################################################
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
//##################################################################################################################
//# nCr computation algorithms. #
//##################################################################################################################
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
//##################################################################################################################
//# nPr computation algorithms. #
//##################################################################################################################
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
//##################################################################################################################
//# Checks if the given integer is Prime #
//##################################################################################################################
public 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;
}
//##################################################################################################################
//# Returns the smallest index i such that a[i]>=val, for int and long values #
//##################################################################################################################
public static int lowerBound(int[] a, int v) {
int l = 0, h = a.length;
while(l<h) {
int mid = (l+h)/2;
if(v<=a[mid]) h = mid;
else l = mid+1;
}
return l;
}
public static int lowerBound(long[] a, long v) {
int l = 0, h = a.length;
while(l<h) {
int mid = (l+h)/2;
if(v<=a[mid]) h = mid;
else l = mid+1;
}
return l;
}
//##################################################################################################################
//# Returns the smallest index i such that a[i]>val, for int and long values #
//##################################################################################################################
public static int upperBound(int[] a, int v) {
int l = 0, h = a.length;
while(l<h) {
int mid = (l+h)/2;
if(a[mid]<=v) l = mid+1;
else h = mid;
}
return l;
}
public static int upperBound(long[] a, long v) {
int l = 0, h = a.length;
while(l<h) {
int mid = (l+h)/2;
if(a[mid]<=v) l = mid+1;
else h = mid;
}
return l;
}
//##################################################################################################################
//# Returns the sieve of eratosthenes up to a value n. #
//##################################################################################################################
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;
}
//##################################################################################################################
//# Gcd algorithms for long and int values. #
//##################################################################################################################
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
//##################################################################################################################
//# Random number generator, from min to max. #
//##################################################################################################################
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
//##################################################################################################################
//# Helper function for debug. #
//##################################################################################################################
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
//##################################################################################################################
//# Reverse functions for int, long, float, double, char data types and for objects. #
//##################################################################################################################
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
//##################################################################################################################
//# Shuffle functions for int, long, float, double, char data types and for objects. #
//##################################################################################################################
public 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;
}
}
public 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;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public 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;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
//##################################################################################################################
//# Sort functions for int, long, float, double, char data types and for Objects that implement comparable. #
//# The reason that we shuffle all the data types except the Object one, is that java uses merge sort for #
//# Objects and quickSort for the other data types. QuickSort can go up to O(n^2) for some anti-java testcases, #
//# so we need to shuffle the array to prevent that. #
//##################################################################################################################
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
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 | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 5d1886020075eb0b9101e2ed1874a398 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | //package round632;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), K = ni();
char[] s = ns(n);
List<List<Integer>> route = new ArrayList<>();
int all = 0;
for(;;){
List<Integer> lr = new ArrayList<>();
for(int i = 0;i < n-1;i++){
if(s[i] == 'R' && s[i+1] == 'L'){
lr.add(i);
}
}
if(lr.size() == 0)break;
all += lr.size();
for(int t : lr){
s[t] = 'L'; s[t+1] = 'R';
}
route.add(lr);
}
if(K < route.size() || K > all){
out.println(-1);
return;
}
K -= route.size();
for(int i = 0;i < route.size();i++){
int j = 0;
for(;j < route.get(i).size()-1 && K > 0;j++){
out.print(1 + " ");
out.println(route.get(i).get(j)+1);
K--;
}
out.print((route.get(i).size()-j));
for(;j < route.get(i).size();j++){
out.print(" " + (route.get(i).get(j)+1));
}
out.println();
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | a0090c36c962913007f299b2e270dd81 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class D {
static class Task {
private void swap(char[] arr, int i, int j) {
char t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
String str = in.next();
char[] arr = str.toCharArray();
List<List<Integer>> ansList = new ArrayList<>();
long RLCount = 0;
while (true) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
if (arr[i] == 'R' && arr[i + 1] == 'L') {
RLCount++;
list.add(i + 1);
swap(arr, i, i + 1);
i++;
}
}
if (list.isEmpty()) {
break;
}
ansList.add(list);
}
if (ansList.size() > k || RLCount < k) {
out.println(-1);
return;
}
// 类似 10, 7,4
int ansListSize = ansList.size();
for (int cur = 0; cur < ansList.size(); cur++) {
List<Integer> indexList = ansList.get(cur);
int indexSize = indexList.size();
for (int i = 0; i < indexSize; i++) {
if (ansListSize - cur < k) {
out.println(1 + " " + indexList.get(i));
k--;
} else {
out.print(indexSize - i + " ");
for (int j = i; j < indexSize; j++) {
out.print(indexList.get(j) + " ");
}
out.println();
k--;
break;
}
}
}
}
}
private static void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(1, in, out);
out.close();
}
public static void main(String[] args) {
new Thread(null, () -> solve(), "1", 1 << 26).start();
}
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());
}
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 8b3dfb2be5b6c6f6b893d53e4f660111 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class D {
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
String str = in.next();
char[] arr = str.toCharArray();
List<List<Integer>> ansList = new ArrayList<>();
long RLCount = 0;
while (true) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
if (arr[i] == 'R' && arr[i + 1] == 'L') {
RLCount++;
list.add(i + 1);
arr[i] = 'L';
arr[i + 1] = 'R';
i++;
}
}
if (list.isEmpty()) {
break;
}
ansList.add(list);
}
if (ansList.size() > k || RLCount < k) {
out.println(-1);
return;
}
// 类似 10, 7,4
int ansListSize = ansList.size();
for (int cur = 0; cur < ansList.size(); cur++) {
List<Integer> indexList = ansList.get(cur);
int indexSize = indexList.size();
for (int i = 0; i < indexSize; i++) {
if (ansListSize - cur < k) {
out.println(1 + " " + indexList.get(i));
k--;
} else {
out.print(indexSize - i + " ");
for (int j = i; j < indexSize; j++) {
out.print(indexList.get(j) + " ");
}
out.println();
k--;
break;
}
}
}
}
}
private static void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task task = new Task();
task.solve(1, in, out);
out.close();
}
public static void main(String[] args) {
new Thread(null, () -> solve(), "1", 1 << 26).start();
}
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());
}
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 7d44c5ef74231f40eae36a1145d8bef4 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class SolD{
public static void main(String[] args){
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n = sc.nextInt();
long k = sc.nextLong();
String s = sc.next();
char[] chArray = s.toCharArray();
List<List<Integer>> list = new ArrayList<>();
long ans = 0;
long p = 0;
while(true){
List<Integer> arrList = new ArrayList<>();
for(int j=0; j<n-1; j++){
if(chArray[j]=='R' && chArray[j+1]=='L'){
chArray[j]='L';
arrList.add(j+1);
chArray[j+1]='R';
j++;
}
}
if(arrList.isEmpty()) break;
p += arrList.size();
list.add(arrList);
ans++;
}
if(k<ans || k>p){
System.out.println(-1);
return;
}
long extra = k - ans;
StringBuilder r = new StringBuilder("");
for(int i=0; i<list.size(); i++){
int m = list.get(i).size();
int j = 0;
while(extra>0 && j<m-1){
r.append(1+" "+list.get(i).get(j));
r.append("\n");
extra--;
j++;
}
if(j!=m) r.append(m-j + " ");
for( ; j<m; j++){
r.append(list.get(i).get(j)+" ");
}
r.append("\n");
}
System.out.println(r);
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 860b5c1d3e5715b7d5c5937b3af94c63 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
public class Main {
static int[][] vis;
static void solve(TreeMap<Integer, Integer>rmap, TreeMap<Integer, Integer>gmap, TreeMap<Integer, Integer>bmap){
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//int tests =sc.nextInt();
int tests =1;
OutputStream out = new BufferedOutputStream( System.out );
for (int z=0;z<tests;z++) {
int n = sc.nextInt();
int k = sc.nextInt();
sc.nextLine();
String c = sc.nextLine();
StringBuilder sb = new StringBuilder(c);
boolean changed = true;
List< Integer>[] arr = new ArrayList[k];
int m = 0;
boolean failed = false;
long tot = 0;
while (changed){
List<Integer > step= new ArrayList<>();
changed = false;
for (int i=0; i<n-1;i++){
if (sb.charAt(i)=='R' && sb.charAt(i+1)=='L'){
sb.setCharAt(i, 'L');
sb.setCharAt(i+1, 'R');
changed=true;
step.add(i+1);
tot++;
i++;
}
}
if (changed && m>=k){
failed=true;
break;
}
if (changed)arr[m] = step;
m++;
}
m--;
if (failed || tot<k){
out.write("-1".getBytes());
out.flush();
continue;
}
/*LRRLRLRLRLLLLRRLLLRRLRRLRRLLLLRRLLRRLLLLLLLRLRRRLLLRRLRLLRL
for (int i=0;i<m;i++){
int rem = m-i-1;
int cur = Math.min(k-rem, arr[i].size());
for (int j=0;j<cur-1;j++){
System.out.println(1 + " " + arr[i].get(j));
}
System.out.print(arr[i].size()-(cur-1));
for (int j=cur-1;j<arr[i].size();j++){
System.out.print(" " + arr[i].get(j));
}
System.out.println();
k-=cur;
}
*/
m = 0;
int ind = 0;
while (k != 0) {
if (tot == k) {
out.write((1 + " " + arr[m].get(ind) + "\n").getBytes());
ind++;
tot--;
k--;
} else {
long min = Math.min(arr[m].size(), tot - k + 1);
out.write((min+"").getBytes());
for (int i = 0; i < min; i++) {
out.write((" " + arr[m].get(ind)).getBytes());
ind++;
tot--;
}
out.write("\n".getBytes());
k--;
}
if (ind>=arr[m].size()){
ind=0;
m++;
}
}
out.flush();
}
}
}
/*
6 3
3 1 3 5
1 3 4
tot=5
k=3
*/
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 07b5fd4525736fcbc8d7b0c9798327b7 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
static void main() throws Exception {
int n = sc.nextInt();
int k = sc.nextInt();
String c = sc.nextLine();
StringBuilder sb = new StringBuilder(c);
boolean changed = true;
List<Integer>[] arr = new ArrayList[k];
int m = 0;
boolean failed = false;
long tot = 0;
while (changed) {
List<Integer> step = new ArrayList<>();
changed = false;
for (int i = 0; i < n - 1; i++) {
if (sb.charAt(i) == 'R' && sb.charAt(i + 1) == 'L') {
sb.setCharAt(i, 'L');
sb.setCharAt(i + 1, 'R');
changed = true;
step.add(i + 1);
tot++;
i++;
}
}
if (changed && m >= k) {
failed = true;
break;
}
if (changed)
arr[m] = step;
m++;
}
m--;
if (failed || tot < k) {
pw.println(-1);
return;
}
m = 0;
int ind = 0;
while (k != 0) {
if (tot == k) {
pw.println((1 + " " + arr[m].get(ind) + "\n"));
ind++;
tot--;
k--;
} else {
long min = Math.min(arr[m].size(), tot - k + 1);
pw.print((min + ""));
for (int i = 0; i < min; i++) {
pw.print((" " + arr[m].get(ind)));
ind++;
tot--;
}
pw.println();
k--;
}
if (ind >= arr[m].size()) {
ind = 0;
m++;
}
}
}
static PrintWriter pw;
static MScanner sc;
public static void main(String[] args) throws Exception {
pw = new PrintWriter(System.out);
sc = new MScanner(System.in);
// int tests =sc.nextInt();
int tests = 1;
while (tests-- > 0)main();
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[] 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;
}
}
}
/*
*
* 6 3 3 1 3 5 1 3 4
*
* tot=5 k=3
*/
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 0ab3e9c7bfd9b6ccf1cc8cdc593f711a | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin (t.me/musin_acm)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DDosugVShkole41 solver = new DDosugVShkole41();
solver.solve(1, in, out);
out.close();
}
static class DDosugVShkole41 {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int k = in.readInt();
int[] a = parse(in.next().toCharArray());
List<List<Integer>> swaps = new ArrayList<>();
while (true) {
List<Integer> curSwaps = new ArrayList<>();
for (int i = 0; i + 1 < n; i++) {
if (a[i] == 1 && a[i + 1] == 0) curSwaps.add(i);
}
if (curSwaps.isEmpty()) break;
swaps.add(curSwaps);
for (int i : curSwaps) {
a[i] ^= 1;
a[i + 1] ^= 1;
}
}
int totalSize = 0;
for (var list : swaps) totalSize += list.size();
if (!(swaps.size() <= k && k <= totalSize)) {
out.print(-1);
return;
}
int extra = k - swaps.size();
List<List<Integer>> answer = new ArrayList<>();
for (var list : swaps) {
int start = 0;
while (list.size() - start > 1 && extra > 0) {
answer.add(Collections.singletonList(list.get(start)));
start++;
extra--;
}
answer.add(list.subList(start, list.size()));
}
for (var list : answer) {
out.print(list.size());
for (int x : list) out.print(" " + (x + 1));
out.printLine();
}
}
int[] parse(char[] s) {
int n = s.length;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = s[i] == 'L' ? 0 : 1;
return a;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine() {
writer.println();
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | ff3827b5055b57fb06c30456e698cc81 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public final static int RIGHT = 1;
public final static int LEFT = -1;
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(System.in);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.nextInt();
int k = in.nextInt();
int[] dir = new int[n];
String str = in.next();
for (int i = 0; i < n; i++) {
dir[i] = str.charAt(i) == 'R' ? RIGHT : LEFT;
}
int total = 0;
ArrayList<Queue<Integer>> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
list.add(i, new LinkedList<>());
for (int j = 0; j < n - 1; j++) {
if (dir[j] == RIGHT && dir[j + 1] == LEFT) {
list.get(i).add(j + 1);
dir[j] = LEFT;
dir[j + 1] = RIGHT;
total++;
j++;
}
}
if (list.get(i).size() == 0) {
list.remove(i);
break;
}
}
if (total < k || list.size() > k) {
out.write("-1");
} else {
int time;
for (time = 0; time < list.size() && total > k - time; ) {
int a = 0;
if (total - list.get(time).size() >= k - time) {
out.write("" + list.get(time).size());
a = 1;
} else {
out.write("" + (total - k + time + 1));
}
while (!list.get(time).isEmpty() && total >= k - time) {
out.write(" " + list.get(time).poll());
total--;
}
time += a;
out.write("\n");
}
while (time < list.size()) {
while (!list.get(time).isEmpty()) {
out.write("1 " + list.get(time).poll() + "\n");
}
time++;
}
}
out.flush();
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | e2f9179430e2c2d5159303be2f8e38a7 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private void swap(char[] a, int i, int j) {
char tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
private void solve() {
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.next();
char[] a = s.toCharArray();
int total = 0;
int last = n - 1;
for (int i = n - 1; i >= 0; i--) {
if (a[i] == 'R') {
total += last - i;
--last;
}
}
if (total < k) {
out.println(-1);
return;
}
Queue<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n - 1; i++) {
if (a[i] == 'R' && a[i + 1] == 'L') {
q.add(i);
}
}
List<Integer> next = new ArrayList<>();
List<Integer> move = new ArrayList<>();
List<Integer> ans = new ArrayList<>();
while (k > 0) {
next.clear();
move.clear();
while (!q.isEmpty() && total >= k) {
int u = q.poll();
move.add(u);
swap(a, u, u + 1);
if (u + 2 < n && a[u + 2] == 'L') {
next.add(u + 1);
}
if (u - 1 >= 0 && a[u - 1] == 'R') {
next.add(u - 1);
}
--total;
}
--k;
ans.add(move.size());
ans.addAll(move);
q.addAll(next);
}
if (total != k) {
out.println(-1);
} else {
int i = 0;
while (i < ans.size()) {
int ni = ans.get(i++);
out.print(ni);
for (int j = 0; j < ni; ++j) {
out.print(' ');
out.print(ans.get(i++) + 1);
}
out.println();
}
}
}
private static PrintWriter out;
private static MyScanner sc;
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new MyScanner();
new Main().solve();
out.close();
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | e738cc46570a3572624d2e12b7d1bc92 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes |
import java.io.*;
import java.util.*;
public class D{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
String s = st.nextToken();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
if(s.charAt(i) == 'R') {
a[i] = 1;
}else {
a[i] = 0;
}
}
ArrayList<Integer> positions = new ArrayList<Integer>();
ArrayList<Integer> levels = new ArrayList<Integer>();
boolean has = true;
while(has) {
int prev = 0;
int ctr = 0;
for(int i = 0; i < n; i++) {
if(prev == 1 && a[i] == 0) {
ctr++;
positions.add(i-1);
a[i] = 1;
a[i-1] = 0;
prev = 0;
}else {
prev = a[i];
}
}
if(ctr == 0) {
has = false;
}else {
levels.add(ctr);
}
}
if(positions.size() < k || levels.size() > k) {
pw.println(-1);
}else {
int posCt = 0;
int levelSum = levels.get(0);
int levelCt = 1;
int levelPos = 0;
int offset = k - levels.size();
while(offset != 0) {
pw.println(1 + " " + (positions.get(posCt)+1));
posCt++;
levelPos++;
offset--;
if(levelPos == levelSum) {
offset++;
levelSum = levels.get(levelCt);
levelPos = 0;
levelCt++;
}
}
while(posCt != positions.size()) {
pw.print(levelSum - levelPos);
for(int i = 0; i < levelSum - levelPos; i++) {
pw.print(" " + (positions.get(posCt)+1));
posCt++;
}
if(posCt == positions.size()) {
break;
}
levelSum = levels.get(levelCt);
levelCt++;
levelPos = 0;
pw.println();
}
}
pw.flush();
}
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 1607f947bf9b5d822a6f2bac2e006d90 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
boolean multiple = false;
long MOD;
@SuppressWarnings({"Duplicates", "ConstantConditions"})
void solve() throws Exception
{
int n = sc.nextInt();
int k = sc.nextInt();
String s = sc.nextToken();
boolean[] arr = new boolean[n], orig = new boolean[n];
for (int i = 0; i < n; i++)
orig[i] = (arr[i] = s.charAt(i) == 'R');
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
int tot = 0;
while (true)
{
ArrayList<Integer> curr = new ArrayList<>();
for (int i = 0; i < n - 1; i++)
if (arr[i] && !arr[i + 1])
{
arr[i] = false;
arr[i + 1] = true;
curr.add(i + 1);
i++;
}
if (curr.isEmpty()) break;
ans.add(curr);
tot += curr.size();
}
// System.out.println(ans);
if (k > tot || k < ans.size()) pl(-1);
else
{
int extra = k - ans.size();
for (ArrayList<Integer> an : ans)
{
int start = 0;
while (start < an.size() - 1 && extra > 0)
{
extra--;
pl(1 + " " + an.get(start));
start++;
}
if (start != an.size())
{
p(an.size() - start);
for (int i = start; i < an.size(); i++)
p(" " + an.get(i));
pl();
}
}
}
}
void process(ArrayList<Integer> ans )
{
p(ans.size());
for (Integer val : ans)
p(" " + val);
pl();
}
StringBuilder ANS = new StringBuilder();
void p(Object s) { ANS.append(s); } void p(double s) {ANS.append(s); } void p(long s) {ANS.append(s); } void p(char s) {ANS.append(s); }
void pl(Object s) { ANS.append(s); ANS.append('\n'); } void pl(double s) { ANS.append(s); ANS.append('\n'); } void pl(long s) { ANS.append(s); ANS.append('\n'); } void pl(char s) { ANS.append(s); ANS.append('\n'); } void pl() { ANS.append(('\n')); }
/*I/O, and other boilerplate*/ @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);sc = new FastScanner(in);if (multiple) { int q = sc.nextInt();for (int i = 0; i < q; i++) solve(); } else solve(); System.out.print(ANS); } catch (Throwable uncaught) { Main.uncaught = uncaught; } finally { out.close(); }} public static void main(String[] args) throws Throwable{ Thread thread = new Thread(null, new Main(), "", (1 << 26));thread.start();thread.join();if (Main.uncaught != null) {throw Main.uncaught;} } static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out; } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) {this.in = in;}public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); }return st.nextToken(); }public int nextInt() throws Exception { return Integer.parseInt(nextToken()); }public long nextLong() throws Exception { return Long.parseLong(nextToken()); }public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); }
} | Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 8532bc890cfe34b30d1b2f2aecbcb954 | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) {
var scanner = new BufferedScanner();
var writer = new PrintWriter(new BufferedOutputStream(System.out, 32768));
// 10 10 LLRRLRLRLL
var n = scanner.nextInt();
var k = scanner.nextInt();
var s = scanner.next().toCharArray();
// var n = 3000;
// var k = 1000000;
// var s = new char[n];
// for (int i = 0; i < n; i++) {
// if (Math.random() > 0.5) {
// s[i] = 'L';
// } else {
// s[i] = 'R';
// }
// }
// for (int i = 0; i < n / 2; i++) {
// s[i] = 'R';
// }
// for (int i = n / 2; i < n; i++) {
// s[i] = 'L';
// }
assert debug(new String(s));
var t = System.nanoTime();
var tt = System.nanoTime();
// 最终,LL...LL,RR...RR,LL...LLRR...RR
// 转头不改变L和R的数量,相当于L和R互换位置
// RLRL->LRLR->LLRR
// 左边的L往左边走了,右边的才能继续往左边走
// 求最大步数,如果大于等于k就有戏
var moves = new ArrayList<Integer>();
var ls = new ArrayList<L>();
{
var r = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] == 'R') {
r++;
} else {
ls.add(new L(i, r));
r = 0;
}
}
}
var ls2 = ls.toArray(new L[0]);
assert debug("ls time:%.2f", (System.nanoTime() - t) / 1e9);
t = System.nanoTime();
var range = new int[]{0, ls.size() - 1};
while (true) {
var all = allLAfterR2(ls, ls2, range);
// var all = allLAfterR(s);
// assert all.equals(allLAfterR(s));
// assert debug("all size:%d", all.size());
if (all.size() == 0) {
break;
}
moves.addAll(all);
// for (Integer i : all) {
// moves.add((i - 1) + 1);
// if (s[i - 1] != 'R') {
// throw new RuntimeException("wtf");
// }
// if (s[i] != 'L') {
// throw new RuntimeException("wtf");
// }
// assert s[i - 1] == 'R' && s[i] == 'L';
// swap(s, i - 1, i);
// }
}
assert debug("moves.size:%d", moves.size());
assert debug("moves loop:%d", totalAllAfterR2);
assert debug("moves inner loop:%d", totalAllAfterR2Loop);
assert debug("moves time:%.2f", (System.nanoTime() - t) / 1e9);
t = System.nanoTime();
// assert firstLAfterR(s) < 0;
if (moves.size() < k) {
writer.println(-1);
} else {
// var groups = group(moves, k);
// assert groups.size() == k;
var groups2 = group2(moves, k);
assert groups2 == null || groups2.length == k;
assert debug("group time:%.2f", (System.nanoTime() - t) / 1e9);
t = System.nanoTime();
// assert false;
// for (List<Integer> group : groups) {
// writer.print(group.size());
// writer.print(" ");
// for (Integer each : group) {
// writer.print(each);
// writer.print(" ");
// }
// writer.println();
// }
if (groups2 == null) {
writer.println(-1);
} else {
for (int[] group : groups2) {
writer.print(group.length);
writer.print(' ');
for (int x : group) {
writer.print(x);
writer.print(' ');
}
writer.println();
}
}
assert debug("output time:%.2f", (System.nanoTime() - t) / 1e9);
}
assert debug("total time:%.2f", (System.nanoTime() - t) / 1e9);
// assert false;
scanner.close();
writer.flush();
writer.close();
}
static boolean debug(String fmt, Object... args) {
System.out.println(String.format(fmt, args));
return true;
}
static int totalAllAfterR2 = 0;
static int totalAllAfterR2Loop = 0;
static int totalTime1, totalTime2;
private static List<Integer> allLAfterR2(List<L> ls, L[] ls2, int[] range) {
// assert debug("range(%d,%d)", range[0], range[1]);
totalAllAfterR2++;
var ans = new ArrayList<Integer>();
// while (ls.peek() != null && ls.peek().preR == 0) {
// ls.poll();
// }
// var it = ls.iterator();
// while (it.hasNext() && it.next().preR == 0) {
// it.remove();
// }
// var first = IntStream.range(0, ls.size())
// .filter(i -> ls.get(i).preR > 0)
// .findFirst()
// .orElse(-1);
// if (first < 0) {
// return List.of();
// }
// var newLs = new ArrayList<L>();
// while (range[0] < ls.size() && ls.get(range[0]).preR == 0) {
while (range[0] < ls2.length && ls2[range[0]].preR == 0) {
range[0]++;
}
var prevI = -999;
// var i = -1;
// for (var x : ls) {
var newEnd = range[0];
for (var i = range[0]; i <= range[1]; i++) {
totalAllAfterR2Loop++;
// L x = ls.get(i);
L x = ls2[i];
// newLs.add(x);
// i++;
var plusR = prevI + 1 == i;
if (x.preR > 0) {
ans.add(x.pos);
x.preR--;
x.pos--;
prevI = i;
}
if (plusR) {
x.preR++;
}
if (x.preR > 0) {
newEnd = i;
}
}
range[1] = Math.min(newEnd + 1, ls2.length - 1);
// ls.clear();
// ls.addAll(newLs);
return ans;
}
static class L {
int pos;
int preR;
public L(int i, int r) {
pos = i;
preR = r;
}
}
private static List<Integer> allLAfterR(char[] s) {
// System.out.println("woohoo");
var ans = new ArrayList<Integer>();
var foundR = false;
var prev = -1;
for (int i = 0; i < s.length; i++) {
if (s[i] == 'R') {
foundR = true;
} else {
if (foundR) {
if (i > prev + 1) {
ans.add(i);
prev = i;
}
foundR = false;
}
}
}
return ans;
}
private static List<List<Integer>> group(List<Integer> moves, int k) {
var work = new LinkedList<>(moves);
var ans = new ArrayList<List<Integer>>();
while (ans.size() < k) {
var batch = new ArrayList<Integer>();
ans.add(batch);
var prev = -1;
var it = work.iterator();
var atMost = work.size() - (k - ans.size());
while (it.hasNext() && batch.size() < atMost) {
var next = it.next();
if (next > prev + 1) {
batch.add(next);
it.remove();
prev = next;
} else if (next <= prev) {
break;
}
}
}
// if (moves.size() > 0) {
// throw new RuntimeException("wtf");
// }
assert work.size() == 0;
return ans;
}
private static int[][] group2(List<Integer> moves, int k) {
var work = new LinkedList<>(moves);
var ans = new int[k][];
var batch = new ArrayList<Integer>();
for (var i = 0; i < k; i++) {
batch.clear();
var prev = -1;
var it = work.iterator();
var atMost = work.size() - (k - i - 1);
while (it.hasNext() && batch.size() < atMost) {
var next = it.next();
if (next > prev + 1) {
batch.add(next);
it.remove();
prev = next;
} else if (next <= prev) {
break;
}
}
ans[i] = batch.stream().mapToInt(x -> x).toArray();
}
// if (moves.size() > 0) {
// throw new RuntimeException("wtf");
// }
// assert work.size() == 0;
// return ans;
return work.size() == 0 ? ans : null;
}
private static int firstLAfterR(char[] s) {
var foundR = false;
for (int i = 0; i < s.length; i++) {
if (s[i] == 'R') {
foundR = true;
} else {
if (foundR) {
return i;
}
}
}
return -1;
}
static void swap(char[] s, int i, int j) {
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
public static class BufferedScanner {
BufferedReader br;
StringTokenizer st;
public BufferedScanner(Reader reader) {
br = new BufferedReader(reader);
}
public BufferedScanner() {
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 nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b > 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static long inverse(long a, long m) {
long[] ans = extgcd(a, m);
return ans[0] == 1 ? (ans[1] + m) % m : -1;
}
private static long[] extgcd(long a, long m) {
if (m == 0) {
return new long[]{a, 1, 0};
} else {
long[] ans = extgcd(m, a % m);
long tmp = ans[1];
ans[1] = ans[2];
ans[2] = tmp;
ans[2] -= ans[1] * (a / m);
return ans;
}
}
private static List<Integer> primes(double upperBound) {
var limit = (int) Math.sqrt(upperBound);
var isComposite = new boolean[limit + 1];
var primes = new ArrayList<Integer>();
for (int i = 2; i <= limit; i++) {
if (isComposite[i]) {
continue;
}
primes.add(i);
int j = i + i;
while (j <= limit) {
isComposite[j] = true;
j += i;
}
}
return primes;
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | 200f83a1647dafd416afa1938b7ae8fc | train_000.jsonl | 1586356500 | There are $$$n$$$ children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number $$$n$$$, the initial arrangement of children and the number $$$k$$$. You have to find a way for the children to act if they want to finish the process in exactly $$$k$$$ seconds. More formally, for each of the $$$k$$$ moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and $$$k = 2$$$ children can do the following steps: At the beginning, two pairs make move: $$$(1, 2)$$$ and $$$(3, 4)$$$. After that, we receive the following configuration: At the second move pair $$$(2, 3)$$$ makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than $$$n^2$$$ "headturns". | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DChallengesInSchool41 solver = new DChallengesInSchool41();
solver.solve(1, in, out);
out.close();
}
static class DChallengesInSchool41 {
public void solve(int testNumber, FastReader s, PrintWriter out) {
int n = s.nextInt(), K = s.nextInt();
char[] arr = s.nextString().toCharArray();
List<List<Integer>> route = new ArrayList<>();
int all = 0;
for (; ; ) {
List<Integer> lr = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
if (arr[i] == 'R' && arr[i + 1] == 'L') {
lr.add(i);
}
}
if (lr.size() == 0) break;
all += lr.size();
for (int t : lr) {
arr[t] = 'L';
arr[t + 1] = 'R';
}
route.add(lr);
}
if (K < route.size() || K > all) {
out.println(-1);
return;
}
K -= route.size();
for (int i = 0; i < route.size(); i++) {
int j = 0;
for (; j < route.get(i).size() - 1 && K > 0; j++) {
out.print(1 + " ");
out.println(route.get(i).get(j) + 1);
K--;
}
out.print((route.get(i).size() - j));
for (; j < route.get(i).size(); j++) {
out.print(" " + (route.get(i).get(j) + 1));
}
out.println();
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["2 1\nRL", "2 1\nLR", "4 2\nRLRL"] | 2 seconds | ["1 1", "-1", "2 1 3 \n1 2"] | NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in $$$k>0$$$ moves.The third configuration is described in the statement. | Java 11 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"games",
"implementation",
"sortings",
"brute force"
] | dfe0f5da0cb90706f33365009d9baf5b | The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 3000$$$, $$$1 \le k \le 3000000$$$) — the number of children and required number of moves. The next line contains a string of length $$$n$$$ and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. | 2,100 | If there is no solution, print a single line with number $$$-1$$$. Otherwise, output $$$k$$$ lines. Each line has to start with a number $$$n_i$$$ ($$$1\le n_i \le \frac{n}{2}$$$) — the number of pairs of children, who turn at this move. After that print $$$n_i$$$ distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. | standard output | |
PASSED | c3f2b110d707508000ac7d76c53c8267 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class D implements Runnable {
boolean judge = false;
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
char[] arr = scn.next().toCharArray();
long ans = n * 1L * (n - 1) / 2 - 2 * n;
for(int i = 1; i < n; i++) {
if(arr[i] != arr[i - 1]) {
ans++;
}
}
int x = 1;
for(int i = 1; i < n; i++) {
if(arr[i] == arr[i - 1]) {
x++;
} else {
ans += x;
x = 0;
break;
}
}
ans += x;
x = 1;
for(int i = n - 2; i >= 0; i--) {
if(arr[i] == arr[i + 1]) {
x++;
} else {
ans += x;
x = 0;
break;
}
}
ans += x;
out.println(ans);
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null || judge;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new D(), "Main", 1 << 26).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | c8da0c509886c38fa229a382b87ea580 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | // package Quarantine;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ABSubstring {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String str=br.readLine();
long tot=(1l*n*(n-1))/2;
int dp[]=new int[n];
dp[n-1]=1;
boolean flag=true;
for(int i=n-2;i>=0;i--){
if(str.charAt(i)==str.charAt(i+1)){
dp[i]=dp[i+1]+1;
if(!flag){
tot-=1;
}
}
else{
flag=false;
dp[i]=1;
tot-=dp[i+1];
}
// System.out.println(tot);
}
System.out.println(tot);
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 3577fb59d406ee05598e7f7aaf7742ad | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
ArrayList<Integer> res=new ArrayList<>();
char[] a=scan.next().toCharArray();
int streak=0, prev=-1;
for(int i=0;i<n;i++) {
if(prev==a[i]||prev==-1) streak++;
else {
res.add(streak);
streak=1;
}
prev=a[i];
}
res.add(streak);
long fin=(long)n*(n-1)/2;
for(int i=0;i<res.size()-1;i++) {
fin-=(res.get(i)+res.get(i+1)-1);
}
System.out.println(fin);
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 0a28669ef3394cb22f52ddee75846f1a | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | //package cfed74;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class G {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
int n = sc.nextInt();
char[] s = sc.nextLine().toCharArray();
long ans = (long) n * (long) (n + 1) / 2;
int[] last = new int[]{-1, -1};
long[] max = new long[n], min = new long[n];
for(int i = 0; i < n; i++) {
if(last[1 - s[i] + 'A'] != -1)
max[last[1 - s[i] + 'A']] = i - last[1 - s[i] + 'A'];
last[s[i] - 'A'] = i;
}
last = new int[]{-1, -1};
for(int i = n - 1; i >= 0; i--) {
if(last[1 - s[i] + 'A'] != -1)
min[last[1 - s[i] + 'A']] = last[1 - s[i] + 'A'] - i;
last[s[i] - 'A'] = i;
}
for(int i = 0; i < n; i++) {
ans -= min[i] + max[i] + 1;
if(max[i] > 0)
ans++;
}
out.println(ans);
out.close();
}
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static class MyScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreElements())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 1a817a59b665638ed5a85c7538356420 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prem_cse
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(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, FastReader sc, PrintWriter out) {
long n = sc.nextLong();
char[] s = sc.next().toCharArray();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; ) {
int j = i;
while (j < n && s[i] == s[j]) ++j;
list.add(j - i);
i = j;
}
long ans = (n * (n - 1)) / 2;
for (int i = 0; i + 1 < list.size(); ++i) {
// whole A then B + whole B then A
ans -= list.get(i) + list.get(i + 1) - 1;
}
out.println(ans);
}
}
static class FastReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastReader(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());
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 1655e71d3082ea1f8814e054b3975ae9 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class cfd {
static DataReader input;
static int LARGE_INT = 1000000007;
//static int MAXN = 300000;
//static int[] len = new int[300000];
//static int[] price = new int[300000];
public static void main(String[] args) throws IOException {
input = new DataReader();
PrintWriter out = new PrintWriter(System.out);
int N = nextInt();
String x = nextStr();
char ch = x.charAt(0);
int k = 0, c = 1;
int[] seq = new int[N];
for (int i=1; i<N; i++) {
char chn = x.charAt(i) ;
if (ch == chn) {
c++;
} else {
seq[k++] = c;
ch = chn;
c = 1;
}
}
seq[k++] = c;
//out.println("K=" + k + Arrays.toString(seq));
long ans = N;
ans = ans * (N-1) / 2;
for (int i=0; i<k-1; i++) {
//out.println("i=" + i +", ans=" + ans);
ans -= (seq[i] - 1); // "aab" doesn't work
ans -= seq[i+1]; // "ab", "abb", "abbb" don't work
}
out.println(ans);
out.flush();
out.close();
}
static int nextInt() throws IOException {
return Integer.parseInt(input.next());
}
static String nextStr() throws IOException {
return input.next();
}
static class DataReader {
BufferedReader br;
StringTokenizer st;
public DataReader() throws IOException { // reading from standard in
br = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext() throws IOException {
while (st == null || !st.hasMoreElements()) {
String line = br.readLine();
if (line == null) { // end of file
return false;
}
st = new StringTokenizer(line);
}
return true;
}
String next() throws IOException {
if (hasNext())
return st.nextToken();
else
return null;
}
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 63105d2d287a6c1a3ee5fb9213fd5783 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Contest1 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
char[]s=sc.nextLine().toCharArray();
TreeSet<Integer>as=new TreeSet<>();
TreeSet<Integer>bs=new TreeSet<>();
for (int i =0;i<n;i++){
if (s[i]=='A')as.add(i);
else bs.add(i);
}
long ans=0;
for (int i =0;i<n-1;i++){
if (s[i]=='A'){
if (s[i+1]=='A'){
ans+=n-i-1;
if (bs.ceiling(i+1)!=null){
ans--;
}
}
else {
Integer mat=as.ceiling(i+1);
if (mat==null)continue;
ans+=n-mat;
}
}
else {
if (s[i+1]=='B'){
ans+=n-i-1;
if (as.ceiling(i+1)!=null){
ans--;
}
}
else {
Integer mat=bs.ceiling(i+1);
if (mat==null)continue;
ans+=n-mat;
}
}
// pw.println(ans);
}
pw.println(ans);
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
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\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | eb3e8ee5a01090319e64ffce337fe14c | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes |
import java.util.Scanner;
import static java.lang.Math.max;
public class D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
int pra[] = new int[n];
int prb[] = new int[n];
int ta = n;
int tb = n;
for (int i = n - 1; i >= 0; i--) {
pra[i] = ta;
prb[i] = tb;
if (s.charAt(i) == 'A') ta = i;
else tb = i;
}
long ans = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == 'A') {
if (pra[i] > prb[i] || prb[i] == n) {
ans += (long) (n - pra[i]);
} else {
ans += (long) (max(n - pra[i] - 1, 0));
}
} else {
if (prb[i] > pra[i] || pra[i] == n) {
ans += (long) (n - prb[i]);
} else {
ans += (long) (max(n - prb[i] - 1, 0));
}
}
}
System.out.println(ans);
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | d205ff641908e073e2ea8aa78a3b8956 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | /**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main
{
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 n = ni();
char c[] = ne().toCharArray();
int A = n, B = n;
int nextA[] = new int[n], nextB[] = new int[n];
for(int i=n-1;i>=0;--i) {
nextA[i] = A;
nextB[i] = B;
if(c[i]=='A') {
A = i;
}
else {
B = i;
}
}
long invalid = 0;
for(int i=n-1;i>=0;--i) {
invalid+=1;
if(c[i]=='A') {
if(i+1<n && c[i+1] !='A') {
invalid+=(nextA[i] - i - 1);
}
}
if(c[i]=='B') {
if(i+1<n && c[i+1]!='B') {
invalid+=(nextB[i] - i - 1);
}
}
}
A = -1;
B = -1;
int prevA[] = new int[n];
int prevB[] = new int[n];
for(int i=0;i<n;++i) {
prevA[i] = A;
prevB[i] = B;
if(c[i]=='A') {
A = i;
}
else {
B = i;
}
}
for(int i=0;i<n;++i) {
if(i>0 && c[i-1]!=c[i]) {
if(c[i]=='A') {
invalid+=(i-prevA[i]-2);
}
else {
invalid+=(i-prevB[i]-2);
}
}
}
long total = 1L * (n) * (n+1);
total/=2;
pl(total-invalid);
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 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 | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 1a2ae61e93b2cd730e406cc2db8c5036 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.PriorityQueue;
public class codeforces {
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// The next two void functions are shuffle functions on an array.
// This way, quick sort encounters the worst case scenario with low probability.
// A reason for doing this is if we don't a primitive data array to an object array.
// For safety reasons, it would be preferable to use object arrays unless doing so expends a lot of time.
public static void shuffleLongArray(long[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i=0; i < n; i++) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static void shuffleIntArray(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i=0; i < n; i++) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public static void main (String[] args) throws IOException {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// Write your solution here.
int n = sc.nextInt(); long m = (long) n;
String str = sc.next();
// the ones that don't work will be A's followed by B's or vice versa
long total = m*(m-1)/2;
ArrayList<Integer> places = new ArrayList<Integer>();
int counter = 0;
for (int i=0; i < n; i++) {
if (i==0) {
counter++; continue;
}
if (str.charAt(i)==str.charAt(i-1)) counter++;
else {
places.add(counter);
counter = 1;
}
}
places.add(counter); // for the last letter
for (int i=0; i < places.size()-1; i++) {
total = total - (places.get(i)+places.get(i+1)-1);
}
out.print(total);
out.close();
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | da7c1fab5c422a0626cca51c4ab520b0 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int inf = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int n = nextInt();
char h[] = next().toCharArray();
int cnt[][] = new int [2][n];
cnt[h[0] - 'A'][0] = 1;
for(int i = 1;i < n;i++) {
cnt[0][i] = cnt[0][i - 1];
cnt[1][i] = cnt[1][i - 1];
cnt[h[i] - 'A'][i]++;
}
long ans = 0;
for(int i = 0;i < n - 1;i++) {
if (h[i] == h[i + 1]) {
ans += n - i - 2;
if (cnt[1 - (h[i] - 'A')][n - 1] == cnt[1 - (h[i] - 'A')][i]) ans++;
}else{
int l = -1;
int r = n;
while(r - l > 1) {
int m =((l + r) >> 1);
if (cnt[h[i] - 'A'][m] > cnt[h[i] - 'A'][i]) r = m;
else l = m;
}
ans += Math.min(n - i - 2, n - r);
}
}
pw.println(ans);
pw.close();
}
static BufferedReader br;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter pw;
static String next() throws IOException {
while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 47c41ecceb19ce000717afbefb33df4b | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.*;
public class CFContest {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = true;
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) 1e9;
long lInf = (long) 1e18;
double dInf = 1e50;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
public void solve() {
int n = io.readInt();
int[] s = new int[n + 1];
for (int i = 1; i <= n; i++) {
s[i] = io.readChar() == 'A' ? 0 : 1;
}
long ans = 0;
int[][] cnts = new int[n + 1][2];
int[] reg = new int[2];
int[] next = new int[n + 1];
reg[s[n]] = n;
for (int i = n - 1; i >= 1; i--) {
cnts[i][0] = cnts[i + 1][0];
cnts[i][1] = cnts[i + 1][1];
cnts[i][s[i + 1]]++;
next[i] = reg[s[i]];
reg[s[i]] = i;
}
for (int i = 1; i <= n; i++) {
if (next[i] == 0) {
continue;
}
if (next[i] == i + 1) {
ans += cnts[i][s[i]] + Math.max(cnts[i][1 - s[i]] - 1, 0);
} else {
ans += cnts[i][s[i]] + cnts[next[i]][1 - s[i]];
}
}
io.cache.append(ans);
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder(20 << 20);
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 << 20];
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() {
try {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
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 | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 2febd6d5dab311f2d918267fe0bb4d26 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
private void run() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
String s = reader.readLine();
int bad = 0, curr = 1;
for (int i = 1; i < n; i++) {
if(s.charAt(i-1) != s.charAt(i)){
bad += curr;
curr = 1;
}else
curr++;
}
curr = 1;
for (int i = n-2; i >= 0; i--) {
if(s.charAt(i) != s.charAt(i+1)){
bad += curr - 1;
curr = 1;
}else
curr++;
}
System.out.println(((long)n*(n-1))/2 - bad);
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 2b9bd5887eb98fb10357b158f1a31b52 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class EDU74D2 {
public static void main(String[] args) {
JS scan = new JS();
int n =scan.nextInt();
String s= scan.next();
long ans = sum(n);
int[][] next = new int[n][2];
int[][] prior = new int[n][2];
for(int i = 0;i<n;i++) {
Arrays.fill(next[i], n);
Arrays.fill(prior[i], -1);
}
int lastA = -1;
int lastB = -1;
for(int i = 0;i<s.length();i++) {
if(s.charAt(i)=='A') {
if(lastA == -1) {
lastA = i;
prior[i][1] =lastB;
continue;
}
prior[i][0] = lastA;
//System.out.println(i+" "+lastA);
prior[i][1] =lastB;
lastA = i;
}else {
if(lastB == -1) {
lastB = i;
prior[i][0] = lastA;
continue;
}
prior[i][1] = lastB;
prior[i][0] = lastA;
//System.out.println(i+" "+lastA);
lastB = i;
}
}
lastA = n;
lastB = n;
for(int i = n-1;i>=0;i--) {
if(s.charAt(i)=='A') {
if(lastA == n) {
lastA = i;
next[i][1] = lastB;
continue;
}
next[i][0] = lastA;
next[i][1] = lastB;
lastA = i;
}else {
if(lastB == -n) {
lastB = i;
next[i][0] = lastA;
continue;
}
next[i][1] = lastB;
next[i][0] = lastA;
lastB = i;
}
}
//System.out.println(ans);
boolean[] a = new boolean[n+1];
for(int i = 0;i<s.length()-1;i++) {
if(s.charAt(i) == s.charAt(i+1)) {
continue;
}
int to = 0;
if(s.charAt(i)=='B') {
to = next[i][1];
for(int j = i+1;j<=to;j++) {
a[j] = true;
}
i = to-2;
//ans-=(to-(i+1));
}
else {
to = next[i][0];
for(int j = i+1;j<=to;j++) {
a[j] = true;
}
i = to-2;
//ans-=(to-(i+1));
}
}
boolean[] b = new boolean[n+1];
for(int i = s.length()-1;i>0;i--) {
if(s.charAt(i) == s.charAt(i-1)) {
continue;
}
int to = 0;
if(s.charAt(i)=='B') {
to = prior[i][1];
//System.out.println(i+" "+to);
for(int j = i-1;j>=to;j--) {
if(j==-1)continue;
b[j] = true;
}
i = to+2;
//ans-=(to-(i+1));
}
else {
to = prior[i][0];
// System.out.println(i+" "+to);
for(int j = i-1;j>=to;j--) {
if(j==-1)continue;
b[j] = true;
}
i = to+2;
//ans-=(to-(i+1));
}
//System.out.println(i+" "+to);
}
for(int i = 0;i<n;i++) {
if(a[i])ans--;
if(b[i])ans--;
// if(a[i] || b[i]) {
// System.out.println(i+" "+a[i]+" "+b[i]);
// ans--;
// }
if(i<n-1)
if(s.charAt(i)!=s.charAt(i+1)) {
ans++;
}
}
System.out.println(ans);
}
static long sum(long n) {
return n*(n-1)/2;
}
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 | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 6e1937ef0f260f9bfaa377939a1dca79 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static int t,m,mod=998244353,maxn=1000000,q,n;
static long INF=(long)1e18,k;
void solve(PrintWriter out, Reader in) throws IOException{
n = in.nextInt();
String str = in.next();
long ans = ((long)n*(n-1))/2;
int prev= str.charAt(0),cnt=1,grp=0;
for(int i=1;i<str.length();i++){
if(str.charAt(i)!=prev){
if(grp==0) ans-=cnt;
else ans-=2*cnt;
cnt=1;
grp++;
}else{
cnt++;
}
prev = str.charAt(i);
}
if(grp!=0)ans-=cnt;
ans+=grp;
out.println(ans);
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Reader in = new Reader();
Main solver = new Main();
solver.solve(out, in);
out.flush();
out.close();
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | c861b3ebdd31919bdaa09f88e4fb4439 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public final class code
{
static void solve()throws IOException
{
int n=nextInt();
String s=nextLine();
ArrayList<Integer> list=new ArrayList<Integer>();
long ans=(long)n*(n-1)/2;
for(int i=0;i<n;)
{
int j=i;
while(j<n && s.charAt(i)==s.charAt(j))
j++;
list.add(j-i);
i=j;
}
for(int i=0;i<list.size()-1;i++)
{
ans-=list.get(i);
ans-=list.get(i+1);
ans+=1;
}
out.println(ans);
}
/////////////////////////////////////////////////////////
static BufferedReader br;
static StringTokenizer st;
static PrintWriter out;
static String nextToken()throws IOException
{
while(st==null || !st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
static String nextLine()throws IOException
{
return br.readLine();
}
static int nextInt()throws IOException
{
return Integer.parseInt(nextToken());
}
static long nextLong()throws IOException
{
return Long.parseLong(nextToken());
}
static double nextDouble()throws IOException
{
return Double.parseDouble(nextToken());
}
public static void main(String args[])throws IOException
{
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(new BufferedOutputStream(System.out));
solve();
out.close();
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | f0e554c6074adc9f7d6161b043cecbdf | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
import javafx.util.Pair;
public class Main {
static long MOD = 0;
static long[] fact = new long[1];
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
solve();
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static void solve() {
long t = in.nextInt();
ArrayList<Integer> runs = new ArrayList<>();
char[] s = in.next().toCharArray();
for (int i = 0; i < s.length; i++) {
if (i == 0 || s[i] != s[i - 1]) {
runs.add(0);
}
int ind = runs.size() - 1;
runs.set(ind, runs.get(ind) + 1);
}
long ans = t * (t - 1) / 2;
for (int i = 0; i + 1 < runs.size(); i++) {
ans -= runs.get(i) + runs.get(i + 1) - 1;
}
out.println(ans);
}
static int valuesGreaterThan(ArrayList<Integer> d, int v) {
int ind = Collections.binarySearch(d, v);
if (ind < 0) {
ind *= -1;
ind--;
} else {
ind++;
}
return d.size() - ind;
}
static <T> Pair<T, T> make_pair(T a, T b) {
return new Pair<>(a, b);
}
static class ModularArithmetic {
static long C(int n, int k) {
return divide(fact[n], mul(fact[k], fact[n - k]));
}
static void precalc(int N) {
fact = new long[N + 5];
fact[0] = 1;
for (int i = 1; i < N; i++)
fact[i] = mul(fact[i - 1], i);
}
static long inv(long x) {
return mod_pow(x, MOD - 2);
}
static long mul(long x, long y) {
return (x * y) % MOD;
}
static long divide(long x, long y) {
return mul(x, inv(y));
}
static long add(long x, long y) {
x += y;
while (x >= MOD)
x -= MOD;
while (x < 0)
x += MOD;
return x;
}
static long mod_pow(long x, long y) {
if (y == 0) {
return 1;
}
if (y == 1) {
return x;
}
long v = mod_pow(x, y / 2);
if ((y & 1) > 0) {
return v * v % MOD * x % MOD;
}
return v * v % MOD;
}
}
static class StringUtils {
static char[] constructReverseWithHash(String s) {
char[] a = s.toCharArray();
char[] b = ArrayUtils.reverse(s.toCharArray());
char[] c = new char[a.length + b.length + 1];
System.arraycopy(a, 0, c, 0, a.length);
c[a.length] = '#';
System.arraycopy(b, 0, c, a.length + 1, b.length);
return c;
}
static String reverse(String s) {
return constructStringFromChars(ArrayUtils.reverse(s.toCharArray()), 0, s.length());
}
static String constructStringFromChars(char[] d, int from, int to) {
StringBuilder res = new StringBuilder();
for (int i = from; i < to; i++) {
res.append(d[i]);
}
return res.toString();
}
static String constructStringFromInts(int[] d, int from, int to) {
StringBuilder res = new StringBuilder();
for (int i = from; i < to; i++) {
res.append(d[i]);
}
return res.toString();
}
static String constructStringFromInts(int[] d, int from, int to, char delim) {
StringBuilder res = new StringBuilder();
for (int i = from; i < to; i++) {
res.append(d[i]);
res.append(delim);
}
return res.toString();
}
static int[] prefix_function(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j]) {
j++;
}
pi[i] = j;
}
return pi;
}
}
static class NumberTheory {
static ArrayList<Integer>[] getDivisors(int n) {
ArrayList<Integer>[] d = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
d[i] = new ArrayList<>();
}
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j += i) {
d[j].add(i);
}
}
return d;
}
static long mod_pow(long x, long y, long MOD) {
if (y == 0) {
return 1;
}
if (y == 1) {
return x;
}
long v = mod_pow(x, y / 2, MOD);
if ((y & 1) > 0) {
return v * v % MOD * x % MOD;
}
return v * v % MOD;
}
static int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
//GCD Long
static long gcd(long a, long b) {
while (b != 0) {
long t = b;
b = a % b;
a = t;
}
return a;
}
}
static class ArrayUtils {
static int[] reverse(int[] data) {
int[] p = new int[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static char[] reverse(char[] data) {
char[] p = new char[data.length];
for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
p[i] = data[j];
}
return p;
}
static int[] MegreSort(int[] A) {
if (A.length > 1) {
int q = A.length / 2;
int[] left = new int[q];
int[] right = new int[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
int[] left_sorted = MegreSort(left);
int[] right_sorted = MegreSort(right);
return Megre(left_sorted, right_sorted);
} else {
return A;
}
}
static int[] Megre(int[] left, int[] right) {
int[] A = new int[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
static long[] MegreSort(long[] A) {
if (A.length > 1) {
int q = A.length / 2;
long[] left = new long[q];
long[] right = new long[A.length - q];
System.arraycopy(A, 0, left, 0, q);
System.arraycopy(A, q, right, 0, A.length - q);
long[] left_sorted = MegreSort(left);
long[] right_sorted = MegreSort(right);
return Megre(left_sorted, right_sorted);
} else {
return A;
}
}
static long[] Megre(long[] left, long[] right) {
long[] A = new long[left.length + right.length];
int i = 0;
int j = 0;
for (int k = 0; k < A.length; k++) {
// To handle left becoming empty
if (i == left.length && j < right.length) {
A[k] = right[j];
j++;
continue;
}
// To handle right becoming empty
if (j == right.length && i < left.length) {
A[k] = left[i];
i++;
continue;
}
if (left[i] <= right[j]) {
A[k] = left[i];
i++;
} else {
A[k] = right[j];
j++;
}
}
return A;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readAllInts(int n) {
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = in.nextInt();
}
return p;
}
public int[] readAllInts(int n, int s) {
int[] p = new int[n + s];
for (int i = s; i < n + s; i++) {
p[i] = in.nextInt();
}
return p;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 99d37d55b6c7977190867ef91ab73ab2 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.util.*;
public class terror{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n=in.nextInt();
in.nextLine();
String s= in.nextLine();
int lasta =n;
int lastb =n;
long val =0;
boolean a=false;
boolean b=false;
for(int i =s.length()-1;i>=0;i--)
{
if(s.charAt(i)=='A')
{
if(lastb<lasta||(b==false))
{
val = val+n-lasta;
}
else
{
val = val+n-lasta-1;
}
lasta=i;
a=true;
}
else
{
if(lasta<lastb||(a==false))
{
val= val+n-lastb;
}
else
val= val+n-lastb-1;
lastb=i;
b=true;
}
}
System.out.println(val);
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 5a58499508aae81eda7e15d203a92ccb | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
//import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static int MD= 998244353;
public static void main(String[] args) throws IOException {
OutputStream outputStream = System.out;
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
/*
* int[] a=new int[n];
* for(int i=0;i<n;i++){
* a[i]=in.nextInt()
*/
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException {
long n=in.nextLong();
String s=in.nextLine();
long ans=((n*(n+1))/2) - n;
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<n;) {
int j=i;
while(j<n && s.charAt(i)==s.charAt(j)) {
j++;
}
a.add(j-i);
i=j;
}
for(int i=0;i<a.size()-1;i++) {
ans=ans-a.get(i)-a.get(i+1)+1;
}
out.println(ans);
}
}
static class InputReader
{
BufferedReader br;
StringTokenizer st;
public InputReader()
{
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 void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 885b256f2e12254eb90ca87c5f115547 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class EdD {
public static void main(String[] args) throws Exception{
int num = 998244353;
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(bf.readLine());
String a = bf.readLine();
long curr = (long)(n)*(long)(n-1)/2;
ArrayList<Integer> temp = new ArrayList<Integer>();
int count = 1;
for(int j = 1;j<n;j++){
if (a.charAt(j) == a.charAt(j-1))
count++;
else{
temp.add(count);
count = 1;
}
}
temp.add(count);
long sub = 0;
for(int j = 0;j<temp.size()-1;j++){
sub+=(temp.get(j)+temp.get(j+1)-1);
}
out.println(curr-sub);
out.close();
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | c1ddc51c624b9992254a4b06865fa318 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Say My Name
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DABString solver = new DABString();
solver.solve(1, in, out);
out.close();
}
static class DABString {
public void solve(int testNumber, InputReader c, OutputWriter w) {
int n = c.readInt();
char a[] = c.readString().toCharArray();
ArrayList<Integer> arr = new ArrayList<>();
int ind = 0;
char ch = a[0];
while (ind < n) {
int cnt = 0;
while (ind < n && a[ind] == ch) {
cnt++;
ind++;
}
arr.add(cnt);
if (ind != n) {
ch = a[ind];
}
}
long res = n * (long) (n - 1) / 2;
for (int i = 1; i < arr.size(); i++) {
res -= arr.get(i - 1);
}
for (int i = 1; i < arr.size(); ++i) {
res -= arr.get(i) - 1;
}
w.printLine(res);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | f28b469cfd902d79b58accc001750c74 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol2{
public static void main(String[] args) throws IOException{
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
TreeSet<Long> idx = new TreeSet<>();
long n= sc.nextLong();
String str = sc.nextToken();
long arr[] = new long[(int)n];
for(int i=0; i<n; i++) {
arr[i]=str.charAt(i)-'A';
}
for(int i=1; i<n; i++) {
if(arr[i]!=arr[i-1])idx.add((long)i);
}
long tot = n*(n-1)/2;
long cnt = 0;
long curr = arr[0];
boolean twice = false;
for(int i=0; i<n; i++) {
if(i>0&&arr[i]!=arr[i-1]) {
if(idx.lower((long)i)==null) {
tot-=i;
}else {
tot-=i-(idx.lower((long)i));
}
}
if(i<n-1&&arr[i]!=arr[i+1]) {
if(idx.higher((long)i+1)==null) {
tot-=n-i-1;
}else {
tot-=idx.higher((long)i+1)-i-1;
}
}
//System.out.println(tot);
}
tot+=idx.size();
System.out.println(tot);
out.close();
}
public static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
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 | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | cd4d63a6c9b11ccb4e17fc1899255cb6 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | //package codeforces.educational74;
import java.io.*;
import java.util.*;
public class D {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
//solve(in.nextInt());
solve(1);
}
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
int n = in.nextInt();
String s = in.next();
long bad = n, cntA = 0, cntB = 0;
//AA...AB, BB....BA, BAA...A, ABB....B
//AAAAAB
for(int i = 0; i < n; i++) {
if(s.charAt(i) == 'B') {
bad += cntA;
cntA = 0;
}
else {
cntA++;
}
}
//BBBBBA
cntB = 0;
for(int i = 0; i < n; i++) {
if(s.charAt(i) == 'A') {
bad += cntB;
cntB = 0;
}
else {
cntB++;
}
}
//BAAAAA
cntA = 0;
for(int i = n - 1; i >= 0; i--) {
if(s.charAt(i) == 'B') {
bad += cntA;
cntA = 0;
}
else {
cntA++;
}
}
//ABBBB
cntB = 0;
for(int i = n - 1; i >= 0; i--) {
if(s.charAt(i) == 'A') {
bad += cntB;
cntB = 0;
}
else {
cntB++;
}
}
//AB and BA are counted twice
long cntAB = 0, cntBA = 0;
for(int i = 0; i < n - 1; i++) {
if(s.charAt(i) == 'A') {
if(s.charAt(i + 1) == 'B') {
cntAB++;
i++;
}
}
}
for(int i = 0; i < n - 1; i++) {
if(s.charAt(i) == 'B') {
if(s.charAt(i + 1) == 'A') {
cntBA++;
i++;
}
}
}
bad -= (cntAB + cntBA);
long good = (long)(n + 1) * n / 2 - bad;
out.println(good);
}
out.close();
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | b2cf93abb6c4927f4b788435a058623c | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
int testCases=1;//Integer.parseInt(br.readLine());
while(testCases-->0)
{
int n=Integer.parseInt(br.readLine());
char carr[]=br.readLine().toCharArray();
long ans=1L*n*(n-1)/2;
ArrayList<Integer> list=new ArrayList<>();
ArrayList<Integer> end=new ArrayList<>();
ArrayList<Integer> cnt=new ArrayList<>();
int last=0;
for(int i=0;i<n;i++)
{
list.add(i);
int j;
for(j=i+1;j<n;++j)
{
if(carr[i]!=carr[j])
break;
}
cnt.add(j-i);
end.add(j-1);
i=j-1;
}
if(list.size()>1)
{
for(int i=1;i<list.size();i++)
{
if(cnt.get(i)>1&&cnt.get(i-1)>1)
{
ans-=(list.get(i)-list.get(i-1));
ans-=(end.get(i)-end.get(i-1)-1);
}
else
{
if(cnt.get(i-1)==1)
ans-=(1L*(end.get(i)-end.get(i-1)));
else
ans-=(1L*(list.get(i)-list.get(i-1)));
}
}
}
pw.println(ans);
}
pw.flush();
pw.close();
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 988a9d7a6991c37ecfa8bd4900f92ae8 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
private static final int MODULO = 998244353;
private FastScanner in;
private PrintWriter out;
public static void main(String[] args) {
(new Main()).run();
}
private void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void solve() throws IOException {
int n = in.nextInt();
char[] string = in.next().toCharArray();
long total = n * (n - 1L) / 2;
List<Integer> list = new ArrayList<>();
for (int i = 1; i < n; i++) {
if (string[i] != string[i - 1]) {
list.add(i);
}
}
for (int i = 0; i < list.size() - 1; i++) {
total -= (list.get(i + 1) - list.get(i)) * 2;
}
if (list.size() > 0) {
total -= list.get(0);
total -= n - list.get(list.size() - 1);
}
total += list.size();
out.println(total);
}
private static class FastScanner {
BufferedReader bufferedReader;
StringTokenizer stringTokenizer;
FastScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
String line = bufferedReader.readLine();
if (line == null) {
return null;
}
stringTokenizer = new StringTokenizer(line);
}
return stringTokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void close() throws IOException {
bufferedReader.close();
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 4951b2b7196044f3a2d2e3c8d862e843 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 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: 19:37:29 08/10/2019
Custom Competitive programming helper.
*/
public class Main {
public static void solve(Reader in, Writer out) {
int n = in.nextInt();
char[] a = in.next().toCharArray();
long ans = get(n);
{
int[] lastIdxA = new int[n];
int[] lastIdxB = new int[n];
lastIdxA[n-1] = a[n-1]=='A'?n-1:n;
lastIdxB[n-1] = a[n-1]=='B'?n-1:n;
for(int i = n-2; i>=0; i--) {
lastIdxA[i] = a[i]=='A'?i:lastIdxA[i+1];
lastIdxB[i] = a[i]=='B'?i:lastIdxB[i+1];
}
for(int i = 0; i<n-1; i++) {
if(a[i]!=a[i+1]) {
if(a[i]=='A') {
ans-=lastIdxA[i+1]-i-1;
}else {
ans-=lastIdxB[i+1]-i-1;
}
}
}
}
for(int i = 0; i<n/2; i++){
char tmp = a[i];
a[i] = a[n-i-1];
a[n-i-1] = tmp;
}
{
int[] lastIdxA = new int[n];
int[] lastIdxB = new int[n];
lastIdxA[n-1] = a[n-1]=='A'?n-1:n;
lastIdxB[n-1] = a[n-1]=='B'?n-1:n;
for(int i = n-2; i>=0; i--) {
lastIdxA[i] = a[i]=='A'?i:lastIdxA[i+1];
lastIdxB[i] = a[i]=='B'?i:lastIdxB[i+1];
}
for(int i = 0; i<n-1; i++) {
if(a[i]!=a[i+1]) {
if(a[i]=='A') {
ans-=lastIdxA[i+1]-i-1;
}else {
ans-=lastIdxB[i+1]-i-1;
}
ans++;
}
}
}
out.println(ans);
}
public static long get(long n) {
return n*(n-1)/2;
}
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 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 | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | cf25af994e432e8859bea58757d481db | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class A
{
private static long ans, pair;
private static void solve(ArrayList<Character> list)
{
ArrayDeque<Integer> A=new ArrayDeque<>();
ArrayDeque<Integer> B=new ArrayDeque<>();
for(int i=0;i<list.size();i++)
{
char ch=list.get(i);
if(ch=='A') A.addLast(i);
else B.addLast(i);
}
A.addLast(list.size()); B.addLast(list.size());
for(int i=0;i<list.size();i++)
{
char ch=list.get(i);
if(ch=='A')
{
A.pollFirst();
int tmp=A.peekFirst()-i;
ans+=tmp;
if(tmp>1) pair++;
}
else
{
B.pollFirst();
int tmp=B.peekFirst()-i;
ans+=tmp;
if(tmp>1) pair++;
}
}
}
public static void main(String[] args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
char[] str=br.readLine().trim().toCharArray();
ArrayList<Character> list=new ArrayList<>();
for(char ch:str) list.add(ch);
solve(list); pair =0;
Collections.reverse(list);
solve(list); ans-=(N+ pair);
ans=(long)N*(N+1)/2-ans;
System.out.println(ans);
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | ee7b2f77e4600024fdfa82b1334bfea7 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 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 anand.oza
*/
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);
DABString solver = new DABString();
solver.solve(1, in, out);
out.close();
}
static class DABString {
public void solve(int testNumber, InputReader in, PrintWriter out) {
long n = in.nextInt();
char[] s = in.next().toCharArray();
UnionFind uf = new UnionFind((int) n);
for (int i = 0; i + 1 < n; i++) {
if (s[i] == s[i + 1]) {
uf.union(i, i + 1);
}
}
long answer = n * (n + 1) / 2; // all nonempty substrings
answer -= n; // remove strings of length 1
for (int i = 0; i + 1 < n; i++) {
if (s[i] != s[i + 1]) {
answer -= uf.size(i);
answer -= uf.size(i + 1);
answer++; // we double-counted the string of length 2
}
}
out.println(answer);
}
}
static class UnionFind {
private int[] __rep;
private int[] __size;
public UnionFind(int n) {
__rep = new int[n];
__size = new int[n];
for (int i = 0; i < n; i++) {
__rep[i] = i;
__size[i] = 1;
}
}
public int rep(int x) {
if (__rep[x] == x) {
return x;
}
int r = rep(__rep[x]);
__rep[x] = r;
return r;
}
public int size(int x) {
return __size[rep(x)];
}
public boolean union(int x, int y) {
x = rep(x);
y = rep(y);
if (x == y) {
return false;
}
if (size(x) < size(y)) {
int t = x;
x = y;
y = t;
}
// now size(x) >= size(y)
__rep[y] = x;
__size[x] += __size[y];
return true;
}
}
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 | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | ae22f9ad075df8874a0b9e8e9698a861 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class ABString implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni();
char[] x = in.next().toCharArray();
List<Integer> groups = new ArrayList<>();
long result = n * (n - 1L) / 2;
for (int i = 1; i < n; i++) {
if (x[i] != x[i - 1]) {
groups.add(i);
}
}
for (int i = 0; i < groups.size() - 1; i++) {
result -= (groups.get(i + 1) - groups.get(i)) * 2;
}
if (groups.size() > 0) {
result -= groups.get(0);
result -= n - groups.get(groups.size() - 1);
}
result += groups.size();
out.println(result);
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (ABString instance = new ABString()) {
instance.solve();
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 7803d090294e3737175b2a6125f212de | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
long n=sc.nextInt();
String s=sc.next();
long ans=n*(n-1)/2;
int x=0;
for (int j=0;j<2;j++) {
int cnt=1;
x=0;
for (int i = 1; i < n; i++) {
if (s.charAt(i) == s.charAt(i - 1)) {
cnt++;
} else {
ans = ans - cnt;
cnt = 1;
x++;
}
}
s=new StringBuilder(s).reverse().toString();
}
System.out.println(ans+x);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | 596dc2f013a0e3aed5cd6f24f317d34f | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class just{
public void solve () {
InputReader in =new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
long n=in.nextLong();
char s[]=in.nextLine().toCharArray();
long cnt=1;
Vector<Long>v=new Vector<>();
for(int i=1;i<n;i++) {
if(s[i]!=s[i-1]) {
v.add(cnt);
cnt=1;
continue;
}
cnt++;
}
v.add(cnt);
long ans = (n*(n-1))/2L;
for(int i=1;i<v.size();i++) {
ans-=(v.get(i)+v.get(i-1)-1);
}
pw.print(ans);
pw.flush();
pw.close();
}
public static void main(String[] args) throws Exception {
new Thread(null,new Runnable() {
public void run() {
new just().solve();
}
},"1",1<<26).start();
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
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 nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} 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] = nextInt();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(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;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public void extended(int a,int b) {
if(b==0) {
d=a;
p=1;
q=0;
}
else
{
extended(b,a%b);
int temp=p;
p=q;
q=temp-(a/b)*q;
}
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long[] shuffle(long[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
long temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static long GCD(long n,long m)
{
if(m==0)
return n;
else
return GCD(m,n%m);
}
static class pair implements Comparable<pair>
{
Long x,y,z;
pair(long l,long m,long n)
{
this.x=l;
this.y=m;
this.z=n;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return (x)+" "+(y)+" "+z;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x.equals(x) && p.y.equals(y) ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
}
class dsu{
int parent[];
long sz[];
dsu(int n){
parent=new int[n+1];
sz=new long[n+1];
for(int i=0;i<=n;i++)
{
parent[i]=i;
sz[i]=1;
}
}
int root(int n) {
while(parent[n]!=n)
{
parent[n]=parent[parent[n]];
n=parent[n];
}
return n;
}
void union(int _a,int _b) {
int p_a=root(_a);
int p_b=root(_b);
parent[p_a]=p_b;
sz[p_b]+=sz[p_a];
}
long find(int a,int b) {
int root_a=root(a);
int root_b=root(b);
if(root_a==root_b)
return 0;
else
return sz[root_a]*sz[root_b];
}
}
class Segment{
long seg[];
Segment (int n){
seg=new long[4*n];
}
public void build(int node,int start,int end) {
if(start==end) {
seg[node]=0L;
return ;
}
int mid=(start+end)/2;
build(2*node+1,start,mid);
build(2*node+2,mid+1,end);
}
public void update(int node,int start,int end,int fi,long val) {
if(start==end) {
seg[node]+=val;
return;
}
int mid=(start+end)/2;
if(fi>=start && fi<=mid) {
update(2*node+1,start,mid,fi,val);
}
else
update(2*node+2,mid+1,end,fi,val);
seg[node]=(seg[2*node+1]+seg[2*node+2]);
}
public long query(int node,int start,int end,int l,int r) {
if(l>end || r<start)
return 0;
if(start>=l && end<=r)
return seg[node];
int mid=(start+end)/2;
return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r));
}
/*public void updateRange(int node,int start,int end,int l,int r,int val) {
if(lazy[node]!=0) {
seg[node]-=lazy[node];
if(start!=end) {
lazy[2*node+1]+=lazy[node];
lazy[2*node+2]+=lazy[node];
}
lazy[node]=0;
}
if(l>end || r<start)
return ;
if(start>=l && end<=r) {
seg[node]-=val;
if(start!=end) {
lazy[2*node+1]+=val;
lazy[2*node+2]+=val;
}
return ;
}
int mid=(start+end)/2;
updateRange(2*node+1,start,mid,l,r,val);
updateRange(2*node+2,mid+1,end,l,r,val);
seg[node]=Math.min(seg[2*node+1],seg[2*node+2]);
}
public long queryRange(int node,int start,int end,int l,int r) {
if(lazy[node]!=0L) {
seg[node]-=lazy[node];
if(start!=end) {
lazy[2*node+1]+=lazy[node];
lazy[2*node+2]+=lazy[node];
}
lazy[node]=0;
}
if(l>end || r<start)
return Long.MAX_VALUE;
if(start>=l && end<=r)
return seg[node];
int mid=(start+end)/2;
return Math.min(queryRange(2*node+1,start,mid,l,r),queryRange(2*node+2,mid+1,end,l,r));
}*/
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output | |
PASSED | b31d171cd5c05410d09ccaab28f97f25 | train_000.jsonl | 1570545300 | The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
char[] s = in.next().toCharArray();
int st = 0;
long res = 0;
for (int i = 1; i < n; i++) {
if (s[i] != s[st]) {
res++;
} else {
if (st+1 == i) {
st = i;
} else {
st = i-1;
res++;
}
}
}
for (int i = 0, j = n-1; i<j; i++, j--) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
st = 0;
for (int i = 1; i < n; i++) {
if (s[i] != s[st]) {
if (st+1 < i) res++;
} else {
if (st+1 == i) {
st = i;
} else {
st = i-1;
}
}
}
long n1 = n;
n1 = n1*(n1-1);
n1 /= 2;
res = n1-res;
out.println(res);
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Main obj = new Main();
obj.solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
}
}
| Java | ["5\nAABBB", "3\nAAA", "7\nAAABABB"] | 2 seconds | ["6", "3", "15"] | NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"binary search",
"strings"
] | 3eb23b7824d06b86be72c70b969be166 | The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B. | 1,900 | Print one integer — the number of good substrings of string $$$s$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.