exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k ⌀ | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k ⌀ | difficulty int64 -1 3.5k ⌀ | prob_desc_output_spec stringlengths 17 1.47k ⌀ | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 187cde9af6b40e3b227fe19992743d0f | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.util.InputMismatchException;
public class compressString {
static char[][] grid;
static String fun(int[][] wolf ,int w, int n , int m)
{
for(int i=0;i<w;i++)
{
int x= wolf[i][0];int y = wolf[i][1];
// System.out.println(x+" "+y);
if(x+1<n)
{
if(grid[x+1][y]=='S')
return "No";
else if(grid[x+1][y]=='.')
grid[x+1][y]='D';
}
if(y+1<m)
{
if(grid[x][y+1]=='S')
return "No";
else if(grid[x][y+1]=='.')
grid[x][y+1]='D';
}
if(x-1>=0)
{
if(grid[x-1][y]=='S')
return "No";
else if(grid[x-1][y]=='.')
grid[x-1][y]='D';
}
if(y-1>=0)
{
if(grid[x][y-1]=='S')
return "No";
else if(grid[x][y-1]=='.')
grid[x][y-1]='D';
}
}
return "A";
}
public static void main(String[] args) {
FastScanner s = new FastScanner();
int r = s.nextInt();
int c = s.nextInt();
grid = new char[r][c];
int[][] wolf =new int[r*c][2];
int k=0;
for(int i=0;i<r;i++)
{
String v = s.nextString();
int j=0;
for(char l:v.toCharArray())
{
grid[i][j] = l;
if(grid[i][j]=='W')
{
wolf[k][0]=i;wolf[k][1]=j;
k++;
}
j++;
}
}
String ans =fun(wolf,k,r,c);
if(ans.equals("No"))
System.out.println(ans);
else
{
System.out.println("Yes");
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++)
System.out.print(grid[i][j]);
System.out.println();
}
}
}
static class FastScanner {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner() {
this(System.in);
}
public FastScanner(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 nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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;
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 73cff629c4e9b5edb0a829bb807694ea | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.Scanner;
public class ProtectSheep {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int r=sc.nextInt();
int c=sc.nextInt();
sc.nextLine();
char arr[][]=new char[r][c];
for(int i=0;i<r;i++){
String str=sc.nextLine();
for(int j=0;j<c;j++){
arr[i][j]=str.charAt(j);
}
}
int i=0;
int flag=0;
for(i=0;i<r;i++){
for(int j=0;j<c;j++){
if(arr[i][j]=='S'){
if(i-1>=0 && arr[i-1][j]!='W'){
if(i-1>=0 && arr[i-1][j]=='.') arr[i-1][j]='D';
}else if(i-1>=0 && arr[i-1][j]=='W'){
flag=1;
System.out.println("No");
break;
}
if(i+1<r && arr[i+1][j]!='W'){
if(i+1<r && arr[i+1][j]=='.') arr[i+1][j]='D';
}else if(i+1<r && arr[i+1][j]=='W'){
flag=1;
System.out.println("No");
break;
}
if(j-1>=0 && arr[i][j-1]!='W'){
if(j-1>=0 && arr[i][j-1]=='.') arr[i][j-1]='D';
}else if(j-1>=0 && arr[i][j-1]=='W'){
flag=1;
System.out.println("No");
break;
}
if(j+1<c && arr[i][j+1]!='W'){
if(j+1<c && arr[i][j+1]=='.') arr[i][j+1]='D';
}else if(j+1<c && arr[i][j+1]=='W'){
flag=1;
System.out.println("No");
break;
}
}
}
if(flag==1)
break;
}
if(i==r){
System.out.println("Yes");
for(int k=0;k<r;k++){
for(int j=0;j<c;j++){
System.out.print(arr[k][j]);
}
System.out.println();
}
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | baa7cb1140956fce9f15e87d35cb8ec4 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author pandusonu
*/
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
// out.print("Case #" + testNumber + ": ");
int n = in.readInt();
int m = in.readInt();
char[][] a = new char[n + 2][m + 2];
for (int i = 0; i < n; i++) {
String s = in.readString();
for (int j = 0; j < m; j++) {
a[i + 1][j + 1] = s.charAt(j);
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] == 'S') {
int[][] x = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int[] xx : x) {
if (a[i + xx[0]][j + xx[1]] == 'W') {
out.println("No");
return;
}
}
}
}
}
out.println("Yes");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] == '.')
out.print("D");
else out.print(a[i][j]);
}
out.println();
}
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
try {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0)
return -1;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return buf[curChar++];
}
public int readInt() {
return (int) readLong();
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new RuntimeException();
}
boolean negative = false;
if (c == '-') {
negative = true;
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 negative ? (-res) : (res);
}
public String readString() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 7e17361deb5d78571f209d6627d55a5b | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.Scanner;
public class Prob948A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
StringBuffer[] rows = new StringBuffer[row];
sc.nextLine();
rows[0] = new StringBuffer(sc.nextLine());
for(int i = 0; i < row; ++i) {
if (row - i > 1) {
rows[i + 1] = new StringBuffer(sc.nextLine());
}
for (int j = 0; j < col; ++j) {
if (rows[i].charAt(j) == 'S') {
if (j > 0) {
if(!checkNeighbor(rows, i, j - 1)) {
System.out.println("No");
sc.close();
return;
}
}
if (col - j > 1) {
if(!checkNeighbor(rows, i, j + 1)) {
System.out.println("No");
sc.close();
return;
}
}
if (i > 0) {
if(!checkNeighbor(rows, i - 1, j)) {
System.out.println("No");
sc.close();
return;
}
}
if (row - i > 1) {
if(!checkNeighbor(rows, i + 1, j)) {
System.out.println("No");
sc.close();
return;
}
}
}
}
}
System.out.println("Yes");
for (StringBuffer ans : rows) {
System.out.println(ans);
}
sc.close();
}
public static boolean checkNeighbor(StringBuffer[] rows, int i, int j) {
switch(rows[i].charAt(j)) {
case '.': {
rows[i].setCharAt(j, 'D');
return true;
}
case 'D': {
return true;
}
case 'W': {
return false;
}
case 'S': {
return true;
}
default: {
return true;
}
}
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 92008e761ceef3d108d2528a5c7c6a18 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes |
import java.io.*;
import java.util.*;
public class NewClass {
static final int INF = Integer.MAX_VALUE;
static void mergeSort(int[] a, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(a, p, q);
mergeSort(a, q + 1, r);
merge(a, p, q, r);
}
}
static void merge(int[] a, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int[] L = new int[n1 + 1], R = new int[n2 + 1];
for (int i = 0; i < n1; i++) {
L[i] = a[p + i];
}
for (int i = 0; i < n2; i++) {
R[i] = a[q + 1 + i];
}
L[n1] = R[n2] = INF;
for (int k = p, i = 0, j = 0; k <= r; k++) {
if (L[i] <= R[j]) {
a[k] = L[i++];
} else {
a[k] = R[j++];
}
}
}
public static boolean sieve(int n) {
int a[] = new int[n + 1];
for (int i = 2; i <= n; i++) {
a[i] = 1;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (a[i] == 1) {
for (int k = 2; i * k <= n; k++) {
a[i * k] = 0;
}
}
}
return a[n] == 1;
}
public static long sum(int a) {
long su = 0;
while (a > 0) {
su += a % 10;
a /= 10;
}
return su;
}
public static int divi(int b) {
int n = 0;
for (int i = 2; i <= Math.sqrt(b); i++) {
if (b % i == 0) {
n = i;
break;
}
}
if (n == 0) {
return b;
}
return n;
}
public static boolean prime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static String reve(int a, int b, String s) {
String q = "";
for (int i = b; i >= a; i--) {
q += s.charAt(i);
}
return q;
}
public static boolean isvowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') {
return true;
} else {
return false;
}
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int hole(int n) {
int y = 0;
if (n == 1) {
return 0;
}
if (prime(n)) {
return 1;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (prime(i)) {
y++;
}
if (prime(n / i) && i != (n / i)) {
y++;
}
}
}
return y;
}
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
OutputWriter or = new OutputWriter(System.out);
int n = in.nextInt(),k=in.nextInt();
StringBuilder[] s= new StringBuilder[n];
for (int i = 0; i < n; i++)s[i]=new StringBuilder(in.readString());
for (int i = 0; i < n; i++) {
String w= s[i].toString();
if (w.contains("SW")||w.contains("WS")) {
or.print("No");
or.flush();
return;
}
else
{
if (i!=n-1) {
for (int j = 0; j < k; j++) {
if ((s[i].charAt(j)=='S'&&s[i+1].charAt(j)=='W')||(s[i].charAt(j)=='W'&&s[i+1].charAt(j)=='S')) {
or.print("No");
or.flush();
return;
}
}
}
for (int j = 0; j < k; j++) {
if (s[i].charAt(j)=='.') {
s[i].setCharAt(j, 'D');
}
}
}
}
or.printLine("Yes");
for (int j = 0; j < n; j++) {
or.printLine(s[j]);
}
or.flush();
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | ddfa95c24e45cc473df7e4faf070a255 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class CF {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int r = in.nextInt();
int c = in.nextInt();
char[][] ch = new char[r][c];
for (int i = 0; i < r; i++) {
ch[i] = in.next().toCharArray();
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (ch[i][j] == 'W') {
if (i > 0 && ch[i - 1][j] == 'S') {
out.println("No");
out.close();
return;
} else if (i > 0 && ch[i - 1][j] != 'W') {
ch[i - 1][j] = 'D';
}
if (j > 0 && ch[i][j - 1] == 'S') {
out.println("No");
out.close();
return;
} else if (j > 0 && ch[i][j - 1] != 'W') {
ch[i][j - 1] = 'D';
}
if (i < r - 1 && ch[i + 1][j] == 'S') {
out.println("No");
out.close();
return;
} else if (i < r - 1 && ch[i + 1][j] != 'W') {
ch[i + 1][j] = 'D';
}
if (j < c - 1 && ch[i][j + 1] == 'S') {
out.println("No");
out.close();
return;
} else if (j < c - 1 && ch[i][j + 1] != 'W') {
ch[i][j + 1] = 'D';
}
}
}
}
out.println("Yes");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
out.print(ch[i][j]);
}
out.println();
}
out.close();
}
static class FastScanner {
private BufferedReader in;
private String[] line;
private int index;
private int size;
public FastScanner(InputStream in) throws IOException {
this.in = new BufferedReader(new InputStreamReader(in));
init();
}
public FastScanner(String file) throws FileNotFoundException {
this.in = new BufferedReader(new FileReader(file));
}
private void init() throws IOException {
line = in.readLine().split(" ");
index = 0;
size = line.length;
}
public int nextInt() throws IOException {
if (index == size) {
init();
}
return Integer.parseInt(line[index++]);
}
public long nextLong() throws IOException {
if (index == size) {
init();
}
return Long.parseLong(line[index++]);
}
public float nextFloat() throws IOException {
if (index == size) {
init();
}
return Float.parseFloat(line[index++]);
}
public double nextDouble() throws IOException {
if (index == size) {
init();
}
return Double.parseDouble(line[index++]);
}
public String next() throws IOException {
if (index == size) {
init();
}
return line[index++];
}
public String nextLine() throws IOException {
if (index == size) {
init();
}
StringBuilder sb = new StringBuilder();
for (int i = index; i < size; i++) {
sb.append(line[i]).append(" ");
}
return sb.toString();
}
private int[] nextIntArray(int n) throws IOException {
int[] tab = new int[n];
for (int i = 0; i < tab.length; i++) {
tab[i] = nextInt();
}
return tab;
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 24cb041286f4e02375a974c1d70c4a46 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.*;
public class Main{
static int[][] D = {{-1,0},{1,0},{0,-1},{0,1}};
static int[][] Visited;
static int flag = 1;
public static String[][] dfs(String[][] arr,int x,int y,int n,int m){
Visited[x][y]=1;
for (int i=0;i<4;i++){
if ((x+D[i][0]>=0 && x+D[i][0]<n) && (y+D[i][1]>=0 && y+D[i][1]<m)){
int X = x+D[i][0];
int Y = y+D[i][1];
if (Visited[X][Y]==0){
if (arr[X][Y].equals("S")){
if (arr[x][y].equals("W")){
flag = -1;
return arr;
}
arr[x][y]="D";
break;
}
else if(arr[X][Y].equals("D")){
continue;
}
else if (arr[X][Y].equals(".")){
arr = dfs(arr,X,Y,n,m);
}
}
}
}
return arr;
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
// ArrayList<Integer>[] arr = new ArrayList[n+1];
String[][] arr = new String[n][m];
Visited = new int[n][m];
// for (int i=1;i<=n;i++){
// arr[i] = new ArrayList<Integer>();
// }
for (int i=0;i<n;i++){
arr[i] = scan.next().split("");
}
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if (arr[i][j].equals("W")){
if (Visited[i][j]==0){
arr = dfs(arr,i,j,n,m);
if (flag==-1){
System.out.println("No");
return;
}
}
}
}
}
System.out.println("Yes");
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
System.out.print(arr[i][j]);
}
System.out.println();
}
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 388c773339477aea4ec7a2aa32b79986 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | //package CFMAR10;
import java.io.*;
import java.util.*;
public class Q1{
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
InputReader in=new InputReader();
int R=in.nextInt();
int C=in.nextInt();
// int count=0;
String ans1[]=new String[R];
for(int l=0;l<R;l++){
ans1[l]=in.next();
}
char ans[][]=new char[R][C];
for(int i=0;i<R;i++){
for(int j=0;j<C;j++){
ans[i][j]=ans1[i].charAt(j);
// System.out.println(ans[i][j]);
if(ans[i][j]=='.'){
// count++;
ans[i][j]='D';
}
}
}
for(int i=1;i<R-1;i++){
// System.out.println("as");
for(int j=1;j<C;j++){
if((ans[i][j-1]=='S') && ((ans[i-1][j-1]=='W') || (ans[i+1][j-1]=='W')|| (ans[i][j]=='W')) || (ans[i][j-1]=='W') && ((ans[i-1][j-1]=='S') || (ans[i+1][j-1]=='S')||(ans[i][j]=='S')) ){
System.out.println("No");
return;
}
}
}
for(int i=0;i<R-1;i++){
// System.out.println("as");
for(int j=1;j<=C;j++){
if((ans[i][j-1]=='S') && (ans[i+1][j-1]=='W') || (ans[i][j-1]=='W') && ((ans[i+1][j-1]=='S') ) ){
System.out.println("No");
return;
}
}
}
//
//
// if(count==0){
// System.out.println("No");
// }
for(int i=0;i<R;i++){
for(int j=1;j<=C-1;j++){
// System.out.println("asss"+j);
if((ans[i][j-1]=='S' && ans[i][j]=='W' ) || ((ans[i][j-1]=='W' ) && ( ans[i][j]=='S'))){
System.out.println("No" );
return;
}
}
}
System.out.println("Yes");
for(int i=0;i<R;i++){
for(int j=0;j<C;j++){
System.out.print(ans[i][j]);
}
System.out.println();
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | ed7fe579abee866cafd7d66929eebbaa | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.awt.List;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n=ni(), m=ni();
char[][] s=new char[n][];
for(int i=0;i<n;i++) {
s[i]=ns(m);
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(s[i][j]=='S') {
if(j-1>=0) {
if(s[i][j-1]=='W') {
out.println("No");
return;
}
}
if(i-1>=0) {
if(s[i-1][j]=='W') {
out.println("No");
return;
}
}
if(j+1<m) {
if(s[i][j+1]=='W') {
out.println("No");
return;
}
}
if(i+1<n) {
if(s[i+1][j]=='W') {
out.println("No");
return;
}
}
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(s[i][j]=='.') s[i][j]='D';
}
}
out.println("YES");
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
out.print(s[i][j]);
}
out.println();
}
}
void setDog(char[][] s,int i,int j,int n,int m) {
if(i-1>=0&&s[i-1][j]=='.') {
s[i-1][j]='D';
}
if(j-1>=0&&s[i][j-1]=='.') {
s[i][j-1]='D';
}
if(i+1<n&&s[i+1][j]=='.') {
s[i+1][j]='D';
}
if(j+1<m&&s[i][j+1]=='.') {
s[i][j+1]='D';
}
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception
{ new Main().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf)
{
ptrbuf = 0;
try
{ lenbuf = is.read(inbuf); }
catch (IOException e)
{ throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c)
{ return !(c >= 33 && c <= 126); }
private int skip()
{ int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd()
{ return Double.parseDouble(ns()); }
private char nc()
{ return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b)))
{ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private String nsl()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b) && 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 static void tr(Object... o)
{ System.out.println(Arrays.deepToString(o)); }
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | e700151469c017f30869ee6dd321b055 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes |
public class ProtectSheep {
public static void main(String[]args) throws Exception{
java.util.Scanner sc= new java.util.Scanner(System.in);
int r=sc.nextInt();
int c=sc.nextInt();
sc.nextLine();
char[][] p= new char[r][c];
for(int i=0; i<r; i++){
String st= sc.nextLine();
for(int j=0; j<c; j++){
if(st.charAt(j)=='S' || st.charAt(j)=='W'){
p[i][j]=st.charAt(j);
}else{
p[i][j]='D';
}
}
}
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
if(p[i][j]=='W'){
try{
if(!(p[i-1][j]=='D' || p[i-1][j]=='W')){
System.out.println("No");
return;
}
}catch (Exception e){}
try{
if(!(p[i+1][j]=='D' || p[i+1][j]=='W')){
System.out.println("No");
return;
}
}catch (Exception e){}
try{
if(!(p[i][j-1]=='D' || p[i][j-1]=='W')){
System.out.println("No");
return;
}
}catch(Exception e){}
try{
if(!(p[i][j+1]=='D' || p[i][j+1]=='W')){
System.out.println("No");
return;
}
}catch (Exception e){}
}
}
}
System.out.println("Yes");
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
System.out.print(p[i][j]);
}
System.out.println();
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 50d1780918c4efa7ef6341595d034c81 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class bfs_dfs {
public static void main(String[] args)
{
scanner in = new scanner();
int r = in.nextInt();
int c = in.nextInt();
StringBuilder[] s = new StringBuilder[r+2];
for(int i = 1;i<=r;i++)
{
s[i] = new StringBuilder(in.next());
s[i].append('D');
s[i].insert(0,'D');
}
char[] x = new char[c+2];
Arrays.fill(x,'D');
s[0] = new StringBuilder(String.copyValueOf(x));
s[r+1] = new StringBuilder(String.copyValueOf(x));
boolean x1 = true;
//System.out.println("im here");
for(int i= 1;x1 && i<=r;i++)
{
for(int j = 1;j<=c;j++)
{
//System.out.println("im here");
if(s[i].charAt(j)=='S')
{
if(s[i].charAt(j+1)!='W' && s[i].charAt(j-1)!='W' && s[i-1].charAt(j)!='W' && s[i+1].charAt(j)!='W')
{
if(s[i].charAt(j+1)==Character.valueOf('.'))
s[i].setCharAt(j+1,'D');
if(s[i].charAt(j-1)==Character.valueOf('.'))
s[i].setCharAt(j-1,'D');
if(s[i-1].charAt(j)==Character.valueOf('.'))
s[i-1].setCharAt(j,'D');
if(s[i+1].charAt(j)==Character.valueOf('.'))
s[i+1].setCharAt(j,'D');
}
else
{
x1 = false;
break;
}
}
}
}
if(!x1)
System.out.println("NO");
else
{
System.out.println("YES");
for(int i = 1;i<=r;i++)
{
s[i].deleteCharAt(0);
s[i].deleteCharAt(c);
System.out.println(s[i]);
}
}
}
}
class scanner
{
BufferedReader br;
StringTokenizer st;
public scanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
st = null;
}
public String next()
{
while(st==null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | e21b72e4085f14e679aa08673c4cf360 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.Scanner;
public class ProtectSheep_ {
public static void main(String[] args) {
int i,j;
boolean safe=true;
Scanner sc=new Scanner(System.in);
int R=sc.nextInt();
int C=sc.nextInt();sc.nextLine();
char field[][]=new char[R][C];
for(i=0;i<R;i++)
field[i]=sc.nextLine().replaceAll("\\.","D").toCharArray();
sc.close();
for(i=0;i<R;i++){
for(j=0;j<C;j++) {
if(field[i][j]=='S')
{
if(i-1>=0 && field[i-1][j]=='W')
{
safe=false;
break;
}
else if(i+1<=R-1 && field[i+1][j]=='W')
{
safe=false;
break;
}
if(j-1>=0 && field[i][j-1]=='W')
{
safe=false;
break;
}
else if(j+1<=C-1 && field[i][j+1]=='W')
{
safe=false;
break;
}
}
}
}
if(safe) {
System.out.println("YES");
for(i=0;i<R;i++) {
for(j=0;j<C;j++)
System.out.print(field[i][j]);
System.out.println();
}
}
else
System.out.print("NO");
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | bb17bbf7b941d572596c7ae0f3e4721c | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.Scanner;
public class ProtectSheep_ {
public static void main(String[] args) {
int i,j;
boolean safe=true;
Scanner sc=new Scanner(System.in);
int R=sc.nextInt();
int C=sc.nextInt();sc.nextLine();
char field[][]=new char[R][C];
for(i=0;i<R;i++)
field[i]=sc.nextLine().substring(0,C).replaceAll("\\.","D").toCharArray();
sc.close();
for(i=0;i<R;i++){
for(j=0;j<C;j++) {
if(field[i][j]=='S')
{
if(i-1>=0 && field[i-1][j]=='W')
{
safe=false;
break;
}
else if(i+1<R && field[i+1][j]=='W')
{
safe=false;
break;
}
if(j-1>=0 && field[i][j-1]=='W')
{
safe=false;
break;
}
else if(j+1<C && field[i][j+1]=='W')
{
safe=false;
break;
}
}
}
}
if(safe) {
System.out.println("YES");
for(i=0;i<R;i++) {
for(j=0;j<C;j++)
System.out.print(field[i][j]);
System.out.println();
}
}
else
System.out.print("NO");
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 32b270aae498fb8503654e6f98900623 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class ProtectSheep_competition {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
int i,j;
boolean safe=true;
FastReader sc=new FastReader();
int R=sc.nextInt();
int C=sc.nextInt();//sc.nextLine();
char field[][]=new char[R][C];
for(i=0;i<R;i++)
field[i]=sc.nextLine().substring(0,C).replaceAll("\\.","D").toCharArray();
for(i=0;i<R;i++){
for(j=0;j<C;j++) {
if(field[i][j]=='S')
{
if(i-1>=0 && field[i-1][j]=='W')
{
safe=false;
break;
}
else if(i+1<=R-1 && field[i+1][j]=='W')
{
safe=false;
break;
}
if(j-1>=0 && field[i][j-1]=='W')
{
safe=false;
break;
}
else if(j+1<=C-1 && field[i][j+1]=='W')
{
safe=false;
break;
}
}
}
}
if(safe) {
System.out.println("YES");
for(i=0;i<R;i++) {
for(j=0;j<C;j++)
System.out.print(field[i][j]);
System.out.println();
}
}
else
System.out.print("NO");
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 87e5aafe926972070515c1a5f44071e1 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 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.BufferedReader;
import java.io.InputStreamReader;
//import java.io.Reader;
public class ProtectSheeps {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
A solver = new A();
solver.solve(1, in, out);
out.close();
}
static class A {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int r = in.ni(), c = in.ni();
char[][] map = in.nm(r, c);
int[] dx = new int[]{1, -1, 0, 0};
int[] dy = new int[]{0, 0, 1, -1};
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (map[i][j] == 'W') {
for (int k = 0; k < 4; k++) {
int ni = i + dy[k];
int nj = j + dx[k];
if (ni >= 0 && ni < r && nj >= 0 && nj < c) {
if (map[ni][nj] == 'S') {
out.println("No");
return;
}
if (map[ni][nj] == '.') {
map[ni][nj] = 'D';
}
}
}
}
}
}
out.println("Yes");
for (int i = 0; i < r; i++) {
out.println(String.valueOf(map[i]));
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String ns() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(ns());
}
public char[] ns(int n) {
char[] buf = new char[n];
try {
in.read(buf);
} catch (IOException e) {
throw new RuntimeException();
}
return buf;
}
public char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) {
map[i] = ns(m);
readLine();
}
return map;
}
public String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeException();
}
}
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | f00c734872cb1d8ddf94f90205866fe5 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] Args) {
Scanner in = new Scanner(System.in);
int r=in.nextInt();
int c=in.nextInt();
String[] s = new String[1000];
for(int i=0;i<r;i++) {
s[i]=in.next();
}
int flag=0;
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
if(j+1<=c-1) {
if(s[i].charAt(j)=='S') {
if(s[i].charAt(j+1)!='W' && s[i].charAt(j+1)!='S') {
s[i]=s[i].substring(0, j+1)+'D'+s[i].substring(j+2);
}
if(s[i].charAt(j+1)=='W') {
flag=1;
break;
}
}
}
if(j-1>=0) {
if(s[i].charAt(j)=='S') {
if(s[i].charAt(j-1)!='W' && s[i].charAt(j-1)!='S') {
s[i]=s[i].substring(0, j-1)+'D'+s[i].substring(j);
}
if(s[i].charAt(j-1)=='W'){
flag=1;
break;
}
}
}
if(i+1<=r-1) {
if(s[i].charAt(j)=='S') {
if(s[i+1].charAt(j)!='W' && s[i+1].charAt(j)!='S') {
s[i+1]=s[i+1].substring(0, j)+'D'+s[i+1].substring(j+1);
}
if(s[i+1].charAt(j)=='W') {
flag=1;
break;
}
}
}
if(i-1>=0) {
if(s[i].charAt(j)=='S') {
if(s[i-1].charAt(j)!='W' && s[i-1].charAt(j)!='S') {
s[i-1]=s[i-1].substring(0, j)+'D'+s[i-1].substring(j+1);
}
if(s[i-1].charAt(j)=='W') {
flag=1;
break;
}
}
}
}
}
if(flag==1) {
System.out.println("No");
}
else {
System.out.println("Yes");
for(int i=0;i<r;i++) {
System.out.println(s[i]);
}
}
in.close();
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | d72b3e1f739301ee13e7d67dfbe8d6fd | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | //package main.java.com.algorithms.practice.codeforces;
import java.io.*;
import java.util.*;
public class ProtectSheep {
private static int rows;
private static int columns;
private static Cell[][] grid;
private static boolean[][] visited = new boolean[rows][columns];
private static boolean possible = true;
static class Cell{
int r;
int c;
Set<Cell> neighbours;
char token;
Cell(int r, int c, char token){
this.neighbours = new HashSet<>();
this.r = r;
this.c = c;
this.token = token;
}
public void setToken(char token) {
this.token = token;
}
public void addNeighbours(){
boolean wolfAround = false;
if(r + 1 < rows){
neighbours.add(grid[r + 1][c]);
wolfAround = grid[r + 1][c].token == 'W';
}
if(c + 1 < columns){
neighbours.add(grid[r][c + 1]);
wolfAround = grid[r][c + 1].token == 'W' || wolfAround;
}
if(r - 1 >= 0){
neighbours.add(grid[r - 1][c]);
wolfAround = grid[r - 1][c].token == 'W' || wolfAround;
}
if(c - 1 >= 0){
neighbours.add(grid[r][c - 1]);
wolfAround = grid[r][c - 1].token == 'W' || wolfAround;
}
if(possible){
possible = !((token == 'S') && wolfAround);
}
}
}
private static boolean performCheck(int r, int c, char[][] grids){
boolean wolfAround = false;
if(r + 1 < rows){
wolfAround = grids[r + 1][c] == 'W';
}
if(c + 1 < columns){
wolfAround = grids[r][c + 1] == 'W' || wolfAround;
}
if(r - 1 >= 0){
wolfAround = grids[r - 1][c] == 'W' || wolfAround;
}
if(c - 1 >= 0){
wolfAround = grids[r][c - 1] == 'W' || wolfAround;
}
if(possible){
possible = !((grids[r][c] == 'S') && wolfAround);
}
return possible;
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer tokenizer = new StringTokenizer(in.readLine().trim());
rows = Integer.parseInt(tokenizer.nextToken());
columns = Integer.parseInt(tokenizer.nextToken());
char[][] grids = new char[rows][columns];
for(int i = 0; i < rows; i++){
String line = in.readLine().trim();
int j = 0;
for(char c: line.toCharArray()){
grids[i][j] = c;
j++;
}
}
for(int i = 0; i < rows; i++){
if(!possible) break;
for(int j = 0; j < columns; j++){
performCheck(i, j, grids);
if(!possible) break;
}
}
if(!possible){
out.write("No"+"\n");
out.flush();
}else{
out.write("Yes"+"\n");
out.flush();
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
if(grids[i][j] == '.'){
grids[i][j] = 'D';
}
out.write(grids[i][j] );
out.flush();
}
System.out.println();
}
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | b074f431203a9053f283142fbc530411 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String []s=bf.readLine().split(" ");
int r=Integer.parseInt(s[0]);
int c=Integer.parseInt(s[1]);
char a[][]=new char[r][c];
for(int i=0;i<r;i++)
{
String s1=bf.readLine();
for(int j=0;j<c;j++)
{
a[i][j]=s1.charAt(j);
}
}
boolean sangam=false;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(a[i][j]=='W')
{
if(i-1>=0)
{
if(a[i-1][j]=='S')
{
sangam=true;
break;
}
else if(a[i-1][j]!='W')
{
a[i-1][j]='D';
}
}
if(i+1<=r-1)
{
if(a[i+1][j]=='S')
{
sangam=true;
break;
}
else if(a[i+1][j]!='W')
{
a[i+1][j]='D';
}
}
if(j-1>=0)
{
if(a[i][j-1]=='S')
{
sangam=true;
break;
}
else if(a[i][j-1]!='W')
{
a[i][j-1]='D';
}
}
if(j+1<=c-1)
{
if(a[i][j+1]=='S')
{
sangam=true;
break;
}
else if(a[i][j+1]!='W')
{
a[i][j+1]='D';
}
}
}
}
if(sangam)
{
break;
}
}
StringBuilder sb=new StringBuilder();
if(sangam)
{
sb.append("NO");
}
else
{
sb.append("YES\n");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
sb.append(a[i][j]+"");
}
sb.append("\n");
}
}
System.out.println(sb);
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 7ad6323125cad2ab897cc517be624792 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | /*
* UMANG PANCHAL
* DAIICT
*/
import java.util.*;
import java.io.*;
import java.math.*;
import java.util.Comparator;
public class Main
{
private static final Comparator<? super Integer> Comparator = null;
static LinkedList<Integer> adj[];
static ArrayList<Integer> adj1[];
static int[] color,visited1;
static boolean b[],visited[],possible;
static int level[];
static Map<Integer,HashSet<Integer>> s;
static int totalnodes,colored;
static int count[];
static long sum[];
static int nodes;
static long ans=0;
static long[] as=new long[10001];
static long c1=0,c2=0;
static int[] a,d,k;
static int max=100000000;
static long MOD = 1000000007,sm=0,m=Long.MIN_VALUE;
static boolean[] prime=new boolean[1000005];
static int[] levl;
static int[] eat;
static int price[];
static int res[],par[],co[];
static int result=0;
static int[] root,size,du,dv;
static long p=Long.MAX_VALUE;
static int start,end,r=0;
static boolean[] vis1,vis2;
// --------------------My Code Starts Here----------------------
public static void main(String[] args) throws IOException
{
in=new InputReader(System.in);
w=new PrintWriter(System.out);
int n=ni(),m=ni();
char[][] c=new char[n+2][m+2];
for(int i=0;i<n;i++)
{
String s=ns();
for(int j=0;j<m;j++)
c[i+1][j+1]=s.charAt(j);
}
boolean ans=true;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(c[i][j]=='S')
{
if(c[i][j-1]=='W' || c[i][j+1]=='W' || c[i-1][j]=='W' || c[i+1][j]=='W')
{
ans=false;
break;
}
}
}
}
if(!ans)
w.print("No");
else
{
w.println("Yes");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(c[i][j]=='.')
c[i][j]='D';
w.print(c[i][j]);
}
w.println();
}
}
w.close();
}
// --------------------My Code Ends Here------------------------
/*
* PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>()
{
public int compare(Integer o1, Integer o2)
{
return Integer.compare(o2,o1);
}
});
*
*
*/
public static void bfs1(int u)
{
Queue<Integer> q=new LinkedList();
q.add(u);
visited[u]=true;
while(!q.isEmpty())
{
//w.print(1);
int p=q.poll();
for(int i=0;i<adj[p].size();i++)
{
if(!visited[adj[p].get(i)])
{
q.add(adj[p].get(i));
visited[adj[p].get(i)]=true;
}
levl[adj[p].get(i)]=levl[p]+1;
}
}
}
public static void bfs2(int u)
{
Queue<Integer> q=new LinkedList();
q.add(u);
vis2[u]=true;
while(!q.isEmpty())
{
int p=q.poll();
for(int i=0;i<adj[p].size();i++)
{
if(!vis2[adj[p].get(i)])
{
dv[adj[p].get(i)]=dv[p]+1;
q.add(adj[p].get(i));
vis2[adj[p].get(i)]=true;
}
}
}
}
public static void buildgraph(int n)
{
adj=new LinkedList[n+1];
visited=new boolean[n];
level=new int[n];
par=new int[n];
for(int i=0;i<=n;i++)
{
adj[i]=new LinkedList<Integer>();
}
}
/*public static long kruskal(Pair[] p)
{
long ans=0;
int w=0,x=0,y=0;
for(int i=0;i<p.length;i++)
{
w=p[i].w;
x=p[i].x;
y=p[i].y;
if(root(x)!=root(y))
{
ans+=w;
union(x,y);
}
}
return ans;
}*/
static class Pair implements Comparable<Pair>
{
Integer x,w;
Pair(int x,int w)
{
this.x=x;
this.w=w;
}
public int compareTo(Pair p)
{
return Integer.compare(this.w,p.w);
}
}
static class npair implements Comparable<npair>
{
int a,b;
npair(int a,int b)
{
this.a=a;
this.b=b;
//this.index=index;
}
public int compareTo(npair o) {
// TODO Auto-generated method stub
return Integer.compare(this.a,o.a);
}
}
public static int root(int i)
{
while(root[i]!=i)
{
root[i]=root[root[i]];
i=root[i];
}
return i;
}
public static void init(int n)
{
root=new int[n+1];
for(int i=1;i<=n;i++)
root[i]=i;
}
public static void union(int a,int b)
{
int root_a=root(a);
int root_b=root(b);
root[root_a]=root_b;
// size[root_b]+=size[root_a];
}
public static boolean isPrime(long n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0)
return false;
for (long i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
public static String ns()
{
return in.nextLine();
}
public static int ni()
{
return in.nextInt();
}
public static long nl()
{
return in.nextLong();
}
public static int[] na(int n)
{
int[] a=new int[n];
for(int i=0;i<n;i++)
a[i]=ni();
return a;
}
public static long[] nla(int n)
{
long[] a=new long[n];
for(int i=0;i<n;i++)
a[i]=nl();
return a;
}
public static void sieve()
{
int n=prime.length;
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*2; i <n; i += p)
prime[i] = false;
}
}
}
public static String rev(String s)
{
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
static InputReader in;
static PrintWriter w;
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 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);
}
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 493c12e7195b17b7ab823e2be394e3e2 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProtectSheep {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String[] rowsColumns = bufferedReader.readLine().split(" ");
int rows = Integer.parseInt(rowsColumns[0]);
int columns = Integer.parseInt(rowsColumns[1]);
char[][] matrix = new char[rows][columns];
for (int i = 0; i < rows; i++) {
String line = bufferedReader.readLine();
for (int j = 0; j < columns; j++) {
matrix[i][j] = line.charAt(j);
}
}
boolean canProtect = canProtect(rows, columns, matrix);
if (!canProtect) {
System.out.println("No");
return;
}
System.out.println("Yes");
for (int i = 0; i < rows; i++) {
System.out.println(matrix[i]);
}
}
private static boolean canProtect(int rows, int columns, char[][] matrix) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
char c = matrix[i][j];
if (c != 'W') {
continue;
}
if (i > 0 && matrix[i - 1][j] == 'S') {
return false;
} else if (i < rows - 1 && matrix[i + 1][j] == 'S') {
return false;
} else if (j > 0 && matrix[i][j - 1] == 'S') {
return false;
} else if (j < columns - 1 && matrix[i][j + 1] == 'S') {
return false;
}
if (i > 0 && matrix[i - 1][j] == '.') {
matrix[i - 1][j] = 'D';
}
if (i < rows - 1 && matrix[i + 1][j] == '.') {
matrix[i + 1][j] = 'D';
}
if (j > 0 && matrix[i][j - 1] == '.') {
matrix[i][j - 1] = 'D';
}
if (j < columns - 1 && matrix[i][j + 1] == '.') {
matrix[i][j + 1] = 'D';
}
}
}
return true;
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 149fd048fd5bd726108a89858b56f995 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ProtectSheep {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String[] rowsColumns = bufferedReader.readLine().split(" ");
int rows = Integer.parseInt(rowsColumns[0]);
int columns = Integer.parseInt(rowsColumns[1]);
char[][] matrix = new char[rows][columns];
for (int i = 0; i < rows; i++) {
String line = bufferedReader.readLine();
for (int j = 0; j < columns; j++) {
matrix[i][j] = line.charAt(j);
}
}
boolean canProtect = canProtect(rows, columns, matrix);
if (!canProtect) {
System.out.println("No");
return;
}
System.out.println("Yes");
for (int i = 0; i < rows; i++) {
for (char c : matrix[i]) {
System.out.print(c);
}
System.out.println();
}
}
private static boolean canProtect(int rows, int columns, char[][] matrix) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
char c = matrix[i][j];
if (c != 'W') {
continue;
}
if (i > 0 && matrix[i - 1][j] == 'S') {
return false;
} else if (i < rows - 1 && matrix[i + 1][j] == 'S') {
return false;
} else if (j > 0 && matrix[i][j - 1] == 'S') {
return false;
} else if (j < columns - 1 && matrix[i][j + 1] == 'S') {
return false;
}
if (i > 0 && matrix[i - 1][j] == '.') {
matrix[i - 1][j] = 'D';
}
if (i < rows - 1 && matrix[i + 1][j] == '.') {
matrix[i + 1][j] = 'D';
}
if (j > 0 && matrix[i][j - 1] == '.') {
matrix[i][j - 1] = 'D';
}
if (j < columns - 1 && matrix[i][j + 1] == '.') {
matrix[i][j + 1] = 'D';
}
}
}
return true;
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | e47ed912f60f266f4f10f3a228ecec97 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ProtectSheep {
private char[][] matrix;
private boolean[][] availability;
private int rows;
private int columns;
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String[] rowsColumns = bufferedReader.readLine().split(" ");
int rows = Integer.parseInt(rowsColumns[0]);
int columns = Integer.parseInt(rowsColumns[1]);
List<String> lines = new ArrayList<>();
for (int i = 0; i < rows; i++) {
lines.add(bufferedReader.readLine());
}
System.out.println(new ProtectSheep().run(rows, columns, lines));
}
public String run(int rows, int columns, List<String> lines) {
this.rows = rows;
this.columns = columns;
matrix = new char[rows][columns];
availability = new boolean[rows][columns];
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
for (int j = 0; j < line.length(); j++) {
matrix[i][j] = line.charAt(j);
}
}
boolean canProtect = canProtect();
if (!canProtect) {
return "No";
}
StringWriter out = new StringWriter();
out.write("Yes");
out.write("\n");
for (int i = 0; i < rows; i++) {
for (char c : matrix[i]) {
out.write(c);
}
if (i < rows - 1) {
out.write("\n");
}
}
return out.toString();
}
private boolean canProtect() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
char c = matrix[i][j];
if (c != 'W') {
continue;
}
if (i > 0 && matrix[i - 1][j] == 'S') {
return false;
} else if (i < rows - 1 && matrix[i + 1][j] == 'S') {
return false;
} else if (j > 0 && matrix[i][j - 1] == 'S') {
return false;
} else if (j < columns - 1 && matrix[i][j + 1] == 'S') {
return false;
}
if (i > 0 && matrix[i - 1][j] == '.') {
matrix[i - 1][j] = 'D';
}
if (i < rows - 1 && matrix[i + 1][j] == '.') {
matrix[i + 1][j] = 'D';
}
if (j > 0 && matrix[i][j - 1] == '.') {
matrix[i][j - 1] = 'D';
}
if (j < columns - 1 && matrix[i][j + 1] == '.') {
matrix[i][j + 1] = 'D';
}
}
}
return true;
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 118ad56cfdff7feab84407027e2cbc07 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String args[])
{
// String s=fs.next();
//char c[]=s.toCharArray();
//int len=s.length();
InputStream in=System.in;
FastScanner fs=new FastScanner(in);
PrintWriter out=new PrintWriter(System.out);
int R=fs.nextInt();
int C=fs.nextInt();
char arr[][]=new char[R][C];
for(int i=0;i<R;i++)
{ String s=fs.next();
arr[i]=s.toCharArray();
}
int tr=1;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
{
if(arr[i][j]=='W')
{
if((i+1<R&&arr[i+1][j]=='S')||(i-1>=0&&arr[i-1][j]=='S')||(j+1<C&&arr[i][j+1]=='S')||(j-1>=0&&arr[i][j-1]=='S'))
tr=0;
}
else if(arr[i][j]=='.')
arr[i][j]='D';
}
if(tr==0)
out.println("No");
else {out.println("Yes");
for(int i=0;i<R;i++)
out.println(arr[i]);
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream f) {
try {
br = new BufferedReader(new InputStreamReader(f));
} 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());
}
char [] charArray()
{
return next().toCharArray();
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | a59028a4a4f80846d48c425d1855f327 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Collections.*;
import static java.util.Arrays.*;
public class Main {
/**
* Solution
*/
static class Solution {
public void solve(Scanner in, PrintWriter out) {
int r = in.nextInt();
int c = in.nextInt();
char[][] matrix = new char[r][];
for (int i = 0; i < r; i++) {
matrix[i] = in.next().toCharArray();
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if(matrix[i][j] == '.')
matrix[i][j] = 'D';
}
}
for(int i = 0; i < r; ++i) {
for (int j = 1; j < c; j++) {
if((matrix[i][j] == 'W' && matrix[i][j - 1] == 'S') || (matrix[i][j] == 'S' && matrix[i][j - 1] == 'W')) {
out.print("No");
return;
}
}
}
for (int i = 0; i < c; i++) {
for (int j = 1; j < r; j++) {
if((matrix[j][i] == 'W' && matrix[j - 1][i] == 'S') || (matrix[j][i] == 'S' && matrix[j - 1][i] == 'W')) {
out.print("No");
return;
}
}
}
out.print("Yes\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
out.print(matrix[i][j]);
}
out.print("\n");
}
}
}
/**
* Online judge checker
*/
public static void main(String[] args) {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
if (onlineJudge) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner inputReader = new Scanner(inputStream);
PrintWriter printWriter = new PrintWriter(outputStream);
Solution solution = new Solution();
solution.solve(inputReader, printWriter);
printWriter.close();
} else {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("./src/com/company/Files/in.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream outputStream = System.out;
Scanner inputReader = new Scanner(inputStream);
PrintWriter printWriter = new PrintWriter(outputStream);
Solution solution = new Solution();
byte test = 1;
while (true) {
try {
if (!inputReader.bufferedReader.ready()) break;
} catch (IOException e) {
e.printStackTrace();
}
printWriter.print("Test#" + test + ":\n");
solution.solve(inputReader, printWriter);
printWriter.print("\n\n");
test++;
}
printWriter.close();
}
}
/**
* Fast input
*/
private static class Scanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
private Scanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringTokenizer = null;
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | e0fd64bce0fa2b718e4dd87e8c6aed2a | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Collections.*;
import static java.util.Arrays.*;
public class Main {
/**
* Solution
*/
static class Solution {
public void solve(Scanner in, PrintWriter out) {
int r = in.nextInt();
int c = in.nextInt();
char[][] m = new char[r][];
for (int i = 0; i < r; i++) {
m[i] = in.next().toCharArray();
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if(m[i][j] == '.')
m[i][j] = 'D';
}
}
for(int i = 0; i < r; ++i) {
for (int j = 1; j < c; j++) {
if((m[i][j] == 'W' && m[i][j - 1] == 'S') || (m[i][j] == 'S' && m[i][j - 1] == 'W')) {
out.print("No");
return;
}
}
}
for (int i = 0; i < c; i++) {
for (int j = 1; j < r; j++) {
if((m[j][i] == 'W' && m[j - 1][i] == 'S') || (m[j][i] == 'S' && m[j - 1][i] == 'W')) {
out.print("No");
return;
}
}
}
out.print("Yes\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
out.print(m[i][j]);
}
out.print("\n");
}
}
}
public static void main(String[] args) {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
if (onlineJudge) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner inputReader = new Scanner(inputStream);
PrintWriter printWriter = new PrintWriter(outputStream);
Solution solution = new Solution();
solution.solve(inputReader, printWriter);
printWriter.close();
} else {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("./src/com/company/Files/in.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream outputStream = System.out;
Scanner inputReader = new Scanner(inputStream);
PrintWriter printWriter = new PrintWriter(outputStream);
Solution solution = new Solution();
byte test = 1;
while (true) {
try {
if (!inputReader.bufferedReader.ready()) break;
} catch (IOException e) {
e.printStackTrace();
}
printWriter.print("Test#" + test + ":\n");
solution.solve(inputReader, printWriter);
printWriter.print("\n\n");
test++;
}
printWriter.close();
}
}
private static class Scanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
private Scanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringTokenizer = null;
}
public String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | b592d2e5b953dc208a89de0eed97e881 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes |
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
int i,j;
boolean temp=false;
String a[] = new String[r];
for(i=0;i<r;i++)
{
a[i] = sc.next();
}
for(i=0;i<r;i++)
{
for(j=0;j<a[i].length();j++)
{
if(j<c-1 && ((a[i].charAt(j)=='W' && a[i].charAt(j+1)=='S') || (a[i].charAt(j)=='S' && a[i].charAt(j+1)=='W')))
{
temp=true;
break;
}
if(i<r-1 &&((a[i].charAt(j)=='W' && a[i+1].charAt(j)=='S') || (a[i].charAt(j)=='S' && a[i+1].charAt(j)=='W')))
{
temp=true;
break;
}
}
if(temp)
break;
}
if(!temp)
System.out.println("YES");
else
System.out.println("No");
if(!temp)
{
for(i=0;i<r;i++)
{
a[i] = a[i].replace('.', 'D');
System.out.println(a[i]);
}
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 461d8f3b234ea2679fcf6ac4838d2359 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.*;
public class psh{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int i,j;
char a[][]=new char[n][m];
sc.nextLine();
for(i=0;i<n;i++){
String s=sc.nextLine();
a[i]=s.toCharArray();
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(a[i][j]=='W'){
if(i-1>=0&&a[i-1][j]=='S'){
System.out.println("No");
return;
}
if(j-1>=0&&a[i][j-1]=='S'){
System.out.println("No");
return;
}
if(i+1<n&&a[i+1][j]=='S'){
System.out.println("No");
return;
}
if(j+1<m&&a[i][j+1]=='S'){
System.out.println("No");
return;
}
}
}
}
System.out.println("Yes");
for(i=0;i<n;i++){
for(j=0;j<m;j++){
if(a[i][j]=='.')
System.out.print('D');
else
System.out.print(a[i][j]);
//a[i][j]='D';
}
System.out.println();
}
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 3872ff571a5eb69d75967853e88d1182 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] mp = new char[505][505];
Scanner sc = new Scanner(System.in);
int r = sc.nextInt(), c = sc.nextInt();
String ln;
for(int i =0;i<=r+1;i++){
for(int j=0;j<=c+1;j++)
mp[i][j] = '#';
}
for (int i=1;i<=r;i++) {
ln = sc.next();
for(int j =1;j<=c;j++) {
mp[i][j] = ln.charAt(j-1);
}
}
sc.close();
// System.out.println();
// for(int i=1;i<=r;i++) {
// for(int j=1;j<=c;j++) {
// System.out.print(mp[i][j]);
// }
// if(i==r) continue;
// System.out.println();
// }
// System.out.println();
for(int i=1;i<=r;i++) {
for(int j =1;j<=c;j++) {
if(mp[i][j]=='S' && (mp[i-1][j]=='W' || mp[i+1][j]=='W' || mp[i][j-1]=='W' || mp[i][j+1]=='W')){
System.out.println("No");
return;
}
if(mp[i-1][j] != 'S' && mp[i-1][j] != 'W') mp[i-1][j] = 'D';
if(mp[i+1][j] != 'S' && mp[i+1][j] != 'W') mp[i+1][j] = 'D';
if(mp[i][j-1] != 'S' && mp[i][j-1] != 'W') mp[i][j-1] = 'D';
if(mp[i][j+1] != 'S' && mp[i][j+1] != 'W') mp[i][j+1] = 'D';
}
}
System.out.println("Yes");
for(int i = 1;i<=r;i++) {
for(int j= 1;j<=c;j++) {
System.out.print(mp[i][j]);
}
if(i == r) continue;
System.out.println();
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | 143f1c2ee4a392c5c0e3f2ac3a7e5d2e | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.*;
public class sheep {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
char[][] graph = new char[r][c];
for(int i=0;i<r;i++) {
String s = sc.next();
graph[i] = s.toCharArray();
// check horizontal adjacent
if(s.contains("SW") || s.contains("WS")) {
System.out.println("No");
return;
}
}
// check vertical adjacent
for(int i=0;i<c;i++) {
String s = "";
for(int j=0;j<r;j++) {
s += graph[j][i];
}
if(s.contains("SW") || s.contains("WS")) {
System.out.println("No");
return;
}
}
// all good
System.out.println("Yes");
for(int i=0;i<r;i++) {
String s = "";
for(int j=0;j<c;j++) {
if(graph[i][j] == '.') s += 'D';
else s += graph[i][j];
}
System.out.println(s);
}
}
} | Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | c15811eab6f87f210df54980ef4ada08 | train_001.jsonl | 1520696100 | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String[] args)
{
int[] dx={1,-1,0,0};
int[] dy={0,0,1,-1};
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
char[][] arr = new char[n][m];
for(int i=0;i<n;i++)
{
String s = scan.next();
for(int j=0;j<m;j++)
arr[i][j] = s.charAt(j);
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(arr[i][j] == 'S')
{
for(int k=0;k<4;k++)
{
if(i+dx[k]<n&&i+dx[k]>=0&&j+dy[k]<m&&j+dy[k]>=0)
{
if(arr[i+dx[k]][j+dy[k]]=='W')
{
System.out.println("No");
System.exit(0);
}
else if(arr[i+dx[k]][j+dy[k]]=='.')
arr[i+dx[k]][j+dy[k]]='D';
}
}
}
}
}
System.out.println("Yes");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
{
System.out.print(arr[i][j]);
}
System.out.println("");
}
}
}
| Java | ["6 6\n..S...\n..S.W.\n.S....\n..W...\n...W..\n......", "1 2\nSW", "5 5\n.S...\n...S.\nS....\n...S.\n.S..."] | 1 second | ["Yes\n..SD..\n..SDW.\n.SD...\n.DW...\nDD.W..\n......", "No", "Yes\n.S...\n...S.\nS.D..\n...S.\n.S..."] | NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force",
"graphs"
] | f55c824d8db327e531499ced6c843102 | First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell. | 900 | If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs. | standard output | |
PASSED | fdc8ab70b24741efb01698b1af4190a2 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int q = (2 * n) - 2;
if (n == 2) {
out.println("PS");
return;
}
String arr[] = new String[q];
int i, j, flag = 0, cou = 0;
String pref = "", suff = "", str = "";
for (i = 0; i < q; i++) {
arr[i] = in.nextString();
if (arr[i].length() == n - 1 && flag == 0) {
pref = arr[i];
flag++;
} else if (arr[i].length() == n - 1 && flag == 1)
suff = arr[i];
}
if (pref.charAt(n - 2) == suff.charAt(n - 3)) {
str = pref + suff.charAt(n - 2);
} else {
str = suff + pref.charAt(n - 2);
}
//out.println(str);
char ans[] = new char[q];
all:
for (i = 0; i < q; i++) {
for (j = i + 1; j < q; j++) {
if (arr[i].length() == arr[j].length()) {
//boolean a = ispref(str,arr[i]);
boolean b = issuff(str, arr[i]);
//boolean c = ispref(str,arr[j]);
boolean d = issuff(str, arr[j]);
if (b == false && d == false) {
break all;
} else if (b == false) {
ans[i] = 'P';
ans[j] = 'S';
cou++;
break;
} else {
ans[i] = 'S';
ans[j] = 'P';
cou++;
break;
}
}
}
}
if (cou != n - 1) {
str = suff + pref.charAt(n - 2);
all:
for (i = 0; i < q; i++) {
for (j = i + 1; j < q; j++) {
if (arr[i].length() == arr[j].length()) {
//boolean a = ispref(str,arr[i]);
boolean b = issuff(str, arr[i]);
//boolean c = ispref(str,arr[j]);
boolean d = issuff(str, arr[j]);
if (b == false && d == false) {
break all;
} else if (b == false) {
ans[i] = 'P';
ans[j] = 'S';
cou++;
break;
} else {
ans[i] = 'S';
ans[j] = 'P';
cou++;
break;
}
}
}
}
}
out.println(ans);
}
boolean issuff(String str, String pre) {
int n = str.length();
int m = pre.length();
int j, i = 0;
for (j = m - 1; j >= 0; j--) {
if (str.charAt(n - 1 - i) != pre.charAt(j))
break;
i++;
}
if (j == -1)
return true;
else return false;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void println(char[] array) {
writer.println(array);
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | e82005c7d74dda64c1e0c5f96ad0134f | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/* Name of the class has to be "Main" only if the class is public. */
public final class Codechef {
private static String ans = null;
private static List<String> getPrefixesOfThisString(String str) {
List<String> prefixes = new ArrayList<>();
StringBuilder prefixBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
prefixBuilder.append(str.charAt(i));
prefixes.add(prefixBuilder.toString());
}
return prefixes;
}
private static String reverse(String str) {
StringBuilder reverse = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reverse.append(str.charAt(i));
}
return reverse.toString();
}
private static Map<Integer, String> getLengthToPrefixOfThisString(String str) {
Map<Integer, String> lengthToPrefix = new HashMap<>();
int length = 1;
StringBuilder prefixBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
prefixBuilder.append(str.charAt(i));
lengthToPrefix.put(length, prefixBuilder.toString());
length++;
}
return lengthToPrefix;
}
private static Map<Integer, String> getLengthToSuffixOfThisString(String str) {
Map<Integer, String> lengthToSuffix = new HashMap<>();
int length = 1;
StringBuilder suffixBuilder = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
suffixBuilder.append(str.charAt(i));
lengthToSuffix.put(length, reverse(suffixBuilder.toString()));
length++;
}
return lengthToSuffix;
}
private static List<String> getSuffixesOfThisString(String str) {
List<String> suffixes = new ArrayList<>();
StringBuilder suffixBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
suffixBuilder.append(str.charAt(i));
suffixes.add(reverse(suffixBuilder.toString()));
}
return suffixes;
}
private static void checkPrefixAndSuffixMatch(List<String> prefixSuffixMix, String possibleStr) {
if (ans == null) {
Map<Integer, String> lengthToPrefix = getLengthToPrefixOfThisString(possibleStr);
Map<Integer, String> lengthToSuffix = getLengthToSuffixOfThisString(possibleStr);
// BUILD PREFIX-SUFFIX STRING
StringBuilder ansSb = new StringBuilder();
List<String> usedPrefixes = new ArrayList<>();
List<String> usedSuffixes = new ArrayList<>();
for (String prefOrSuf : prefixSuffixMix) {
String prefix = lengthToPrefix.get(prefOrSuf.length());
String suffix = lengthToSuffix.get(prefOrSuf.length());
if (prefix.equals(suffix) && prefix.equals(prefOrSuf)) {
if (!usedPrefixes.contains(prefix)) {
usedPrefixes.add(prefix);
ansSb.append("P");
} else {
usedSuffixes.add(suffix);
ansSb.append("S");
}
} else {
if (prefix.equals(prefOrSuf)) {
usedPrefixes.add(prefix);
ansSb.append("P");
} else {
if (suffix.equals(prefOrSuf)) {
usedSuffixes.add(prefix);
ansSb.append("S");
} else {
return;
}
}
}
}
if (usedPrefixes.size() == possibleStr.length() - 1 && usedSuffixes.size() == possibleStr.length() - 1) {
ans = ansSb.toString();
}
}
}
public static void main(String[] args) throws java.lang.Exception {
Scanner s = new Scanner(System.in);
int N = s.nextInt();
ans = null;
List<String> prefixSuffixMix = new ArrayList<>();
String longestPrefOrSuf1 = null;
String longestPrefOrSuf2 = null;
String shortestPrefOrSuf1 = null;
String shortestPrefOrSuf2 = null;
for (int i = 0; i < 2 * N - 2; i++) {
String str = s.next();
if (str.length() == 1) {
if (shortestPrefOrSuf1 == null) {
shortestPrefOrSuf1 = str;
} else {
shortestPrefOrSuf2 = str;
}
}
if (str.length() == N - 1) {
if (longestPrefOrSuf1 == null) {
longestPrefOrSuf1 = str;
} else {
longestPrefOrSuf2 = str;
}
}
prefixSuffixMix.add(str);
}
// FORM ALL POSSIBLE ACTUAL STRINGS
String possibleStr1 = longestPrefOrSuf1 + shortestPrefOrSuf1;
String possibleStr2 = longestPrefOrSuf1 + shortestPrefOrSuf2;
String possibleStr3 = shortestPrefOrSuf1 + longestPrefOrSuf1;
String possibleStr4 = shortestPrefOrSuf2 + longestPrefOrSuf1;
String possibleStr5 = longestPrefOrSuf2 + shortestPrefOrSuf1;
String possibleStr6 = longestPrefOrSuf2 + shortestPrefOrSuf2;
String possibleStr7 = shortestPrefOrSuf1 + longestPrefOrSuf2;
String possibleStr8 = shortestPrefOrSuf2 + longestPrefOrSuf2;
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr1);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr2);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr3);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr4);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr5);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr6);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr7);
checkPrefixAndSuffixMatch(prefixSuffixMix, possibleStr8);
System.out.println(ans);
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 5160d573876fc5dee40f364f124107aa | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static class Node {
int idx;
String word;
public Node (int idx, String word) {
this.idx = idx;
this.word = word;
}
}
private static char[] fullWord;
private static char[] res;
private static Node[] node;
private static int n;
public static void main(String args[]) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
fullWord = new char[n];
Arrays.fill(fullWord, '*');
node = new Node[2*n-2];
res = new char[2*n-2];
for(int i=0; i < 2*n-2; ++i) {
node[i] = new Node(i, br.readLine());
}
Arrays.sort(node, new Comparator <Node> () {
@Override
public int compare(Node o1, Node o2) {
return o2.word.length() - o1.word.length();
}
});
recur(0, 0);
}
private static void recur(int idx, int prev) {
if(idx == 2*n - 2) {
if(prev == 0) {
System.out.print(String.valueOf(res));
System.exit(0);
}
return;
}
int leng = node[idx].word.length();
char []defaultVal = new char[n];
for(int i=0; i<n; ++i) {
defaultVal[i] = fullWord[i];
}
if(prev == 0 || prev == -1) {
boolean pass = true;
for(int i=0; i<leng; ++i) {
if(fullWord[i] != '*' && fullWord[i] != node[idx].word.charAt(i)) {
pass = false;
break;
}
}
if(pass) {
for(int i=0; i<leng; ++i) {
fullWord[i] = node[idx].word.charAt(i);
}
res[node[idx].idx] = 'P';
recur(idx+1, prev+1);
res[node[idx].idx] = ' ';
for(int i=0; i<n; ++i) {
fullWord[i] = defaultVal[i];
}
}
}
if(prev == 0 || prev == 1) {
boolean pass2 = true;
for(int i=0; i<leng; ++i) {
int rev = n - leng + i;
if(fullWord[rev] != '*' && fullWord[rev] != node[idx].word.charAt(i)) {
pass2 = false;
break;
}
}
if(pass2) {
for(int i=0; i<leng; ++i) {
int rev = n - leng + i;
fullWord[rev] = node[idx].word.charAt(i);
}
res[node[idx].idx] = 'S';
recur(idx+1, prev-1);
res[node[idx].idx] = ' ';
for(int i=0; i<n; ++i) {
fullWord[i] = defaultVal[i];
}
}
}
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | f9afc9bceeff677630c0074799297fd3 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
What do you think? What do you think?
1st on Billboard, what do you think of it
Next is a Grammy, what do you think of it
However you think, I’m sorry, but shit, I have no fucking interest
*******************************
Higher, higher, even higher, to the point you won’t even be able to see me
https://www.a2oj.com/Ladder16.html
*******************************
300IQ as writer = Sad!
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1092C
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
String[] arr = new String[2*N-2];
String[] one = new String[N];
String[] two = new String[N];
Arrays.fill(one, "@");
for(int i=0; i < 2*N-2; i++)
{
String input = infile.readLine();
int len = input.length();
if(one[len].charAt(0) == '@')
one[len] = input;
else
two[len] = input;
arr[i] = input;
}
if(N == 2)
{
System.out.println("PS");
return;
}
res = new int[N];
//solve
String template = "???";
if(works(one[1], two[N-1], one, two))
template = one[1]+two[N-1];
else if(works(one[N-1], two[1], one, two))
template = one[N-1]+two[1];
else if(works(two[N-1], one[1], one, two))
template = two[N-1]+one[1];
else if(works(two[1], one[N-1], one, two))
template = two[1]+one[N-1];
else if(works(one[1], one[N-1], one, two));
else if(works(two[1], two[N-1], one, two));
else if(works(one[N-1], one[1], one, two));
else if(works(two[N-1], two[1], one, two));
else
{
System.out.println("wtf");
return;
}
StringBuilder sb = new StringBuilder();
char[] answer = new char[2*N-2];
Arrays.fill(answer, '?');
HashSet<String> seen = new HashSet<String>();
for(int i=0; i < 2*N-2; i++)
{
int len = arr[i].length();
if(arr[i].equals(one[len]))
{
if(arr[i].equals(two[len]))
{
char c = 'P';
if(seen.contains(arr[i]))
c = 'S';
answer[i] = c;
}
else
{
char c = 'P';
if(res[len] == 1)
c = 'S';
answer[i] = c;
}
}
else
{
char c = 'S';
if(res[len] == 1)
c = 'P';
answer[i] = c;
}
seen.add(arr[i]);
}
System.out.println(answer);
}
static int[] res;
public static boolean works(String aa, String bb, String[] one, String[] two)
{
Arrays.fill(res, 0);
String template = aa+bb;
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
for(String s: one)
push(map1, s);
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
for(String s: two)
push(map2, s);
String pref = "";
int N = template.length();
for(int i=0; i < N-1; i++)
{
pref += template.charAt(i);
if(!map1.containsKey(pref))
{
if(!map2.containsKey(pref))
return false;
pull(map2, pref);
res[pref.length()] = 1; //two is prefix
}
else
pull(map1, pref);
}
String suff = "";
for(int i=N-1; i >= 1; i--)
{
suff = template.substring(i, N);
if(!map1.containsKey(suff))
{
if(!map2.containsKey(suff))
return false;
pull(map2, suff);
}
else
{
res[suff.length()] = 1; //one is suffix
pull(map1, suff);
}
}
return true;
}
public static void push(HashMap<String, Integer> map, String k)
{
if(!map.containsKey(k))
map.put(k, 0);
map.put(k, map.get(k)+1);
}
public static void pull(HashMap<String, Integer> map, String k)
{
map.put(k, map.get(k)-1);
if(map.get(k) == 0)
map.remove(k);
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 3cdb7b716583ef43c3282ad5b874b743 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | /* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
HashMap<String,Integer> hmap=new HashMap<String,Integer> ();
ArrayList<String> a=new ArrayList<> ();
ArrayList<String> a1=new ArrayList<> ();
String str="",s2="";
int x=0;
int tot=2*n-2;
while(tot-->0)
{
String s=sc.next();
if(s.length()>x&&s.length()!=x)
{
x=s.length();
str=s;
}
if(s.length()==x)
{
s2=s;
}
a.add(s);
}
String s3="";
String s4=str;
String s5=s2;
if(str.substring(1,str.length()).contains(s2.substring(0,s2.length()-1)))
{
str+=s2.charAt(s2.length()-1);
s3=str;
}
else if(str.substring(0,str.length()-1).contains(s2.substring(1,s2.length())))
s3=s2.charAt(0)+str.substring(0,str.length());
else if(s2.substring(1,s2.length()).contains(str.substring(0,str.length()-1)))
{
s2+=str.charAt(str.length()-1);
s3=s2;
}
else if(s2.substring(0,s2.length()-1).contains(str.substring(1,str.length())))
s3=str.charAt(0)+s2.substring(0,s2.length());
//System.out.println(s3+" "+str+" "+s2);
String fs="";
for(int i=0;i<a.size();i++)
{
String get=a.get(i);
if((s3.substring(0,get.length()).contains(get))&&!a1.contains(get))
{
fs+='P';
a1.add(get);
//System.out.println(s3.substring(0,get.length()));
}
else if((s3.substring(s3.length()-get.length(),s3.length()).contains(get))&&!a1.contains(get))
{
fs+='S';
a1.add(get);
//System.out.println((s3.substring(s3.length()-get.length(),s3.length())));
}
else if((s3.substring(0,get.length()).contains(get))&&a1.contains(get))
{
fs+='S';
a1.remove(get);
//System.out.println((s3.substring(0,get.length())));
}
else if((s3.substring(s3.length()-get.length(),s3.length()).contains(get))&&a1.contains(get))
{
fs+='P';
a1.remove(get);
//System.out.println((s3.substring(s3.length()-get.length(),s3.length())));
}
}
if(fs.length()==a.size())
{
System.out.println(fs);
//System.out.println("dssd");
}
else
{ s3="";
if(s5.substring(1,s5.length()).contains(s4.substring(0,s4.length()-1)))
{
s5+=s4.charAt(s4.length()-1);
s3=s5;
}
else if(s5.substring(0,s5.length()-1).contains(s4.substring(1,s4.length())))
s3=s4.charAt(0)+s5.substring(0,s5.length());
else if(s4.substring(1,s4.length()).contains(s5.substring(0,s5.length()-1)))
{
s4+=s5.charAt(s5.length()-1);
s3=s4;
}
else if(s4.substring(0,s4.length()-1).contains(s5.substring(1,s5.length())))
s3=s5.charAt(0)+s4.substring(0,s4.length());
//System.out.println(s3+" "+str+" "+s2);
fs="";
a1.clear();
for(int i=0;i<a.size();i++)
{
String get=a.get(i);
if((s3.substring(0,get.length()).equals(get))&&!a1.contains(get))
{
fs+='P';
a1.add(get);
//System.out.println("a");
}
else if((s3.substring(s3.length()-get.length(),s3.length()).equals(get))&&!a1.contains(get))
{
fs+='S';
a1.add(get);
//System.out.println((s3.substring(s3.length()-get.length()-1,s3.length())));
}
else if((s3.substring(0,get.length()).equals(get))&&a1.contains(get))
{
fs+='S';
a1.remove(get);
//System.out.println("c");
}
else if((s3.substring(s3.length()-get.length(),s3.length()).equals(get))&&a1.contains(get))
{
fs+='P';
a1.remove(get);
//System.out.println("d");
}
}
System.out.println(fs);
}
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 38303d4868724ec090a9faf5cce23616 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class fast implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new fast(),"fast",1<<26).start();
}
public void sortbyColumn(int arr[][], int col){
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}
public void sortbyColumn(long arr[][], int col){
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<long[]>() {
@Override
// Compare values according to columns
public int compare(final long[] entry1,
final long[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}
long power(long x, long y, long p){
long res = 1;
x = x % p;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
long ncr(int n, int r, long p){
long C[]=new long[r+1];
C[0] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j-1])%p;
}
return C[r];
}
public void run(){
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=s.nextInt(),flag=0,cnt=0,f2=0;
String st[]=new String[2*(n-1)],a="",b1="",b2="",pre="",s1="",s2="";
boolean b[][]=new boolean[n-1][2];
for(int i=0;i<2*(n-1);i++){
st[i]=s.next();
if(flag==0 && st[i].length()==n-1){
b1=st[i];
flag=1;
}
else if(flag==1 && st[i].length()==n-1){
b2=st[i];
}
if(f2==0 && st[i].length()==n-2){
s1=st[i];
f2=1;
}
else if(f2==1 && st[i].length()==n-2){
s2=st[i];
}
}
if((b1.substring(0,n-2).equals(s1) && b2.substring(1).equals(s2)) || (b1.substring(0,n-2).equals(s2) && b2.substring(1).equals(s1))){
pre=b1;
}
else
pre=b2;
for(int i=0;i<2*(n-1);i++){
if(b[st[i].length()-1][0]){
a+="P";
continue;
}
else if(b[st[i].length()-1][1]){
a+="S";
continue;
}
if(st[i].equals(pre.substring(0,st[i].length()))){
a+="P";
b[st[i].length()-1][1]=true;
}
else{
a+="S";
b[st[i].length()-1][0]=true;
}
}
w.println(a);
w.close();
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | e92b362ab3bebbf3af8dd7a37e4552f8 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 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 yashk
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
ArrayList<Inp>[] set = new ArrayList[n];
for (int i = 0; i < n; i++) {
set[i] = new ArrayList<>();
}
for (int i = 0; i < 2 * (n - 1); i++) {
String s = in.nextString();
Inp inp = new Inp();
inp.s = s;
inp.idx = i;
inp.ans = ' ';
set[s.length()].add(inp);
}
// for (int i = 1; i < n; i++) {
// out.print(set[i].get(0) + " " + set[i].get(1));
// out.println();
// }
// char[] str = new char[n];
String str1 = set[n - 1].get(0).s.substring(0, n - 1) + String.valueOf(set[n - 1].get(1).s.charAt(n - 2));
boolean flag = true;
for (int i = 1; i < n; i++) {
Inp inp1 = set[i].get(0);
Inp inp2 = set[i].get(1);
if (inp1.s.equals(str1.substring(0, i)) && inp2.s.equals(str1.substring(n - i))) {
// str[i - 1] = inp1.s.charAt(i - 1);
// str[n - i] = inp2.s.charAt(0);
inp1.ans = 'P';
inp2.ans = 'S';
} else if (inp2.s.equals(str1.substring(0, i)) && inp1.s.equals(str1.substring(n - i))) {
// str[i - 1] = inp2.s.charAt(i - 1);
// str[n - i] = inp1.s.charAt(0);
inp1.ans = 'S';
inp2.ans = 'P';
} else {
flag = false;
break;
}
}
if (!flag) {
String str2 = set[n - 1].get(1).s.substring(0, n - 1) + String.valueOf(set[n - 1].get(0).s.charAt(n - 2));
// boolean flag = true;
for (int i = 1; i < n; i++) {
Inp inp1 = set[i].get(0);
Inp inp2 = set[i].get(1);
if (inp1.s.equals(str2.substring(0, i)) && inp2.s.equals(str2.substring(n - i))) {
// str[i - 1] = inp1.s.charAt(i - 1);
// str[n - i] = inp2.s.charAt(0);
inp1.ans = 'P';
inp2.ans = 'S';
} else if (inp2.s.equals(str2.substring(0, i)) && inp1.s.equals(str2.substring(n - i))) {
// str[i - 1] = inp2.s.charAt(i - 1);
// str[n - i] = inp1.s.charAt(0);
inp1.ans = 'S';
inp2.ans = 'P';
} else {
break;
}
}
}
char[] ans = new char[2 * (n - 1)];
for (int i = 1; i < n; i++) {
ans[set[i].get(0).idx] = set[i].get(0).ans;
ans[set[i].get(1).idx] = set[i].get(1).ans;
// out.println(set[i].get(0));
// out.println(set[i].get(1));
}
// out.println(str);
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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 println(char[] array) {
writer.println(array);
}
public void close() {
writer.close();
}
}
static class Inp {
String s;
int idx;
char ans;
public String toString() {
return "Inp{" +
"s='" + s + '\'' +
", idx=" + idx +
", ans=" + ans +
'}';
}
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 2ac8bb54d18ec334f0e47c77e7585e0d | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes |
import java.io.ByteArrayInputStream;
import java.util.*;
public class Prefixes {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
// Scanner sc = testData();
int n = sc.nextInt();
int stringSize = n;
if(stringSize==2) {
System.out.println("SP");
return;
}
n = 2*n-2;
String arr[] = new String[n];
for(int i = 0; i<n ; i++) {
arr[i] = sc.next();
}
String largest[] = new String[4];
int n1 = 0, n2=2;
for(int i = 0; i<n; i++) {
if(arr[i].length()==(stringSize-1)) {
largest[n1++] = arr[i];
}
if(arr[i].length()==(stringSize-2)) {
largest[n2++] = arr[i];
}
}
String original;
if((largest[0].startsWith(largest[2])&&largest[1].endsWith(largest[3]))||
(largest[0].startsWith(largest[3])&&largest[1].endsWith(largest[2]))) {
original = largest[0]+largest[1].charAt(stringSize-2);
} else {
original = largest[1]+largest[0].charAt(stringSize-2);
}
StringBuilder result = new StringBuilder();
Set<String> seen = new HashSet<>();
for(int i = 0; i<n; i++) {
if(original.startsWith(arr[i])&&!seen.contains(arr[i]))
result.append('P');
else
result.append('S');
seen.add(arr[i]);
}
System.out.println(result.toString());
}
public static Scanner testData() {
return new Scanner(new ByteArrayInputStream((
"2 a b").getBytes()));
/*
"5\n" +
"ba\n" +
"a\n" +
"abab\n" +
"a\n" +
"aba\n" +
"baba\n" +
"ab\n" +
"aba"
).getBytes()));
SPPSPSPS */
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 4176978d6f19c4366aab774f7a43f587 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new Main().run(in, out);
out.close();
}
char[] ret;
Integer[] ri;
String[] sap;
int n;
void run(FastScanner in, PrintWriter out) {
n = in.nextInt();
sap = new String[2*n-2];
for (int i = 0; i < 2*n-2; i++) sap[i] = in.next();
ret = new char[2*n-2];
ri = new Integer[2*n-2];
for (int i = 0; i < ri.length; i++) ri[i] = i;
Arrays.sort(ri, (a,b) -> sap[b].length() - sap[a].length());
// try P/S first
// if it is logically inconsistent, try S/P
ret[ri[0]] = 'P';
ret[ri[1]] = 'S';
String prefix = sap[ri[0]];
String suffix = sap[ri[1]];
if (!get(prefix, suffix)) {
ret[ri[0]] = 'S';
ret[ri[1]] = 'P';
get(suffix, prefix);
}
for (char c : ret) out.print(c);
out.println();
}
boolean get(String prefix, String suffix) {
boolean possible = true;
for (int i = 2; i < 2*n-2; i += 2) {
// if P/S is logically consistent
if (isPrefix(prefix, sap[ri[i]]) && isSuffix(suffix, sap[ri[i+1]])) {
ret[ri[i]] = 'P';
ret[ri[i+1]] = 'S';
} else if (isPrefix(prefix, sap[ri[i+1]]) && isSuffix(suffix, sap[ri[i]])) {
ret[ri[i]] = 'S';
ret[ri[i+1]] = 'P';
} else {
possible = false;
break;
}
}
return possible;
}
boolean isPrefix(String prefix, String b) {
int i = 0;
for (char c : b.toCharArray()) {
if (prefix.charAt(i++) != c) return false;
}
return true;
}
boolean isSuffix(String suffix, String b) {
for (int i = suffix.length()-1, j = b.length()-1; j >= 0; i--, j--) {
if (suffix.charAt(i) != b.charAt(j)) return false;
}
return true;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
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());
}
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 52aa41dedbdf4d72d0c46bbf2705415b | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | // No sorceries shall prevail. //
import java.util.*;
import java.io.*;
public class InVoker {
//Variables
static long mod = 1000000007;
static long mod2 = 998244353;
static FastReader inp= new FastReader();
static PrintWriter out= new PrintWriter(System.out);
public static void main(String args[]) {
InVoker g=new InVoker();
g.main();
out.close();
}
//Main
void main() {
int n=inp.nextInt();
String s[]=new String[2*n-2];
input(s,2*n-2);
StringBuilder s1=new StringBuilder("");
StringBuilder s2=new StringBuilder("");
boolean first=true;
for(int i=0;i<2*n-2;i++) {
if(s[i].length()==n-1) {
if(first) {
s1=new StringBuilder(s[i]);
s2=new StringBuilder(s[i]);
first=false;
}else {
s1.append(s[i].charAt(n-2));
s2=new StringBuilder(s[i].charAt(0)+""+s2);
}
}
}
char ans[][]=new char[2*n-2][2];
int gg=0;
if(check(s,s1.toString(),ans,0,n)) {
gg=0;
}else if(check(s,s2.toString(),ans,1,n)) {
gg=1;
}
for(int i=0;i<2*n-2;i++) {
out.print(ans[i][gg]);
}
}
boolean check(String s[], String original, char ans[][],int k, int n) {
boolean prefix[]=new boolean[n-1];
boolean suffix[]=new boolean[n-1];
for(int i=0;i<2*n-2;i++) {
int len=s[i].length();
if(!prefix[len-1] && isPrefix(original,s[i])) {
prefix[len-1]=true;
ans[i][k]='P';
}else if(!suffix[len-1] && isSuffix(original,s[i])) {
suffix[len-1]=true;
ans[i][k]='S';
}
}
int pre=0,suf=0;
for(int i=0;i<2*n-2;i++) {
if(ans[i][k]=='P') {
pre++;
}
else if(ans[i][k]=='S') {
suf++;
}
}
return pre==n-1 && suf==n-1;
}
boolean isPrefix(String original,String s) {
for(int i=0;i<s.length();i++) {
if(original.charAt(i)!=s.charAt(i)) {
return false;
}
}
return true;
}
boolean isSuffix(String original,String s) {
int n=original.length();
int l=s.length();
for(int i=l-1;i>=0;i--) {
if(original.charAt(i+(n-l))!=s.charAt(i)) {
return false;
}
}
return true;
}
/*********************************************************************************************************************************************************************************************************
* ti;. .:,:i: :,;;itt;. fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE :,:. f::::. .,ijLGDDDDDDDEEEEEEE*
*ti;. .:,:i: .:,;itt;: GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG. .::. f:,...,ijLGDDDDDDDDEEEEEE *
*ti;. .:,:i: :,;;iti, :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG .::. .f,::,ijLGDDDDDDDDEEEEEE *
*ti;. .:,:i: .,,;iti;. LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj .::. .:L;;ijfGDDDDDDDDDEEEEE *
*ti;. .:,:i: .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL .::. .:;LijLGGDDDDDDDDEEEEE *
*ti;. .:,:;: :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj .::. :,;jffGGDDDDDDDDDEEEE *
*ti;. .:,:i: .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL .::. .:;itDGGDDDDDDDDDEEEE *
*ti;. .:::;: :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf .::. :,itfGEDDDDDDDDDDDEE *
*ti;. .:::;: :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG .::. .,;jfLGKDLDDDDDDEEDD *
*ti;. .:::;: fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::. .,;tfLGDEDDDDDDDDEEE *
*ti;. :::;: fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::. .,;tfLGDDDKDDDDDDDDD *
*ti;. .::;: fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:. .,;tfLGGDDDKDDDDDDDD *
*ti;. .:.;: tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::. .,;tfLGGDDDDEDDDDDDD *
*ti;. .::;: fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::. .,;tfLGGDDDDDDEDDDDD *
*ti;. .:.;: tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::. .,;tfLGGDDDDDDDEDDDD *
*ti;. .:.,. LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:. .,;tfLGGDDDDDDDDEDDD *
*ti;. ..:.,. LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,. .,;tfLGGDDDDDDDDDKDD *
*tt;. .:.,: jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,: .,;tfLGGDDDDDDDDDDKD *
*tii,. .:.,. tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,. .,;tfLGGDDDDDDDDDDDE *
*ti;;,:. .:.,: fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,. .,;tfLGGDDDDDDDDDDDD *
*tii;,,:.. ...,. ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,: .,itfLGGDDDDDDDDDDDD *
*ti;,,,,,:. ...,. LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:. .,itfGGGDDDDDDDDDDDD *
*tii,,,,::::. ...,: .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:. .,ijfGGGDDDDDDDDDDDD *
*ti;:::::::::.. .:.,: LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,: .,ijLGGGDDDDDDDDDDDD *
*tt;. .::::::::.. ...,: :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:. .:,;,:. .,ijLGGDDDDDDDDDDDDD *
*tt;. .:::::::.. ...,: GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,. :,,,:...,ijLGGGDDDDDDDDDDDD *
*tt;. .....::::.. ...,: fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi. .,;,:::,ijLGGGDDDDDDDDDDDD *
*tt;. ....:::::. ...,. iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff. .:,;,,;ijLGGGDDDDDDDDDDDD *
*tt;. ....::::.. .:.,: .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG. .:,;;iijLGGGDDDDDDDDDDDD *
*tt;. .....:::.. ...,. .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG. :,iitjLGGGDDDDDDDDDDDD *
*tti. .....:::.. ...,. GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf. .,;tjfLGGDDDDDDDDDDDD *
*tti. ....::::.. ...,. fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf. :;ijfLGGDDDDDDDDDDDD *
*tti. ....::::.. ...,. LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf: .,itfLGGDDDDDDDDDDDD *
*tti. .....:::.. ...,. fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi .,;tfLGGGDDDDDDDDDDD *
*tti. .....:::.. ...,. iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL .,;tjLLGGDDDDDDDDDDD *
*tti. ....::::......:. LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG .,;tjLLGGDDDDDDDDDDD *
*tti. ...::::::..,. :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL .,;tjLLGGDDDDDDDDDDD *
*tti. ....::::::,. GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf .,;tjLLGGDDDDDDDDDDD *
*tti. ....:::,,. .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf .:;tjLLGGGDDDDDDDDDD *
*tti. ...::,,,:. GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf .:;tjLLGGDDDDDDDDDDD *
*jti. ...::,,,,:. .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf: .,;tfLLGGDDDDDDDDDDD *
*tti. ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi .,;tfLLGGGDDDDDDDDDD *
*tti. ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL .,;tfLGGGDDDDDDDDDDD *
*jti. ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG .,;tfLGGGGDDDDDDDDDD *
*jti. ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL .,;tfLGGGGDDDDDDDDDD *
*jti. ...:. .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:. .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,: .,;tfGGGGDDDDDDDDDDD *
*jti. ...:. GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK, ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD *
*jti. ...:. fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG .:,,,:::,;tfGGGDDDDDDDDDDDD *
*jti. ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL .:,;,,,;tfGGGDDDDDDDDDDDD *
*jti. ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf .:,;;;itfGGGDDDDDDDDDDDD *
*jti. ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf .,;iitfGGGDDDDDDDDDDDD *
*jti. ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL .:;itfGGGDDDDDDDDDDDD *
*jji. ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j. KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf .,;tfGGGDDDDDDDDDDDD *
*jji. ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;.................................. . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL, .:;tfGGGDDDDDDDDDDDD *
*jji. .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................:: KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj .:;tfGGDDDDDDDDDDDDD *
*jji. .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG .:;tfGGGDDDDDDDDDDDD *
*jji. . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG .;tjfLLGDDDDDDDDDDDDDDD *
*jji. i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL ,fGGGDDDDDDDDEEEDDDDDDDDDD *
*jji. .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD *
*jji. i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD *
*jji. .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD *
*jji. .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL; .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD *
*jji. :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED *
*jji. i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE *
*jji. i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD *
*jji. .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG *
*jjt. :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG *
*jji. ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG *
*jjt. f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG *
*jjt. ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG *
*fji. ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL *
*fji. t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL *
*fjt: .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL *
*fjji;:. .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG *
*fjjtii;,:. :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG *
*fjtiiiii;;:. j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG *
*fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG *
*fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD *
*jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD *
*fjt. .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD *
*fjt. .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD *
*fjt. .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD *
*fjt: :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD *
*fjt: t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD *
*jjt. f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD *
*fjt:. ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG *
*fjt:. ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; *
*fjt:. f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, *
*fjt:. .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, *
*fjt:. .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, *
*fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, *
*fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, *
*fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
*fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
*fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; *
***********************************************************************************************************************************************************************************************************/
// Classes
static class Edge implements Comparable<Edge>{
int l,r;
Edge(){}
Edge(int l,int r){
this.l=l;
this.r=r;
}
@Override
public int compareTo(Edge e) {
return (l-e.l)!=0?l-e.l:r-e.r;
}
}
static class Segment implements Comparable<Segment> {
long l, r, initialIndex;
Segment () {}
Segment (long l_, long r_, long d_) {
this.l = l_;
this.r = r_;
this.initialIndex = d_;
}
@Override
public int compareTo(Segment o) {
return (int)((l - o.l) !=0 ? l-o.l : initialIndex - o.initialIndex);
}
}
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 s="";
try {
s=br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
// Functions
static long gcd(long a, long b) {
return b==0?a:gcd(b,a%b);
}
static int gcd(int a, int b) {
return b==0?a:gcd(b,a%b);
}
static void reverse(long[] A,int l,int r) {
int i=l,j=r-1;
while(i<j) {
long t=A[i];
A[i]=A[j];
A[j]=t;
i++;j--;
}
}
static void reverse(int[] A,int l,int r) {
int i=l,j=r-1;
while(i<j) {
int t=A[i];
A[i]=A[j];
A[j]=t;
i++;j--;
}
}
//Input Arrays
static void input(long a[], int n) {
for(int i=0;i<n;i++) {
a[i]=inp.nextLong();
}
}
static void input(int a[], int n) {
for(int i=0;i<n;i++) {
a[i]=inp.nextInt();
}
}
static void input(String s[],int n) {
for(int i=0;i<n;i++) {
s[i]=inp.next();
}
}
static void input(int a[][], int n, int m) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=inp.nextInt();
}
}
}
static void input(long a[][], int n, int m) {
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
a[i][j]=inp.nextLong();
}
}
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 29a086b8ad986367ebedfff370683466 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
static class Pair
{
int x;
int y;
// Constructor
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
static class Compare
{
static void compare(Pair arr[], int n)
{
// Comparator to sort the pair according to second element
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.y - p2.y;
}
});
}
}
public static long pow(long a, long b)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a);
b--;
}
a=(a*a);
b /= 2;
}
return result;
}
public static BigInteger fact(long num)
{
BigInteger fact=new BigInteger("1");
int i=0;
for(i=1; i<=num; i++)
{
BigInteger bg=BigInteger.valueOf(i);
fact=fact.multiply(bg);
}
return fact;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static long lcm(int a,int b)
{
return a * (b / gcd(a, b));
}
public static long sum(int h)
{
return (h*(h+1)/2);
}
/* public static void dfs(int parent,boolean[] visited)
{
ArrayList<Integer> arr=new ArrayList<Integer>();
arr=graph.get(parent);
visited[parent]=true;
bigParent=parent;
for(int i=0;i<arr.size();i++)
{
int num=arr.get(i);
if(visited[num]==false)
{
color[num]=count++;
dfs(num,visited);
}
}
}
static int count=0;
static int[] storing1;
*/ static int[] storing2;
static ArrayList<ArrayList<Integer>> graph;
public static void main(String args[])throws IOException
{
InputReader in=new InputReader(System.in);
OutputWriter out=new OutputWriter(System.out);
// long a=pow(26,1000000005);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ArrayList<Character> ar=new ArrayList<>();
ArrayList<Integer> ar1=new ArrayList<>();
ArrayList<Integer> ar2=new ArrayList<>();
ArrayList<Integer> ar3=new ArrayList<>();
ArrayList<Integer> ar4=new ArrayList<>();
TreeSet<String> ts=new TreeSet<>();
TreeSet<String> ts1=new TreeSet<>();
TreeSet<String> pre=new TreeSet<>();
HashMap<Integer,Integer> hash=new HashMap<Integer,Integer>();
HashMap<Long,Integer> hash1=new HashMap<Long,Integer>();
HashMap<Long,Integer> hash2=new HashMap<Long,Integer>();
boolean[] prime=new boolean[100001];
for(int i=2;i*i<=100000;i++)
{
if(prime[i]==false)
{
for(int j=2*i;j<=100000;j++)
{
prime[j]=true;
}
}
}
int n=i();
String[] s=new String[2*n-2];
String[] s1=new String[2*n-2];
for(int i=0;i<2*n-2;i++)
{
s[i]=s();
s1[i]=s[i];
}
int index=0,index1=0;
for(int i=0;i<2*n-2;i++)
{
for(int j=i+1;j<2*n-2;j++)
{
if(s[i].length()==n-1 && s[j].length()==n-1)
{
index=i;
index1=j;
}
}
}
TreeSet<String> post=new TreeSet<>();
String s2="";
for(int i=0;i<n-1;i++)
{
s2=s2+s[index].charAt(i);
pre.add(s2);
}
int flag=0;
String s4="";
for(int i=0;i<n-1;i++)
{
s4=s[index1].charAt(n-2-i)+s4;
post.add(s4);
}
for(int i=0;i<2*n-2;i++)
{
if(pre.contains(s[i]) && ts1.contains(s[i])==false)
{
ar.add('P');
// System.out.print("P");
}
else
{
if(post.contains(s[i])==false)
{
flag=1;
}
ar.add('S');
}
ts1.add(s[i]);
}
if(flag!=1)
{
for(int i=0;i<ar.size();i++)
System.out.print(ar.get(i)+"");
}
else
{
String s3="";
pre.clear();
for(int i=0;i<n-1;i++)
{
s3=s3+s[index1].charAt(i);
pre.add(s3);
}
ts1.clear();
for(int i=0;i<2*n-2;i++)
{
if(pre.contains(s[i]) && ts1.contains(s[i])==false)
{
System.out.print("P");
}
else
System.out.print("S");
ts1.add(s[i]);
}
}
pln("");
}
/**/
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static long l()
{
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value)
{
System.out.println(value);
}
public static int i()
{
return in.Int();
}
public static String s()
{
return in.String();
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 20e3511d336980f816f0a390a93c2f88 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.*;
import java.io.*;
public class PA {
public static boolean checkPrefix(String p , String s)
{
for(int i = 0 ; i < p.length() ; i++)
{
if(p.charAt(i) != s.charAt(i))
return false;
}
return true;
}
public static boolean checkSuffix(String p , String s)
{
for(int i = p.length()-1 , j = 0 ; i >=0 ; i-- , j++)
{
if(p.charAt(i) != s.charAt(s.length()-1-j))
return false;
}
return true;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
String arr1[] = new String[2*t-2];
String arr2[] = new String[2*t-2];
for(int i = 0 ; i < 2*t-2 ; i++)
arr1[i] = arr2[i] = br.readLine();
for(int i = 0 ; i < arr2.length ; i++)
{
for(int j = 0 ; j < arr2.length-1 ; j++)
{
if(arr2[j].length() > arr2[j+1].length())
{
String tmp = arr2[j];
arr2[j] = arr2[j+1];
arr2[j+1] = tmp;
}
}
}
String s1 = arr2[arr2.length-1]+arr2[arr2.length-2].charAt(arr2[arr2.length-2].length()-1) , s2 = arr2[arr2.length-2]+arr2[arr2.length-1].charAt(arr2[arr2.length-1].length()-1);
boolean flag1 = true , flag2 = true;
StringBuilder r1 = new StringBuilder();
StringBuilder r2 = new StringBuilder();
HashSet<String> ss1 = new HashSet<>();
HashSet<String> ss2 = new HashSet<>();
for(int i = 0 ; i < arr1.length ; i++)
{
if(!checkPrefix(arr1[i] , s1) && !checkSuffix(arr1[i] , s1))
{
flag1 = false;
}
else
{
if(checkPrefix(arr1[i] , s1) && checkSuffix(arr1[i] , s1)) {
if(!ss1.contains(arr1[i]))
{
r1 .append( "P");
}
else
{
r1 .append( "S");
}
ss1.add(arr1[i]);
}
else
{
if(checkPrefix(arr1[i] , s1))
r1 .append( "P");
else
r1 .append( "S");
ss1.add(arr1[i]);
}
}
if(!checkPrefix(arr1[i] , s2) && !checkSuffix(arr1[i] , s2))
{
flag2 = false;
}
else
{
if(checkPrefix(arr1[i] , s2) && checkSuffix(arr1[i] , s2)) {
if(!ss2.contains(arr1[i]))
{
r2 .append( "P");
}
else
{
r2 .append( "S");
}
ss2.add(arr1[i]);
}
else
{
if(checkPrefix(arr1[i] , s2))
r2 .append( "P");
else
r2 .append( "S");
ss2.add(arr1[i]);
}
}
}
if(flag1) {
out.println(r1 );
}
else
out.println(r2 );
out.flush();
out.close();
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | e191b716a8e05721b5f99414479602c9 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.*;
import java.util.*;
public class ProblemC {
public static InputStream inputStream = System.in;
public static OutputStream outputStream = System.out;
public static void main(String[] args) {
MyScanner scanner = new MyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
int n = scanner.nextInt();
List<String> list = new ArrayList<>();
String str1 = null, str2 = null;
for (int i = 0; i < 2 * n - 2; i++) {
String s = scanner.next();
if (s.length() == n - 1) {
if (str1 == null) {
str1 = s;
} else {
str2 = s;
}
}
list.add(s);
}
Set<Integer> prefixes = new HashSet<>();
Set<Integer> suffixes = new HashSet<>();
StringBuilder stringBuilder = new StringBuilder();
String str = str1 + str2.charAt(str2.length() - 1);
boolean cant = false;
for (int i = 0; i < 2 * n - 2; i++) {
if (prefixes.contains(list.get(i).length())) {
if (isSuffix(str, list.get(i))) {
stringBuilder.append("S");
} else {
cant = true;
break;
}
} else if (suffixes.contains(list.get(i).length())) {
if (isPrefix(str, list.get(i))) {
stringBuilder.append("P");
} else {
cant = true;
break;
}
} else {
if (isPrefix(str, list.get(i))) {
stringBuilder.append("P");
prefixes.add(list.get(i).length());
} else {
stringBuilder.append("S");
suffixes.add(list.get(i).length());
}
}
}
if (cant) {
str = str2 + str1.charAt(str1.length() - 1);
prefixes.clear();
suffixes.clear();
stringBuilder = new StringBuilder();
for (int i = 0; i < 2 * n - 2; i++) {
if (prefixes.contains(list.get(i).length())) {
if (isSuffix(str, list.get(i))) {
stringBuilder.append("S");
}
} else if (suffixes.contains(list.get(i).length())) {
if (isPrefix(str, list.get(i))) {
stringBuilder.append("P");
}
} else {
if (isPrefix(str, list.get(i))) {
stringBuilder.append("P");
prefixes.add(list.get(i).length());
} else {
stringBuilder.append("S");
suffixes.add(list.get(i).length());
}
}
}
out.println(stringBuilder.toString());
} else {
out.println(stringBuilder.toString());
}
out.flush();
}
private static boolean isPrefix(String str, String prefix) {
for (int i = 0; i < prefix.length(); i++) {
if (str.charAt(i) != prefix.charAt(i)) {
return false;
}
}
return true;
}
private static boolean isSuffix(String str, String suffix) {
for (int i = suffix.length() - 1; i >= 0; i--) {
if (str.charAt(i + (str.length() - suffix.length())) != suffix.charAt(i)) {
return false;
}
}
return true;
}
private static class MyScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
private MyScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
private String next() {
while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
private String nextLine() {
String str = "";
try {
str = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static class Pair<F, S> {
private F first;
private S second;
public Pair() {}
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 724c59932dcdb608b0762543066e84e6 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.awt.Rectangle;
import java.io.*;
import java.util.*;
public class ProbC {
BufferedReader in;
StringTokenizer str;
PrintWriter out;
String SK;
String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
String nexts()throws IOException {
return in.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
char[] charArray() throws IOException{
return next().toCharArray();
}
public static void main(String[] args) throws IOException {
new ProbC().run();
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter("output.txt");
solve();
out.close();
}
void solve() throws IOException {
int n = nextInt();
A str[]=new A[2*n-2];
A stro[]=new A[2*n-2];
for (int i = 0; i < 2*n-2; i++) {
stro[i]=new A();
str[i]=new A();
stro[i].a=next();
str[i].a=stro[i].a;
}
Arrays.sort(str);
String str1B=str[2*n-3].a;
String str2B=str[2*n-4].a;
String str1S=str[0].a;
String str2S=str[1].a;
// out.println(str1B+" "+str2B+" "+str1S+" "+str2S);
String guess[]=new String[4];
int c=0;
if((str1S+str1B).equals(str2B+str2S)){
guess[c++]=str1S+str1B;
}
if((str2S+str1B).equals(str2B+str1S)){
guess[c++]=str2S+str1B;
}
if((str1B+str1S).equals(str2S+str2B)){
guess[c++]=str1B+str1S;
}
if((str1B+str2S).equals(str1S+str2B)){
guess[c++]=str1B+str2S;
}
/*if(str1B.startsWith(str1S) && str2B.endsWith(str2S)){
guess=str1B+str2S;
}
else if(str1B.startsWith(str2S) && str2B.endsWith(str1S)){
guess=str1B+str1S;
}
else if(str2B.startsWith(str1S) && str1B.endsWith(str2S)){
guess=str2B+str2S;
}
else if(str2B.startsWith(str2S) && str1B.endsWith(str1S)){
guess=str2B+str1S;
}
*/
//out.println(guess);
for (int j = 0; j < 4; j++) {
String res="";
boolean usedP[]=new boolean[n];
boolean usedS[]=new boolean[n];
for (int i = 0; i < 2*n-2; i++) {
int len=stro[i].a.length();
if(!usedP[len] && guess[j].startsWith(stro[i].a)){
res+="P";
usedP[len]=true;
}
else if(!usedS[len] && guess[j].endsWith(stro[i].a)){
res+="S";
usedS[len]=true;
}
}
boolean ok=true;
for (int i = 1; i < n; i++) {
if(!usedS[i] || !usedP[i]){
ok=false;
break;
}
}
if(ok){
out.println(res);
return;
}
}
}
}
class A implements Comparable<A> {
String a;
public int compareTo(A next) {
if (a.length()<next.a.length()) {
return -1;
}
else if (a.length()>next.a.length()) {
return 1;
}
if (a.length()==next.a.length()) {
return 0;
}
return 0;
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 06665930c5da2905c2f2dc904b4bc130 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.*;
public class div573{
public static void main(String sp[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = (2*n)-2;
ArrayList<String> al = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
for(int i=0;i<q;i++){
String st = sc.next();
al.add(st);
if(st.length()==n-1)
temp.add(st);
}
String st="";
if(n==2){
System.out.println("SP");
return;
}
String s1=temp.get(0);
String s2=temp.get(1);
st=s1+s2.charAt(n-2)+"";
ArrayList<String> p = new ArrayList<>();
ArrayList<String> s = new ArrayList<>();
String df="";
for(int i=0;i<n-1;i++){
df+=st.charAt(i);
p.add(df);
s.add(st.substring(i+1));
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<q;i++){
String val=al.get(i);
boolean f=false;
for(int j=0;j<p.size();j++){
if(val.equals(p.get(j))){
f=true;
sb.append("P");
p.remove(val);
break;
}
}
if(f==false){
for(int j=0;j<s.size();j++){
if(val.equals(s.get(j))){
sb.append("S");
s.remove(val);
break;
}
}}
}
if(sb.length()==q)
System.out.println(sb.toString());
if(sb.length()!=q){
st=s2+s1.charAt(n-2)+"";
p = new ArrayList<String>();
s = new ArrayList<String>();
df="";
for(int i=0;i<n-1;i++){
df+=st.charAt(i);
p.add(df);
s.add(st.substring(i+1));
}
sb = new StringBuilder();
for(int i=0;i<q;i++){
String val=al.get(i);
boolean f=false;
for(int j=0;j<p.size();j++){
if(val.equals(p.get(j))){
f=true;
sb.append("P");
p.remove(val);
break;
}
}
if(f==false){
for(int j=0;j<s.size();j++){
if(val.equals(s.get(j))){
sb.append("S");
s.remove(val);
break;
}
}}
}
System.out.println(sb.toString());
}
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 350179123241bd37dbda2888c18ed3b3 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
void run(){
out.println(work());
out.flush();
}
String work() {
int n=in.nextInt();
String[] strs=new String[2*n-2];
String s1="",s2="";
for(int i=0;i<2*n-2;i++){
strs[i]=in.next();
if(s1.length()==0&&strs[i].length()==(n+1)/2){
s1=strs[i];
}else if(strs[i].length()==(n+1)/2){
s2=strs[i];
}
}
String ret1="",ret2="";
if(n%2==0){
ret1=s1+s2;
ret2=s2+s1;
}else{
if(s1.charAt(0)==s2.charAt((n+1)/2-1)){
ret1=s2+s1.substring(1,(n+1)/2);
}
if(s2.charAt(0)==s1.charAt((n+1)/2-1)){
ret2=s1+s2.substring(1,(n+1)/2);
}
}
if(ret1.length()==0) ret1=ret2;
// out.println(ret1);out.println(ret2);
//str1
boolean f=true;
StringBuilder sb=new StringBuilder();
int[] visited=new int[n];
for(int i=0;i<2*n-2;i++){
int l=strs[i].length();
if(visited[l]==1){
if(ret1.substring(n-l,n).equals(strs[i])){
sb.append("S");
}else{
f=false;
break;
}
}else if(visited[l]==2){
if(ret1.startsWith(strs[i])){
sb.append("P");
}else{
f=false;
break;
}
}else{
if(ret1.startsWith(strs[i])){
sb.append("P");
visited[l]=1;
}else if(ret1.substring(n-l,n).equals(strs[i])){
sb.append("S");
visited[l]=2;
}else{
f=false;
break;
}
}
}
if(f){
return sb.toString();
}
// if(n==99) {out.println(s1);out.println(s2);out.println(ret1);out.println(ret2);out.println(ret1.length());}
// if(n==99) out.println(sb.toString());
sb=new StringBuilder();
visited=new int[n];
for(int i=0;i<2*n-2;i++){
int l=strs[i].length();
if(visited[l]==1){
sb.append("S");
}else if(visited[l]==2){
sb.append("P");
}else{
if(ret2.startsWith(strs[i])){
sb.append("P");
visited[l]=1;
}else{
sb.append("S");
visited[l]=2;
}
}
}
return sb.toString();
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 84adecf57388f8f1cc1b299e57e33383 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.*;
public class Main {
static int n;
static String suffix = null;
static String prefix = null;
static String[]sp;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
scanner.nextLine();
sp = new String[2 * n - 2];
for (int i = 0; i < 2 * n - 2; i++) {
sp[i] = scanner.nextLine();
if (sp[i].length() == n - 1) {
if (suffix == null)
suffix = sp[i];
else
prefix = sp[i];
}
}
init();
boolean again=false;
for (int i = 0; i < 2 * n - 2; i++) {
if(!marked[i]) {
again = true;
break;
}
}
if(again){
String s = prefix;
prefix = suffix;
suffix = s;
init();
}
for (int i = 0; i < 2 * n - 2; i++) {
System.out.print(ans[i]);
}
}
static boolean marked[] ;
static char ans[] ;
private static void init() {
marked = new boolean[2 * n - 2];
ans = new char[2 * n - 2];
for (int j = 0; j < n - 1; j++) {
String s = prefix.substring(0, j + 1);
for (int k = 0; k < 2 * n - 2; k++) {
if (sp[k].equals(s) && !marked[k]) {
marked[k] = true;
ans[k] = 'P';
break;
}
}
}
for (int j = n - 2; j > -1; j--) {
String s = suffix.substring(j, n - 1);
for (int k = 0; k < 2 * n - 2; k++) {
if (sp[k].equals(s) && !marked[k]) {
marked[k] = true;
ans[k] = 'S';
break;
}
}
}
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | aab9b36b5a439e94c77deb7308f13c1c | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.util.*;
import java.util.function.BiFunction;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String longestPrefix = "", longestSuffix = "";
int n = input.nextInt();
String[] arr = new String[2*n-2];
for(int i = 0 ; i < 2*n-2 ; i++) {
arr[i]= input.next();
if(arr[i].length() == n-1){
if(longestPrefix.isEmpty()) {
longestPrefix = arr[i];
}else{
longestSuffix = arr[i];
}
}
}
char[] answer = calculateAnswer(arr, populatePrefixeMap(longestPrefix), populateSuffixeMap(longestSuffix));
if(answer == null) {
answer = calculateAnswer(arr, populatePrefixeMap(longestSuffix), populateSuffixeMap(longestPrefix));
assert answer != null;
}
System.out.println(new String(answer));
}
public static char[] calculateAnswer(
String[] dict, Map<String, Character> prefixMap, Map<String, Character> suffixMap
) {
char[] answer = new char[dict.length];
for(int i = 0 ; i < dict.length ; i++) {
if(prefixMap.containsKey(dict[i])) {
answer[i] = 'P';
prefixMap.remove(dict[i]);
} else if(suffixMap.containsKey(dict[i])) {
answer[i] = 'S';
suffixMap.remove(dict[i]);
} else {
return null;
}
}
return answer;
}
public static Map<String, Character> populatePrefixeMap(String longestPrefix) {
return populateMap(longestPrefix, (arr, i) -> new String(arr, 0, i + 1), 'P');
}
public static Map<String, Character> populateSuffixeMap(String longestSuffix) {
return populateMap(longestSuffix, (arr, i) -> new String(arr, i, longestSuffix.length() - i), 'S');
}
public static Map<String, Character> populateMap(String substr, BiFunction<char[], Integer, String> keyBuilder, char value) {
Map<String, Character> type = new HashMap<>();
StringBuilder tmp = new StringBuilder();
char[] strArr = substr.toCharArray();
int n = strArr.length;
for (int i = 0; i < n; ++i)
type.put(keyBuilder.apply(strArr, i), value);
return type;
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 2b7c667de77aebcce378e6601ea905ea | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.List;
import java.util.stream.Stream;
public class Main {
private static BufferedReader in;
private static BufferedWriter out;
public static void main(String[] args) throws IOException {
// openFile();
openConsole();
int size = readInt();
int longWordId = 0;
String [] longWords = new String[2];
List<String> allWords = new ArrayList<>();
List<String> shortWords = new ArrayList<>();
for (int i = 0; i < 2 * size - 2; i++) {
String word = readString();
if (word.length() == size - 1) {
longWords[longWordId] = word;
++longWordId;
} else {
shortWords.add(word);
}
allWords.add(word);
}
String guessedWord = longWords[0].charAt(0) + longWords[1];
String result = check(guessedWord, allWords);
if (result != null) {
System.out.println(result);
} else {
guessedWord = longWords[1].charAt(0) + longWords[0];
System.out.println(check(guessedWord, allWords));
}
close();
}
private static String check(String candidate, List<String> allWords) {
Set<String> prefixes = new HashSet<>();
StringBuilder result = new StringBuilder();
for (String eachWord : allWords) {
if (candidate.startsWith(eachWord) && !prefixes.contains(eachWord)) {
result.append("P");
prefixes.add(eachWord);
} else if (candidate.endsWith(eachWord)) {
result.append("S");
} else {
return null;
}
}
return result.toString();
}
private static int readInt() throws IOException {
return Integer.parseInt(in.readLine());
}
private static int[] readInts() throws IOException {
return Stream.of(in.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
}
private static long[] readLongs() throws IOException {
return Stream.of(in.readLine().split("\\s+")).mapToLong(Long::parseLong).toArray();
}
private static long readLong() throws IOException {
return Long.parseLong(in.readLine());
}
private static double[] readDoubles() throws IOException {
return Stream.of(in.readLine().split("\\s+")).mapToDouble(Double::parseDouble).toArray();
}
private static double readDouble() throws IOException {
return Double.parseDouble(in.readLine());
}
private static String readString() throws IOException {
return in.readLine();
}
private static void openFile() throws FileNotFoundException {
in = new BufferedReader(new FileReader(new File("/Users/mukhan/development/src/input.txt")));
out = new BufferedWriter(new OutputStreamWriter((System.out)));
}
private static void openConsole() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter((System.out)));
}
private static void close() throws IOException {
out.flush();
out.close();
in.close();
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 1fe6cab5a7feba03458f0f616864f8ca | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes |
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
public class Main {
static StdIn in = new StdIn();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception{
int n = in.nextInt();
int m = 2 * n - 2;
String a = "", b = "";
List<String> list = new ArrayList<String>();
for(int i = 0; i < m; ++i) {
String s = in.next();
list.add(s);
if(s.length() == n - 1) {
if(a == "") a = s;
else b = s;
}
}
String s1 = a.charAt(0) + b;
String s2 = b.charAt(0) + a;
if(check(s1, list)) { }
else check(s2, list);
out.close();
}
static boolean check(String s, List<String> list) {
HashMap<String, Character> prefixes = new HashMap<String, Character>();
HashMap<String, Character> suffixes = new HashMap<String, Character>();
int n = s.length();
for(int i = 1; i < n; ++i) prefixes.put(s.substring(0, i), 'P');
for(int i = 1; i < n; ++i) suffixes.put(s.substring(i, n), 'S');
List<Character> ans = new ArrayList<Character>();
for(String x : list) {
if(prefixes.containsKey(x)) {
ans.add('P');
prefixes.remove(x);
}
else if(suffixes.containsKey(x)) {
ans.add('S');
suffixes.remove(x);
}
else return false;
}
ans.forEach(out::print);
return true;
}
static long mul_mod(long a, long b, long m) {
if (a >= m)
a %= m;
if (b >= m)
b %= m;
double x = a;
long c = (long) (x * b / m);
long r = (long) (a * b - c * m) % m;
return r < 0 ? r + m : r;
}
static long pow_mod(long a, long b, long m) {
long res = 1;
a %= m;
while (b > 0) {
if (b % 2 != 0)
res = mul_mod(res, a, m);
b >>= 1;
a = mul_mod(a, a, m);
}
return res;
}
static class Pair<T extends Comparable<T>, K extends Comparable<K>> implements Comparable<Pair<T, K>>{
public T x;
public K y;
public Pair() { }
public Pair(T first, K second) {
this.x = first;
this.y = second;
}
@Override
public int compareTo(Pair<T, K> o) {
int cmp = x.compareTo(o.x);
return cmp != 0 ? cmp : y.compareTo(y);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair)) {
return false;
}
Pair<?, ?> p = (Pair<?, ?>) obj;
return Objects.equals(p.x, x) && Objects.equals(p.y, y);
}
@Override
public int hashCode() {
return x.hashCode() * 31 + y.hashCode() * 10000007;
}
@Override
public String toString() {
return "( " + x.toString() + " , " + y.toString() + " )";
}
}
static class PairInt extends Pair<Integer, Integer> {
public PairInt() { super(0, 0); }
public PairInt(int a, int b) { super(a, b); }
}
static class PairLong extends Pair<Long, Long> {
public PairLong() { super(0L, 0L); }
public PairLong(long a, long b) { super(a, b); }
}
static class StdIn {
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public StdIn() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(InputStream in) {
try {
din = new DataInputStream(in);
} catch (Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public StdIn(String fileName) {
InputStream in;
try {
in = new FileInputStream(new File(fileName));
din = new DataInputStream(in);
} catch (Exception e) {
throw new RuntimeException();
}
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() {
int c;
while ((c = read()) != -1 && (c == ' ' || c == '\n' || c == '\r'))
;
StringBuilder s = new StringBuilder();
while (c != -1) {
if (c == ' ' || c == '\n' || c == '\r')
break;
s.append((char) c);
c = read();
}
return s.toString();
}
public String nextLine() {
int c;
while ((c = read()) != -1 && (c == ' ' || c == '\n' || c == '\r'))
;
StringBuilder s = new StringBuilder();
while (c != -1) {
if (c == '\n' || c == '\r')
break;
s.append((char) c);
c = read();
}
return s.toString();
}
public int nextInt() {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for (int i = 0; i < n; ++i)
ar[i] = nextInt();
return ar;
}
public long nextLong() {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long[] readLongArray(int n) {
long[] ar = new long[n];
for (int i = 0; i < n; ++i)
ar[i] = nextLong();
return ar;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
ret = ret * 10 + c - '0';
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() {
try {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
} catch (IOException e) {
throw new RuntimeException();
}
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 8d2b77fc0989828f4ce0b8ac6f72d565 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes |
//Where there is a will, there is a way !
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class FastReader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public FastReader() { this(System.in); }public FastReader(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();}
public long l(){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 i(){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 double d() throws IOException {return Double.parseDouble(next()) ;}
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 void scanIntArr(int [] arr){ for(int li=0;li<arr.length;++li){ arr[li]=i();}}
public void scanLongArr(long [] arr){for (int i=0;i<arr.length;++i){arr[i]=l();}}
public void shuffle(int [] arr){ for(int i=arr.length;i>0;--i) { int r=(int)(Math.random()*i); int temp=arr[i-1]; arr[i-1]=arr[r]; arr[r]=temp; } }
}
static int count=0;
static int countS=0;
static int countP=0;
static boolean [] prefixMark;
static boolean [] suffixMark;
public static void main(String[] args)throws IOException {
/*
inputCopy
5
ba
a
abab
a
aba
baba
ab
aba
outputCopy
SPPSPSPS
inputCopy
3
a
aa
aa
a
outputCopy
PPSS
inputCopy
2
a
c
outputCopy
PS
*/
PrintWriter pw = new PrintWriter(System.out);
FastReader fr = new FastReader();
int n=fr.i();
prefixMark=new boolean [n+1];
suffixMark=new boolean [n+1];
String [] arr =new String[2*(n-1)];
String str1="";
String str2="";
char [] ans=new char [2*(n-1)];
for(int i=0;i<arr.length;++i)
{
arr[i]=fr.next();
if(arr[i].length()==n-1 && str1.length()==0)
{
str1+=arr[i];
}
else if(arr[i].length()==n-1 && str1.length()!=0)
{
str2+=arr[i];
}
}
String str=str1+str2.charAt(str2.length()-1);
//pw.println("Firstly str="+str);
if(!satisfies(str,arr))
{
//pw.println("Not satisfied");
str=str2+str1.charAt(str1.length()-1);
}
//pw.println("Str is :"+str);
getPreOrSuf(str,arr,ans);
boolean alternate=true;
for(int i=0;i<arr.length;++i)
{
if(ans[i]=='B')
{
if(prefixMark[arr[i].length()])
{
suffixMark[arr[i].length()]=true;
ans[i]='S';
}
else
{
prefixMark[arr[i].length()]=true;
ans[i]='P';
}
}
}
pw.println(String.valueOf(ans));
pw.flush();
pw.close();
}
public static boolean satisfies(String str,String [] arr)
{
for(int i=0;i<arr.length;++i)
{
if(!(str.startsWith(arr[i]) || str.endsWith(arr[i])))
{
//System.out.println("False for :"+i);
return false;
}
}
return true;
}
public static boolean isPrefix(String str,String pre)
{
return str.startsWith(pre);
}
public static boolean isSuffix(String str,String suff)
{
return str.endsWith(suff);
}
public static void getPreOrSuf(String str,String [] arr,char [] ans)
{
for(int i=0;i<arr.length;++i)
{
String sub=arr[i];
if(str.startsWith(sub) && str.endsWith(sub))
{
ans[i]='B';//Both
++count;
}
else if(str.startsWith(sub))
{
ans[i]='P';
prefixMark[sub.length()]=true;
++countP;
}
else
{
ans[i]='S';
suffixMark[sub.length()]=true;
++countS;
}
}
return;
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 260cad294c1334420116f1402b1ae320 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution
{
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static long modInverse(long a,long m)
{
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1)
{
long q = a / m;
long t = m;
m = a % m;
a = t;
t = y;
y = x - q * y;
x = t;
}
if (x < 0)
x += m0;
return x;
}
public static HashMap<String,ArrayList<Integer>> map;
public static char[] ans;
public static int n;
public static boolean[] vis;
public static boolean check(String p,String s)
{
//System.out.println(p+" "+s);
StringBuilder pre=new StringBuilder(p);
StringBuilder suf=new StringBuilder(s);
int mp=0;
for(int i=1;i<=n-1;i++)
{
String sub=pre.substring(0,i);
//System.out.println(sub);
Set<String> all=map.keySet();
Iterator it=all.iterator();
boolean pos=false;
while(it.hasNext())
{
String str=(String)(it.next());
ArrayList<Integer> as=map.get(str);
if(str.equals(sub))
{
//System.out.println(str+" "+as.get(0));
ans[as.get(0)]='P';
vis[as.get(0)]=true;
mp++;
pos=true;
break;
}
}
if(!pos)
return false;
}
int ms=0;
for(int i=0;i<n-1;i++)
{
String sub=suf.substring(i,n-1);
//System.out.println(sub);
Set<String> all=map.keySet();
Iterator it=all.iterator();
boolean pos=false;
while(it.hasNext())
{
String str=(String)(it.next());
ArrayList<Integer> as=map.get(str);
if(str.equals(sub) && as.size()>1)
{
//System.out.println(str+" "+as.get(1));
ans[as.get(1)]='S';
vis[as.get(1)]=true;
ms++;
pos=true;
break;
}
else if(str.equals(sub) && !vis[as.get(0)])
{
//System.out.println(str+" "+as.get(0));
ans[as.get(0)]='S';
ms++;
pos=true;
break;
}
}
if(!pos)
return false;
}
if(mp>=n-2 && ms>=n-2)
{
//System.out.println(ans.length);
for(int i=0;i<ans.length;i++)
System.out.print(ans[i]);
return true;
}
return false;
}
public static void main(String[] args) throws IOException
{
InputReader in=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
n=in.nextInt();
map=new HashMap<String,ArrayList<Integer>>();
ans=new char[(2*n)-2];
vis=new boolean[(2*n)-2];
//System.out.println(ans.length);
StringBuilder sb=new StringBuilder();
for(int i=0;i<(2*n)-2;i++)
{
String str=in.readString();
if(map.get(str)==null)
{
ArrayList<Integer> ai=new ArrayList<Integer>();
ai.add(i);
map.put(str,ai);
}
else
{
ArrayList<Integer> num=map.get(str);
num.add(i);
map.remove(str);
map.put(str,num);
}
if(str.length()==n-1)
sb.append(str);
}
//w.println(sb.toString());
if(check(sb.substring(0,n-1),sb.substring(n-1,sb.length())))
return;
vis=new boolean[2*n-2];
if(check(sb.substring(n-1,sb.length()),sb.substring(0,n-1)))
return;
//w.println("-1");
//w.println(sb.substring(0,n-1)+" "+sb.substring(n-1,sb.length()));
w.close();
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 78bea2593ef7871553b3eba2a9823e04 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | import javax.swing.text.html.HTMLDocument;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.nio.Buffer;
import java.util.*;
public class Main {
public static void main(String[] args){
try {
PrintWriter out=new PrintWriter(System.out,true);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
List<String> list=new ArrayList<>();
String pre="-1",suf="-1";
int a=-1,b=-1;
for(int i=0;i<2*n-2;i++){
list.add(br.readLine());
if(list.get(i).length()==n-1){
if(pre.equals("-1")){
pre=list.get(i);
a=i;
}else{
suf=list.get(i);
b=i;
}
}
}
char[] c = new char[2*n-2];
String word=pre+suf.charAt(suf.length()-1);
int[] p=new int[n];
int[] s=new int[n];
c[a]='P';
c[b]='S';
p[n-1]=1;
s[n-1]=1;
boolean flag=true;
for(int i=0;i<2*n-2;i++){
if(i==a || i==b){
continue;
}
String str=list.get(i);
boolean bb=false,ff=false;
if(word.startsWith(str)){
bb=true;
}
if(word.endsWith(str)){
ff=true;
}
if (bb && ff) {
if(s[str.length()]==0){
c[i]='S';
s[str.length()]=1;
}else if(p[str.length()]==0){
c[i]='P';
p[str.length()]=1;
}else{
flag=false;
break;
}
}else if(bb){
c[i]='P';
p[str.length()]=1;
}else{
c[i]='S';
s[str.length()]=1;
}
}
for(int i=1;i<n;i++){
if(s[i]!=1 || p[i]!=1){
flag=false;
break;
}
}
if(flag){
String ss=String.valueOf(c);
out.println(ss);
}else{
String temp=pre;
pre=suf;
suf=temp;
int tem = a;
a=b;
b=tem;
word=pre+suf.charAt(suf.length()-1);
c=new char[2*n-2];
p=new int[n];
s=new int[n];
c[b]='S';
c[a]='P';
p[n-1]=1;
s[n-1]=1;
for(int i=0;i<2*n-2;i++){
if(i==a || i==b){
continue;
}
String str=list.get(i);
boolean bb=false,ff=false;
if(word.startsWith(str)){
bb=true;
}
if(word.endsWith(str)){
ff=true;
}
if (bb && ff) {
if(s[str.length()]==0){
c[i]='S';
s[str.length()]=1;
}else if(p[str.length()]==0){
c[i]='P';
p[str.length()]=1;
}
}else if(bb){
c[i]='P';
p[str.length()]=1;
}else{
c[i]='S';
s[str.length()]=1;
}
}
String ss=String.valueOf(c);
out.println(ss);
}
out.close();
} catch (Exception e) {
System.out.println("kkkk "+ e.getMessage());
}
}
static void dfs(ArrayList<HashSet<Integer>> list,Set<Integer> set,int i){
set.add(i);
Iterator<Integer> it=list.get(i).iterator();
while(it.hasNext()){
int u=it.next();
if(!set.contains(u)){
dfs(list,set,u);
}
}
}
static int diff(String s1,String s2){
int c=0;
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)!=s2.charAt(i)){
c++;
}
}
return c;
}
static boolean isPal(String s){
StringBuilder str=new StringBuilder(s);
str=str.reverse();
String ss=String.valueOf(str);
if (ss.equals(s)) {
return true;
}
return false;
}
static int mod(int a,int b){
if (a>b){
return a-b;
}
return b-a;
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static int lcm(int a,int b){
long c=a*((long)b);
return (int)(c/hcf(a,b));
}
static int hcf(int a,int b){
if(a==0){
return b;
}
if(b==0){
return a;
}
if(a>b)
return hcf(a%b,b);
return hcf(a,b%a);
}
static int modInverse(int x,int m){
return power(x,m-2,m);
}
static int power(int x, int y, int m)
{
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
return (int)((y%2==0)? p : (x*p)%m);
}
static class pair{
int a,b;
public pair(int a,int b){
this.a=a;
this.b=b;
}
}
} | Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 75649fe72bd87ffcc6f0292ac00eba18 | train_001.jsonl | 1545143700 | Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin! | 256 megabytes | //package Codef;
import java.util.Arrays;
import java.util.Scanner;
public class C_1092 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
String[] st = new String[2*n-2];
// String[] str = new String[2*n-2];
String st1 = "";
String st2 = "";
for(int i=0;i<st.length;i++) {
st[i] = s.next();
if(st1 .equals("") && st[i].length() == n-1 ) {
st1 = st[i];
}else if(st[i].length() == n-1) {
st2 = st[i];
}
}
//System.out.println(st1+" "+st2 );
String ans ="";
int k=0;
boolean[] chk = new boolean[n];
if(st1.substring(1).equals(st2.substring(0,n-2))) {
for(int i=0;i<2*n-2;i++) {
//System.out.println(st1.substring(0 , st[i].length()));
if(st1.substring(0 , st[i].length()).equals(st[i]) && !chk[st[i].length()-1]) {
ans+= "P";
chk[st[i].length()-1] = true;
}else if(st2.substring(st2.length()-st[i].length()).equals(st[i])) {
ans+="S";
}else {
k=1;
break;
}
}
if(k==0) {
System.out.println(ans);
return;
}
}
ans="";
chk = new boolean[n];
for(int i=0;i<2*n-2;i++) {
if(st2.substring(0 , st[i].length()).equals(st[i]) && !chk[st[i].length()-1]) {
//System.out.println(8990);
ans+= "P";
chk[st[i].length()-1] = true;
}else if(st1.substring(st1.length()-st[i].length()).equals(st[i])) {
//System.out.println(597979);
ans+="S";
}
}
System.out.println(ans);
}
}
| Java | ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"] | 1 second | ["SPPSPSPS", "PPSS", "PS"] | NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | Java 8 | standard input | [
"strings"
] | ddbde202d00b928a858e9f4ff461e88c | The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$. | 1,700 | Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any. | standard output | |
PASSED | 74f660fbc5bbb6e0071e16ae9333a825 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
//package codeforces;
import java.io.PrintWriter;
import java.util.Scanner;
/**
*
* @author huseyngasimov
*/
public class SerejaAlgorithm {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = in.next();
int N = s.length();
int[][] a = new int[N+1][3];
for (int i = 0; i < N; i++) {
System.arraycopy(a[i], 0, a[i+1], 0, 3);
if (s.charAt(i) == 'x') a[i+1][0] = a[i][0] + 1;
else if (s.charAt(i) == 'y') a[i+1][1] = a[i][1] + 1;
else a[i+1][2] = a[i][2] + 1;
}
//printA(a);
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int li = in.nextInt();
int ri = in.nextInt();
if (ri - li < 2) {
out.println("YES");
}
else {
int numx = a[ri][0] - a[li-1][0];
int numy = a[ri][1] - a[li-1][1];
int numz = a[ri][2] - a[li-1][2];
//out.println(numx + " " + numy + " ");
if (Math.abs(numx-numy) > 1) out.println("NO");
else if (Math.abs(numx-numz) > 1) out.println("NO");
else if (Math.abs(numy-numz) > 1) out.println("NO");
else out.println("YES");
}
}
out.flush();
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | ea0e4a358732c1065accc4f9fc97cc00 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.*;
public class C {
int INF = Integer.MAX_VALUE / 100;
static Scanner sc = null;
static BufferedReader br = null;
static PrintStream out = null;
static BufferedWriter bw = null;
int N = 0;
String yes = "YES";
String no = "NO";
public void solve() throws Exception{
String s = br.readLine();
char[] c = s.toCharArray();
int n = s.length();
int m = nextInt();
int[] b = new int[n];
for(int i = 0; i < n - 2; i++){
if(c[i] == 'z' && c[i+1] == 'y' && c[i+2] == 'x') b[i] = 1;
if(c[i] == 'x' && c[i+1] == 'z' && c[i+2] == 'y') b[i] = 1;
if(c[i] == 'y' && c[i+1] == 'x' && c[i+2] == 'z') b[i] = 1;
}
BIT bit = new BIT(n);
BIT bitx = new BIT(n);
BIT bity = new BIT(n);
BIT bitz = new BIT(n);
for(int i = 0; i < n; i++){
if(c[i] == 'x'){
bitx.add(i+1, 1);
}
if(c[i] == 'y'){
bity.add(i+1, 1);
}
if(c[i] == 'z'){
bitz.add(i+1, 1);
}
bit.add(i+1, b[i]);
}
for(int i = 0; i < m; i++){
int[] t = nextInts();
int l = t[0];
int r = t[1];
if(r - l < 2){
out.println(yes);
}
else{
int x = bitx.sum(r) - bitx.sum(l-1);
int y = bity.sum(r) - bity.sum(l-1);
int z = bitz.sum(r) - bitz.sum(l-1);
boolean flag = false;
if(x > 0 && y > 0 && z > 0){
int maxn = max(x, y);
maxn = max(maxn, z);
int minn = min(x, y);
minn = min(minn, z);
if(maxn - minn <= 1){
flag = true;
}
}
if(flag){
out.println(yes);
}
else{
out.println(no);
}
}
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = sc.nextInt();
}
return ret;
}
private int nextInt() throws IOException{
String s = br.readLine();
return parseInt(s);
}
private int[] nextInts() throws IOException{
String s = br.readLine();
String[] sp = s.split(" ");
int[] r = new int[sp.length];
for(int i = 0;i < sp.length; i++){
r[i] = parseInt(sp[i]);
}
return r;
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
File file = new File("input.txt");
if(file.exists()){
System.setIn(new BufferedInputStream(new FileInputStream("input.txt")));
}
out = System.out;
bw = new BufferedWriter(new PrintWriter(out));
//sc = new Scanner(System.in);
br = new BufferedReader(new InputStreamReader(System.in));
C t = new C();
t.solve();
bw.close();
}
class BIT {
public BIT(int n){
this.N = n;
bit = new int[N+2];
}
int N = 100000;
int bit[] = null;
int sum0(int i){
return sum(i+1);
}
void add0(int i, int x){
add(i+1, x);
}
int sum(int i){
int s = 0;
while(i > 0){
s += bit[i];
i-=i&-i;
}
return s;
}
void add(int i, int x){
while(i <= N){
bit[i] = bit[i] + x;
i += i & -i;
}
}
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | ddf0b45637f3d9276d64385322913d48 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | /* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
String s= sc.next();
char xyz[] = s.toCharArray();
int n = xyz.length;
int x[] = new int[n+1];
int y[] = new int[n+1];
int z[] = new int[n+1];
x[0]=0;
y[0]=0;
z[0]=0;
for(int i = 1;i<=n;i++){
x[i]=x[i-1];
y[i]=y[i-1];
z[i]=z[i-1];
if(xyz[i-1]=='x'){
x[i]++;
}
if(xyz[i-1]=='y'){
y[i]++;
}
if(xyz[i-1]=='z'){
z[i]++;
}
}
int m = sc.nextInt();
for(int abercrombie = 0;abercrombie<m;abercrombie++){
int l = sc.nextInt();
int r = sc.nextInt();
int xx = x[r]-x[l-1];
int yy = y[r]-y[l-1];
int zz = z[r]-z[l-1];
if(r-l<2){
System.out.println("YES");
}
else{
int whyamievenmakinganarray[] = new int[] {xx,yy,zz};
Arrays.sort(whyamievenmakinganarray);
xx=whyamievenmakinganarray[0];
yy=whyamievenmakinganarray[1];
zz=whyamievenmakinganarray[2];
if((xx==yy&&yy==zz)||(xx==yy&&yy==zz-1)||(xx==yy-1)&&(yy==zz)){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
} | Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 395c268208d472d0527797af7ac6fa88 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | //package Round_215;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
void solve() throws Exception {
char ch[] = in.next().toCharArray();
int n = ch.length;
int fx[] = new int[n];
int fy[] = new int[n];
int fz[] = new int[n];
for (int i = 0; i < n; i++) {
switch (ch[i]) {
case 'x':
fx[i]++;
break;
case 'y':
fy[i]++;
break;
case 'z':
fz[i]++;
break;
}
if (i > 0) {
fx[i] += fx[i - 1];
fy[i] += fy[i - 1];
fz[i] += fz[i - 1];
}
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int x = fx[r], y = fy[r], z = fz[r];
if (l > 0) {
x -= fx[l - 1];
y -= fy[l - 1];
z -= fz[l - 1];
}
int len = r - l + 1;
x -= len / 3;
y -= len / 3;
z -= len / 3;
if (len % 3 != 0) {
if (z >= x && z >= y) {
z--;
if (len % 3 == 2) {
if (x > y)
x--;
else
y--;
}
} else if (x >= z && x >= y) {
x--;
if (len % 3 == 2) {
if (z > y)
z--;
else
y--;
}
} else if (y >= z && y >= x) {
y --;
if (len % 3 == 2) {
if (x > z)
x--;
else
z--;
}
}
}
if (r - l + 1 < 3) {
out.println("YES");
} else if (x == 0 && y == 0 && z == 0) {
out.println("YES");
} else {
out.println("NO");
}
}
}
String input = "";
String output = "";
FastScanner in;
PrintWriter out;
void run() throws Exception {
if (input.length() == 0) {
in = new FastScanner(System.in);
} else {
in = new FastScanner(new File(input));
}
if (output.length() == 0) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(new File(output));
}
solve();
out.close();
}
public static void main(String[] args) throws Exception {
new C().run();
}
class FastScanner {
BufferedReader bf;
StringTokenizer st;
public FastScanner(InputStream is) {
bf = new BufferedReader(new InputStreamReader(is));
}
public FastScanner(File fr) throws FileNotFoundException {
bf = new BufferedReader(new FileReader(fr));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(bf.readLine());
}
} catch (IOException ex) {
ex.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 19705463efa70a99a3115dd3f7b30ada | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | /*
Date :
Problem Name :
Location :
Algorithm :
Status :
Coding :
Thinking :
Time spent :
Note :
*/
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader reader
= new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args){
char[] q = getLine().toCharArray();
int numTests = Integer.parseInt(getLine());
int[] xs = new int[q.length + 5];
int[] ys = new int[q.length + 5];
int[] zs = new int[q.length + 5];
for (int i = 1; i <= q.length; i++){
xs[i] = xs[i-1];
ys[i] = ys[i-1];
zs[i] = zs[i-1];
if (q[i-1] == 'x'){
xs[i]++;
}
if (q[i-1] == 'y'){
ys[i]++;
}
if (q[i-1] == 'z'){
zs[i]++;
}
}
for (int test = 0; test < numTests; test++){
int x, y, z;
int from, to;
String[] inp = getLine().split("\\s+");
from = Integer.parseInt(inp[0]);
to = Integer.parseInt(inp[1]);
if (to - from + 1 < 3){
System.out.println("YES");
continue;
}
x = xs[to] - xs[from - 1];
y = ys[to] - ys[from - 1];
z = zs[to] - zs[from - 1];
int[] ary = {x, y, z};
Arrays.sort(ary);
System.out.println(ary[2] - ary[0] <= 1 ? "YES" : "NO");
}
}
static String getLine(){
try {
return reader.readLine().trim();
} catch (Exception e){
}
return null;
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 331c1651c118dd9da45f5553cd38d0c4 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 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.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Task {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA s = new TaskA();
s.solve(in, out);
out.close();
}
}
class TaskA {
public void solve(InputReader in, PrintWriter out) {
String s=in.next();
int[][] a=new int[3][s.length()+1];
a[0][0]=a[1][0]=a[2][0]=0;
for(int i=1;i<=s.length();i++){
char c=s.charAt(i-1);
for(int j=0;j<3;j++)
a[j][i]=a[j][i-1];
a[c-'x'][i]++;
}
int m=in.nextInt();
for(int i=0;i<m;i++){
int l=in.nextInt();
int r=in.nextInt();
if(r-l+1<3){
out.println("YES");
continue;
}
int x=a[0][r]-a[0][l-1];
int y=a[1][r]-a[1][l-1];
int z=a[2][r]-a[2][l-1];
if(x-y>=-1 && x-y<=1
&& x-z>=-1 && x-z<=1
&& y-z>=-1 && y-z<=1)
out.println("YES");
else
out.println("NO");
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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 | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 3b4d6bf182d911db7b006c9d8c4356a5 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.PrintStream;
import java.util.*;
public class Problem215C {
public static void main(String[] args) throws Exception {
new Problem215C().solve(new Scanner(System.in), System.out);
}
public void solve(Scanner in, PrintStream out) throws Exception{
char[] s = in.nextLine().toCharArray();
int[] xs = new int[s.length];
int[] ys = new int[s.length];
int[] zs = new int[s.length];
int x = 0;
int y = 0;
int z = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] == 'x') x += 1;
else if (s[i] == 'y') y += 1;
else if (s[i] == 'z') z += 1;
xs[i] = x;
ys[i] = y;
zs[i] = z;
}
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int nx, ny, nz;
if (l == r) {
nx = ny = nz = 0;
} else if (l == 0) {
nx = xs[r];
ny = ys[r];
nz = zs[r];
} else {
nx = xs[r] - xs[l - 1];
ny = ys[r] - ys[l - 1];
nz = zs[r] - zs[l - 1];
}
if (r - l >= 2 && (Math.abs(nz - nx) > 1 || Math.abs(ny - nz) > 1 || Math.abs(nx -
ny) > 1)) {
out.println("NO");
} else {
out.println("YES");
}
}
}
} | Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 1b4dfbc132061daa72f70db019ef1c14 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 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;
/*
* Notes....
* Notice the huge sizes. I was like oh yeah try bfs.
* Stupid idea though. Numbers wayyyyyy too huge.
* Should be indication that there's cheesy solution by realizing that every set of 3 chars
* needs all xyz. the three 3 letter combinations are there for a reason.
*/
public class TaskC {
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
char[] input = in.next().toCharArray();
int[] x = new int[input.length];
int[] y = new int[input.length];
int[] z = new int[input.length];
for(int i=0;i<input.length;i++)
{
if(input[i]=='x')
{
x[i]++;
}
if(input[i]=='y')
{
y[i]++;
}
if(input[i]=='z')
{
z[i]++;
}
if(i!=0)
{
x[i]+=x[i-1];
y[i]+=y[i-1];
z[i]+=z[i-1];
}
}
int m = in.nextInt();
for(int i=0;i<m;i++)
{
int l = in.nextInt();
int r = in.nextInt();
int xn,yn,zn;
if(l!=1)
{
xn = x[r-1]-x[l-2];
yn = y[r-1]-y[l-2];
zn = z[r-1]-z[l-2];
}
else
{
xn = x[r-1];
yn = y[r-1];
zn = z[r-1];
}
int length = r-l+1;
xn-=length/3;
yn-=length/3;
zn-=length/3;
if(length%3!=0)
{
if(zn>xn || zn>yn)
{
zn--;
if(length%3==2)
{
if(xn>yn)
{
xn--;
}
else
{
yn--;
}
}
}
if(yn>zn || yn>xn)
{
yn--;
if(length%3==2)
{
if(zn>xn)
{
zn--;
}
else
{
xn--;
}
}
}
if(xn>yn||xn>zn)
{
xn--;
if(length%3==2)
{
if(zn>yn)
{
zn--;
}
else
{
yn--;
}
}
}
}
if(length<3)
{
out.println("YES");
}
else if(xn==0&&yn==0&&zn==0)
{
out.println("YES");
}
else
{
out.println("NO");
}
}
out.close();
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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 | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 1916472432ae1a25dfc36e39fa9e3cd2 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Algorithm {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int[][] xyzi = new int[line.length() + 1][3];
for (int i = 1; i <= line.length(); i++) {
xyzi[i] = xyzi[i-1].clone();
char c = line.charAt(i - 1);
switch (c) {
case 'x':
xyzi[i][0]++;
break;
case 'y':
xyzi[i][1]++;
break;
case 'z':
xyzi[i][2]++;
break;
}
}
int ntests = sc.nextInt();
for (int i = 0; i < ntests; i++) {
int l = sc.nextInt();
int r = sc.nextInt();
int x = xyzi[r][0] - xyzi[l - 1][0];
int y = xyzi[r][1] - xyzi[l - 1][1];
int z = xyzi[r][2] - xyzi[l - 1][2];
int min = x;
int max = x;
min = Math.min(min, y);
min = Math.min(min, z);
max = Math.max(max, y);
max = Math.max(max, z);
if (r - l + 1 < 3) {
System.out.println("YES");
continue;
}
if ((max - min <= 1) && (min > 0)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 25a5b9333bcfb5bb33b7ab30cc9e2953 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
/**
* @param args
*/
public static StringBuilder str;
static int[] sx;
static int[] sy;
static int[] sz;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
String st = fs.nextToken();
int n = st.length();
str = new StringBuilder(st);
int m=fs.nextInt();
int[] first = new int[m];
int[] second = new int[m];
sx = new int[n+1];
sy = new int[n+1];
sz = new int[n+1];
for(int i=1;i<=n;i++) {
if(i>0) {
sx[i]=sx[i-1];
sy[i]=sy[i-1];
sz[i]=sz[i-1];
}
if(str.charAt(i-1)=='x')
sx[i]++;
if(str.charAt(i-1)=='y')
sy[i]++;
if(str.charAt(i-1)=='z')
sz[i]++;
}
for(int i=0;i<m;i++) {
first[i] = fs.nextInt();
second[i] = fs.nextInt();
}
for(int j=0;j<m;j++) {
System.out.println(possible(first[j],second[j]));
}
}
static String possible(int l, int r) {
if(r-l+1<3)
return "YES";
int x = 0,y = 0,z = 0;
x=sx[r]-sx[l-1];
y=sy[r]-sy[l-1];
z=sz[r]-sz[l-1];
if(x==y && y==z)
return "YES";
if(x==y) {
if(Math.abs(x-z)==1) {
return "YES";
}
}
if(x==z) {
if(Math.abs(x-y)==1) {
return "YES";
}
}
if(z==y) {
if(Math.abs(z-x)==1) {
return "YES";
}
}
return "NO";
}
}
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 8f854503ecf22f1989c0da216bd826bf | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author karan173
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out)
{
char a[] = in.ns ().toCharArray ();
int n = a.length;
int m = in.ni ();
int cnt[][] = new int[n + 1][3];
Arrays.fill (cnt[0], 0);
for (int i = 1; i <= n; i++)
{
int z = a[i-1] - 'x';
for (int j = 0; j <3; j++)
{
cnt[i][j] = cnt[i - 1][j];
}
cnt[i][z]++;
}
// out.println (Arrays.toString (dp));
for (int i = 0; i < m; i++)
{
int l = in.ni ();
int r = in.ni ();
int nn = r - l + 1;
if (nn < 3)
{
out.println ("YES");
continue;
}
int newcnt[] = new int[3];
Arrays.fill (newcnt, 0);
int min = nn + 5;
for (int j = 0; j < 3; j++)
{
newcnt[j] = cnt[r][j] - cnt[l - 1][j];
min = Math.min (min, newcnt[j]);
}
int cnt0 = 0, cnt1 = 0;
for (int j = 0; j < 3; j++)
{
newcnt[j] -= min;
if (newcnt[j] == 0)
{
cnt0++;
}
else if (newcnt[j] == 1)
{
cnt1++;
}
}
int x = nn%3;
if (x == 0)
{
if (cnt0 == 3)
{
out.println ("YES");
}
else
{
out.println ("NO");
}
}
else if (x == 1)
{
if (cnt0 == 2 && cnt1 == 1)
{
out.println ("YES"); //CHECK
}
else
{
out.println ("NO");
}
}
else
{
if (cnt0 == 1 && cnt1 == 2)
{
out.println ("YES"); //CHECK
}
else
{
out.println ("NO");
}
}
}
}
}
class FastReader
{
public InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private 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 ni()
{
int c = read ();
while (isSpaceChar (c))
c = read ();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read ();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException ();
}
res *= 10;
res += c - '0';
c = read ();
} while (!isSpaceChar (c));
return res * sgn;
}
public String ns()
{
int c = read ();
while (isSpaceChar (c))
c = read ();
StringBuilder res = new StringBuilder ();
do
{
res.appendCodePoint (c);
c = read ();
} while (!isSpaceChar (c));
return res.toString ();
}
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 | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | b3bca9d5a4ee5a83ae86969e05b331d6 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
String S=in.readLine();
int N=S.length();
int[][] ct= new int[N][3];
ct[0][(int)S.charAt(0)-(int)'x']++;
for (int i = 1; i < N; i++) {
for (int j = 0; j < 3; j++) {
ct[i][j]=ct[i-1][j];
}
ct[i][(int)S.charAt(i)-(int)'x']++;
}
int m=in.nextInt();
while(m-->0){
int l=in.nextInt()-1,r=in.nextInt()-1;
int[] ans= new int[3];
for (int i = 0; i < 3; i++) {
ans[i]=ct[r][i];
if(l!=0)
ans[i]-=ct[l-1][i];
}
// System.out.println(S.substring(l,r+1));
if(r-l<2){
out.println("YES");
continue;
}
int nn=r-l+1;
Arrays.sort(ans);
if(nn%3==0){
if(ans[2]==ans[0]) out.println("YES");
else out.println("NO");
}
if(nn%3==1||nn%3==2){
// out.printArray(ans);
if(ans[2]==ans[0]+1) out.println("YES");
else out.println("NO");
}
}
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | a66e98f8f92e438fcb5e612b2a7d6b68 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
private StreamTokenizer st;
public PrintWriter pw;
public static final int modulo = 1000000009;
public static class Rational extends Number {
private long num;
private long denom;
// Construct Rational object from numerator and denominator.
// @param num the numerator
// @param denom the denomenator
public float floatValue() {
return (float) ((float) this.num / (float) this.denom);
}
public double doubleValue() {
return (double) ((double) this.num / (double) this.denom);
}
public int intValue() {
return (int) ((int) this.num / (int) this.denom);
}
public long longValue() {
return (long) ((long) this.num / (long) this.denom);
}
// Print
public void print() {
System.out.print(this.toString());
}
// Println
public void println() {
System.out.println(this.toString());
}
public Rational(long num, long denom) {
this.num = num;
this.denom = denom;
}
// Construct Rational number by parsing string.
// (Note: The parsing is *really* primitive and not at all
// robust.)
// @param r a string representation of a rational number
public Rational(String r) {
long num = 0;
long denom = 1;
long whole = 0;
// Parse a string of form "[N ]num/denom"
StringTokenizer st1 = new StringTokenizer(r);
if (st1.countTokens() == 2) {
try {
whole = Long.parseLong(st1.nextToken());
} catch (Exception e) {
whole = 0;
}
}
if (st1.countTokens() == 1) {
// Next, try to find the slash separating the
// numerator and denominator.
StringTokenizer st2 = new StringTokenizer(st1.nextToken(), "/",
false);
if (st2.countTokens() != 2) {
num = 0;
denom = 1;
} else {
try {
num = Long.parseLong(st2.nextToken());
} catch (NumberFormatException s) {
num = 0;
}
try {
denom = Long.parseLong(st2.nextToken());
} catch (NumberFormatException s) {
denom = 1;
}
}
}
this.num = (whole * denom) + num;
this.denom = denom;
this.normalize();
}
// Normalize the rational number so that the negative sign
// is stored in the numerator, rather than the denominator.
private void normalize() {
long num = this.num;
long denom = this.denom;
if (denom < 0) {
if (num < 0) {
this.num = -num;
this.denom = -denom;
} else {
this.denom = -denom;
}
}
}
// Reduce numerator and demoninator by greatest common denominator.
public void reduce() {
this.normalize();
long g = gcd(this.num, this.denom);
this.num /= g;
this.denom /= g;
}
// Return numerator of this Rational object.
public long num() {
return this.num;
}
// Return denomenator of this Rational object.
public long denom() {
return this.denom;
}
// Addition
// @param num the numerator
// @param denom the denominator
public void add(long num, long denom) {
this.num = (this.num * denom) + (num * this.denom);
this.denom = this.denom * denom;
this.normalize();
}
// @param r a rational number object
public void add(Rational r) {
this.num = (this.num * r.denom()) + (r.num() * this.denom);
this.denom = this.denom * r.denom();
this.normalize();
}
// Subtraction
// @param num the numerator
// @param denom the denominator
public void sub(long num, long denom) {
this.num = (this.num * denom) - (num * this.denom);
this.denom = this.denom * denom;
this.normalize();
}
// @param r a rational number object
public void sub(Rational r) {
this.num = (this.num * r.denom()) - (r.num() * this.denom);
this.denom = this.denom * r.denom();
this.normalize();
}
// Multiplication
// @param num the numerator
// @param denom the denominator
public void mul(long num, long denom) {
this.num = (this.num * num);
this.denom = (this.denom * denom);
this.normalize();
}
// @param r a rational number object
public void mul(Rational r) {
this.num = (this.num * r.num());
this.denom = (this.denom * r.denom());
this.normalize();
}
// Division
// @param num the numerator
// @param denom the denominator
public void div(long num, long denom) {
this.num = (this.num * denom);
this.denom = (this.denom * num);
this.normalize();
}
// @param r a rational number object
public void div(Rational r) {
this.num = (this.num * r.denom());
this.denom = (this.denom * r.num());
this.normalize();
}
@Override
public boolean equals(Object ss) {
Rational a = (Rational) ss;
if ((a.num() * this.denom()) == (this.num() * a.denom())) {
return true;
}
return false;
}
// Instance method to test for
// equivalence with another object (overrides Object's method)
// @param a an object
// Return Greatest Common Denominator (GCD)
// @param a first long integer
// @param b second long integer
public long gcd(long a, long b) {
long g;
if (b == 0) {
return a;
} else {
g = gcd(b, (a % b));
if (g < 0)
return -g;
else
return g;
}
}
public static Rational compAdd(Rational a, Rational b) {
return new Rational(a.num() + b.num(), a.denom() + b.denom());
}
@Override
public int hashCode() {
Rational q = new Rational(this.num, this.denom);
q.reduce();
return ((int) q.num) * 37 + ((int) q.denom);
}
}
void init(String in, String out) throws Exception {
if (in.isEmpty())
st = new StreamTokenizer(System.in);
else
st = new StreamTokenizer(new BufferedReader(new FileReader(in)));
if (out.isEmpty())
pw = new PrintWriter(System.out);
else
pw = new PrintWriter(new FileWriter(out));
}
private void close() {
pw.close();
}
private int nI() throws Exception {
st.nextToken();
return (int) st.nval;
}
private double nD() throws Exception {
st.nextToken();
return (double) st.nval;
}
private String nS() throws Exception {
st.nextToken();
return st.sval;
}
private long nL() throws Exception {
st.nextToken();
return (long) st.nval;
}
public static void main(String[] sssssssssss) throws Exception {
Main f = new Main();
f.init("", "");
String s = f.nS();
int n = s.length();
int m = f.nI();
int l[] = new int[m];
int r[] = new int[m];
for (int i = 0 ; i < m; ++i)
{
l[i] = f.nI() - 1;
r[i] = f.nI() - 1;
}
int x[] = new int[n];
int y[] = new int[n];
int z[] = new int[n];
Arrays.fill(x, 0);
Arrays.fill(y, 0);
Arrays.fill(z, 0);
if (s.charAt(0) == 'x')
x[0] = 1;
if (s.charAt(0) == 'y')
y[0] = 1;
if (s.charAt(0) == 'z')
z[0] = 1;
for (int i = 1 ; i < n; ++i)
{
x[i] = x[i-1];
y[i] = y[i-1];
z[i] = z[i-1];
if (s.charAt(i) == 'x')
++x[i];
if (s.charAt(i) == 'y')
++y[i];
if (s.charAt(i) == 'z')
++z[i];
}
for (int i = 0 ; i < m; ++i)
{
int left = l[i];
int right = r[i];
if (left == 0)
{
int countX = x[right];
int countY = y[right];
int countZ = z[right];
if (right - left + 1 >=3)
{
int max = Math.max(Math.max(countX, countY), countZ);
if (countX + 1 < max || countY + 1 < max || countZ +1 < max)
System.out.println("NO");
else
System.out.println("YES");
}
else
System.out.println("YES");
}
else
{
int countX = x[right] - x[left-1];
int countY = y[right] - y[left-1];
int countZ = z[right] - z[left-1];
if (right - left + 1 >=3)
{
int max = Math.max(Math.max(countX, countY), countZ);
if (countX + 1 < max || countY + 1 < max || countZ +1 < max)
System.out.println("NO");
else
System.out.println("YES");
}
else
System.out.println("YES");
}
}
f.close();
}
} | Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 81414f19ba7e89e9eb29e2740f95e29c | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String str = in.readLine();
char c[] = str.toCharArray();
int n = in.readInt();
int a[][] = new int[n][2];
for(int i = 0 ; i < n ; i++){
a[i][0] = in.readInt();
a[i][1] = in.readInt();
}
int count[][] = new int[3][c.length];
for(int i = 0; i < c.length; i++){
for(int j = 0 ; j < 3 ; j++){
if(i>0)count[j][i] = count[j][i-1];
}
count[c[i]-'x'][i]++;
}
for(int i = 0 ; i < n ; i++){
int l = a[i][0]-1;
int r = a[i][1]-1;
if(r-l<2){
out.printLine("YES");
continue;
}
int ct[] = new int[3];
for(int j = 0 ; j < 3 ; j++){
ct[j] = count[j][r] - ((l>0)?count[j][l-1]:0);
}
int max = Math.max(ct[0],ct[1]);
max = Math.max(max,ct[2]);
String res = "YES";
for(int j = 0 ; j < 3 ; j++){
if(max-ct[j]>1){
res = "NO";
break;
}
}
out.printLine(res);
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | e80c830bd0746fe4f882512708965fa5 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author Aditya Joshi
*/
public class Main
{
public static void main(String[] args)
{
MyScanner sc = new MyScanner();
String s = sc.next();
int cx = 0, cy = 0, cz = 0;
int length = s.length();
Count[] DP = new Count[length];
for(int i = 0; i < length; i++)
{
if(s.charAt(i) == 'z') cz++;
else if(s.charAt(i) == 'x') cx++;
else cy++;
DP[i] = new Count(cx, cy, cz);
}
int m = sc.nextInt();
for(int i = 0; i < m; i++)
{
int lo = sc.nextInt();
int hi = sc.nextInt();
int nox = DP[hi - 1].x - DP[lo - 1].x;
int noy = DP[hi - 1].y - DP[lo - 1].y;
int noz = DP[hi - 1].z - DP[lo - 1].z;
if(s.charAt(lo - 1) == 'x') nox++;
else if(s.charAt(lo - 1) == 'y') noy++;
else noz++;
//System.out.println("At index " + i + " and counts are " + nox + " " + noy + " " + noz);
if(hi - lo + 1 < 3) System.out.println("YES");
else if(nox == noy && noy == noz) System.out.println("YES");
else if(nox == noy && (noz == (nox + 1) || (noz == (nox - 1)))) System.out.println("YES");
else if(nox == noz && (noy == (nox + 1) || (noy == (nox - 1)))) System.out.println("YES");
else if(noy == noz && (nox == (noy + 1) || (nox == (noy - 1)))) System.out.println("YES");
else System.out.println("NO");
}
}
private static class Count
{
int x, y, z;
public Count(int a, int b, int c)
{
this.x = a;
this.y = b;
this.z = c;
}
}
public static class MyScanner
{
BufferedReader br;
StringTokenizer st;
public MyScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | fcb83e62e31e53a1c87911c046b708ea | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.util.Scanner;
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 balbasaur
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String s = in.next();
int m = in.nextInt();
int []x = new int[s.length() + 1];
int []y = new int[s.length() + 1];
int []z = new int[s.length() + 1];
int vx = 0,vy = 0,vz = 0;
for (int i = 0;i < s.length();++i){
if (s.charAt(i) == 'x'){
x[i + 1] = ++vx;
y[i + 1] = vy;
z[i + 1] = vz;
}
if (s.charAt(i) == 'y'){
y[i + 1] = ++vy;
x[i + 1] = vx;
z[i + 1] = vz;
}
if (s.charAt(i) == 'z'){
z[i + 1] = ++vz;
x[i + 1] = vx;
y[i + 1] = vy;
}
}
for (int i = 1;i <= m;++i){
int l = in.nextInt();
int r = in.nextInt();
if ((r - l + 1) < 3){
out.println("YES");continue;
}
else{
int xx = 0,yy = 0,zz = 0;
xx = x[r] - x[l - 1];
yy = y[r] - y[l - 1];
zz = z[r] - z[l - 1];
int val = Math.max(zz,yy);
val = Math.max(val,xx);
if (val == xx){
if (yy < (val - 1) || zz < (val - 1)){
out.println("NO");
}
else {
out.println("YES");
}
}
else if (val == yy){
if (xx < (val - 1) || zz < (val - 1)){
out.println("NO");
}
else {
out.println("YES");
}
}
else if (val == zz){
if (yy < (val - 1) || xx < (val - 1)){
out.println("NO");
}
else {
out.println("YES");
}
}
}
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
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 | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 77425923bdafffe5a8eed982930a494f | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ayush.1731
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
String str=" "+in.next();
int len=str.length(); len--;
int noOfX[]=new int[len+1];
int noOfY[]=new int[len+1];
int noOfZ[]=new int[len+1];
noOfX[0]=noOfY[0]=noOfZ[0]=0;
for(int i=1;i<=len;i++){
// System.out.println(str.charAt(i));
if(str.charAt(i)=='x')
noOfX[i]=noOfX[i-1]+1;
else
noOfX[i]=noOfX[i-1];
if(str.charAt(i)=='y')
noOfY[i]=noOfY[i-1]+1;
else
noOfY[i]=noOfY[i-1];
if(str.charAt(i)=='z')
noOfZ[i]=noOfZ[i-1]+1;
else
noOfZ[i]=noOfZ[i-1];
}
String pre[]=new String[100005];
int XYZ[]=new int[3];
int a=1,b=1,c=0;
for(int i=3;i<=100000;i++){
if(i%3==0)
c++;
else
if(i%3==2)
b++;
if(i%3==1)
a++;
XYZ[0]=a;
XYZ[1]=b;
XYZ[2]=c;
Arrays.sort(XYZ);
pre[i]=Integer.toString(XYZ[0])+Integer.toString(XYZ[1])+Integer.toString(XYZ[2]);
}
int test=in.nextInt(),l,r;
for(int i=1;i<=test;i++){
l=in.nextInt();
r=in.nextInt();
XYZ[0]=noOfX[r]-noOfX[l-1];
XYZ[1]=noOfY[r]-noOfY[l-1];
XYZ[2]=noOfZ[r]-noOfZ[l-1];
Arrays.sort(XYZ);
String temp= Integer.toString(XYZ[0])+Integer.toString(XYZ[1])+Integer.toString(XYZ[2]);
int diff=r-l+1;
// System.out.println(pre[diff]+" "+temp);
if((diff)<=2){
System.out.println("YES");
}
else
if(pre[diff].equals(temp)){
System.out.println("YES");
}
else
System.out.println("NO");
}
}
}
class InputReader
{
BufferedReader in;
StringTokenizer tokenizer=null;
public InputReader(InputStream inputStream)
{
in=new BufferedReader(new InputStreamReader(inputStream));
}
public String next()
{
try{
while (tokenizer==null||!tokenizer.hasMoreTokens())
{
tokenizer=new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (IOException e)
{
return null;
}
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
class OutputWriter {
public PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer= new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 3651bed16a7cd995df3bafde1b33f575 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main {
FastIO in;
PrintWriter out;
int[][] sum;
int getSum(int c, int l, int r) {
int res = sum[c][r];
if (l != 0) {
res -= sum[c][l - 1];
}
return res;
}
// File names!!!
void solve() throws IOException {
char[] s = in.next().toCharArray();
int n = s.length;
sum = new int[3][n];
for (int i = 0; i < n; i++) {
int c = s[i] - 'x';
sum[c][i] = 1;
if (i != 0) {
for (int j = 0; j < 3; j++) {
sum[j][i] += sum[j][i - 1];
}
}
}
int[] s3 = new int[3];
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
for (int j = 0; j < 3; j++) {
s3[j] = getSum(j, l, r);
}
Arrays.sort(s3);
int len = r - l + 1;
boolean ok = len < 3;
if (len % 3 == 0) {
if (s3[0] == s3[1] && s3[1] == s3[2]) {
ok = true;
}
}
if (len % 3 == 1) {
if (s3[0] == s3[1] && s3[1] == s3[2] - 1) {
ok = true;
}
}
if (len % 3 == 2) {
if (s3[0] == s3[1] - 1 && s3[1] == s3[2]) {
ok = true;
}
}
if (ok) {
out.println("YES");
} else {
out.println("NO");
}
}
}
void run() {
try {
in = new FastIO();
solve();
in.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(abs(-1));
}
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception ignore) {
}
new Main().run();
}
class FastIO {
private BufferedReader in;
private StringTokenizer stok;
FastIO() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
FastIO(String s) throws FileNotFoundException {
if ("".equals(s)) {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} else {
in = new BufferedReader(new FileReader(s + ".in"));
out = new PrintWriter(s + ".out");
}
}
void close() throws IOException {
in.close();
out.close();
}
String next() {
while (stok == null || !stok.hasMoreTokens()) {
try {
stok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return stok.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 5c14fc06110dbdc716a4f1dcc38b432e | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
private void solve() throws IOException {
char[]s = nextToken().toCharArray();
int n = s.length;
int m = nextInt();
int[] cz = new int[n+1],
cy = new int[n+1],
cx = new int[n+1];
for(int i = 0; i < n; i++){
switch(s[i]){
case 'z':
cz[i+1]++;
break;
case 'x':
cx[i+1]++;
break;
case 'y':
cy[i+1]++;
break;
}
cz[i+1] += cz[i];
cy[i+1] += cy[i];
cx[i+1] += cx[i];
}
for(int i = 0; i < m; i++){
int l = nextInt(), r = nextInt();
int x = cx[r] - cx[l-1];
int z = cz[r] - cz[l-1];
int y = cy[r] - cy[l-1];
boolean yes = false;
if(r - l + 1 < 3)
yes = true;
else {
int c = (r-l+1)/3;
int h = (r-l+1)%3;
if(h == 0){
if(z == c && x == c && y == c)
yes = true;
} else if(h == 1){
if(z == c + 1 && x == y && x == c)
yes = true;
if(x == c + 1 && z == y && z == c)
yes = true;
if(y == c + 1 && x == z && x == c)
yes = true;
} else if(h == 2){
if(z == c + 1 && y == c+1 && x == c)
yes = true;
if(y == c + 1 && x == c+1 && z == c)
yes = true;
if(z == c + 1 && x == c+1 && y == c)
yes = true;
}
}
if(yes)
out.println("YES");
else
out.println("NO");
}
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | d0d264f63010cd720563dbb6b542ad6e | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
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);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
String str = in.readLine();
int count[][] = new int[3][str.length() + 1];
String valid = "xyz";
for (int i = 0;i < str.length(); i++){
count[0][i + 1] = count[0][i];
count[1][i + 1] = count[1][i];
count[2][i + 1] = count[2][i];
count[valid.indexOf(str.charAt(i))][i + 1]++;
}
int m = in.readInt();
for (int i = 0; i < m; i++){
int l = in.readInt();
int r = in.readInt();
int x = count[0][r] - count[0][l] + (str.charAt(l - 1) == 'x' ? 1:0);
int y = count[1][r] - count[1][l] + (str.charAt(l - 1) == 'y' ? 1:0);
int z = count[2][r] - count[2][l] + (str.charAt(l - 1) == 'z' ? 1:0);
int min = Math.min(x, Math.min(y,z));
x-= min;
y-= min;
z-= min;
if (r - l + 1 < 3) out.println("YES");
else if (x > 1 || y > 1 || z > 1) out.println("NO");
else out.println("YES");
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 9e0c3e1a26302ff4d256a5dab568125b | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 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.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
public class CopyOfSolution {
public static void main(String[] args) throws NumberFormatException, IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
String s = in.next();
int m = in.nextInt();
int n = s.length();
int[] x = new int[n];
int[] y = new int[n];
int[] z = new int[n];
int xc = 0;
int yc = 0;
int zc = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case 'x':
xc++;
break;
case 'y':
yc++;
break;
case 'z':
zc++;
break;
}
x[i] = xc;
y[i] = yc;
z[i] = zc;
}
for (int i = 0; i < m; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
// System.out.println("Solving for " + l + " " + r + " with " + (x[r] - x[l - 1]) + " " + (y[r] - y[l - 1])
// + " " + (z[r] - z[l - 1]));
out.println(solve(x[r] - ((l > 0) ? x[l - 1] : 0), y[r] - ((l > 0) ? y[l - 1] : 0), z[r]
- ((l > 0) ? z[l - 1] : 0)));
}
out.close();
}
private static String solve(int x, int y, int z) {
// TODO Auto-generated method stub
if (x + y + z < 3) {
return "YES";
}
if (x == 0 || y == 0 || z == 0) {
return "NO";
}
int min = Math.min(x, Math.min(y, z));
x = x - min;
y = y - min;
z = z - min;
int[] a = new int[3];
a[0] = x;
a[1] = y;
a[2] = z;
Arrays.sort(a);
if (x + y + z == 0) {
return "YES";
}
if (a[0] == 0 && (a[1] == 0 || a[1] == 1) && (a[2] == 1)) {
return "YES";
}
return "NO";
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 538064b1035e032076fa9fb6ce33df91 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine().trim();
int n = line.length();
int[][] tripples = new int[n][3];
for (int start = n - 1; start >= 0; --start) {
int[] inc = new int[]{
line.charAt(start) == 'x' ? 1 : 0,
line.charAt(start) == 'y' ? 1 : 0,
line.charAt(start) == 'z' ? 1 : 0};
if (start == n - 1) {
tripples[start] = inc;
} else {
tripples[start] = new int[]{
tripples[start + 1][0] + inc[0],
tripples[start + 1][1] + inc[1],
tripples[start + 1][2] + inc[2]};
}
}
StringBuilder sb = new StringBuilder();
int m = sc.nextInt();
for (; m > 0; --m) {
int l = sc.nextInt() - 1;
int r = sc.nextInt() - 1;
int[] tripple;
if (r == n - 1) {
tripple = tripples[l];
} else {
tripple = new int[] {
tripples[l][0] - tripples[r + 1][0],
tripples[l][1] - tripples[r + 1][1],
tripples[l][2] - tripples[r + 1][2]
};
}
int min = tripple[0];
for (int i = 0; i < 3; ++i) {
min = Math.min(min, tripple[i]);
}
int[] diff = new int[3];
for (int i = 0; i < 3; ++i) {
diff[i] = tripple[i] - min;
}
Arrays.sort(diff);
if (r - l + 1 < 3 ||
(diff[2] == 0 ||
(diff[2] == 1 && diff[1] == 0) ||
(diff[2] == 1 && diff[1] == 1))) {
sb.append("YES\n");
} else {
sb.append("NO\n");
}
}
System.out.print(sb.toString());
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | 5271996ec3ca201f3b3c46a8675bf50d | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Round215_C {
public void solve() throws Exception {
InputReader in = new InputReader();
char[] a = in.next().toCharArray();
int N = a.length;
int[] x = new int[N + 1];
int[] y = new int[N + 1];
int[] z = new int[N + 1];
for (int i = 0; i < N; i++) {
if (a[i] == 'x') {
x[i]++;
} else if (a[i] == 'y') {
y[i]++;
} else {
z[i]++;
}
int prevIndex = (i > 0) ? (i - 1) : N;
x[i] += x[prevIndex];
y[i] += y[prevIndex];
z[i] += z[prevIndex];
}
StringBuffer ret = new StringBuffer();
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int left = in.nextInt() - 1;
int right = in.nextInt() - 1;
if (right - left + 1 < 3) {
ret.append("YES");
} else {
int prevIndex = (left > 0) ? (left - 1) : N;
int xs = x[right] - x[prevIndex];
int ys = y[right] - y[prevIndex];
int zs = z[right] - z[prevIndex];
int min = Math.min(xs, Math.min(ys, zs));
xs -= min;
ys -= min;
zs -= min;
boolean valid = true;
if ((xs > 1 || ys > 1 || zs > 1))
valid = false;
ret.append(valid ? "YES" : "NO");
}
ret.append('\n');
}
System.out.print(ret);
}
public static void main(String[] args) throws Exception {
new Round215_C().solve();
}
static class InputReader {
BufferedReader in;
StringTokenizer st;
public InputReader() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(in.readLine());
}
public String next() throws IOException {
while (!st.hasMoreElements())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | e35b1e27e9f855bc4ea0b95bc52a7f54 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | //package R215;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class q3 {
public static void main(String[] args) {
Scanner s2 = new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
String s1=s2.nextLine();
int s[][]=new int[100001][3];
s[0][0]=s[0][1]=s[0][2]=0;
char a[]=new char[100001];
a=s1.toCharArray();
int w=0;
for(w=0;w<a.length;w++){
s[w+1][0]=s[w][0];
s[w+1][1]=s[w][1];
s[w+1][2]=s[w][2];
s[w+1][a[w]-120]++;
}
int q=s2.nextInt();
for(w=0;w<q;w++){
int e=s2.nextInt()-1;
int r=s2.nextInt();
int t=s[r][0]-s[e][0];
int y=s[r][1]-s[e][1];
int u=s[r][2]-s[e][2];
if((r-e<3)||(Math.max(t,Math.max(y,u))-Math.min(t,Math.min(y,u))<2))
System.out.println("YES");
else
System.out.println("NO");
}
}
private static long ncr(int i, int j) {
if(j==0){
return 1;
}
int k=0;
long ans=1;
while(k<j){
ans*=i-k;
ans/=k+1;
ans%=1000000007;
k++;
}
return ans%1000000007;
}
private static boolean sum(long i, int x, int y) {
int k=0;
while(i!=0){
k+=i%10;
i=i/10;
}
if(k<=y && k>=x)
return true;
else
return false;
}
private static long c(int i) {
return 0;
}
private static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | fcf0bed1051d9afbdb0cb5d5c9633328 | train_001.jsonl | 1385479800 | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.PriorityQueue;
/**
*
* @author Anextro
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
/////////////////////////
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new PrintWriter(System.out));
///////////////
String A = br.readLine();
int n = A.length();
int[][] d = new int[n][3];
if(A.charAt(n-1)=='x') d[n-1][0]=1;
else if(A.charAt(n-1)=='y') d[n-1][1]=1;
else d[n-1][2]=1;
for(int i=n-2;i>=0;i--){
char r = A.charAt(i);
if(r=='x') {d[i][0]=d[i+1][0]+1;d[i][1]=d[i+1][1];d[i][2]=d[i+1][2];}
else if(r=='y') {d[i][1]=d[i+1][1]+1;d[i][2]=d[i+1][2];d[i][0]=d[i+1][0];}
else {d[i][2] = d[i+1][2]+1;d[i][1]=d[i+1][1];d[i][0]=d[i+1][0];}
}
int m = Integer.parseInt(br.readLine());
for(int i=0;i<m;i++){
String[] ln1 = br.readLine().split(" ");
int l = Integer.parseInt(ln1[0])-1;int r = Integer.parseInt(ln1[1])-1;
//System.out.println(l+"na wa o "+r);
if((r-l+1)<3) {bw.append("YES"+"\n");}
else{
int x=0,y=0,z=0;
if(r==n-1){
x = d[l][0];
y = d[l][1];
z = d[l][2];
}
else{
x = d[l][0]-d[r+1][0];
y = d[l][1]-d[r+1][1];
z = d[l][2]-d[r+1][2];
}
////////////////////////
// System.out.println(x+"na wa o "+y+" "+z);
if(x==y){
if(z==x-1 || z==x || z==x+1) bw.append("YES"+"\n");
else bw.append("NO"+"\n");
}else if(x==z){
if(y==x-1 || y==x || y==x+1) bw.append("YES"+"\n");
else bw.append("NO"+"\n");
}else if(y==z){
if(x==z-1 || x==z || x==z+1) bw.append("YES"+"\n");
else bw.append("NO"+"\n");
}
else{
bw.append("NO"+"\n");
}
//////////////////////////
}
}
bw.close();
}
}
| Java | ["zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6"] | 1 second | ["YES\nYES\nNO\nYES\nNO"] | NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | Java 7 | standard input | [
"implementation",
"brute force"
] | 4868cbb812d222ffababb4103210a3f1 | The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). | 1,500 | For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. | standard output | |
PASSED | f1ed6139db1f50ab4e73fd9f326b7d42 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.math.BigInteger;
public class Main{
static PrintWriter out;
static InputReader ir;
static void solve(){
int n=ir.nextInt();
int[][] be=new int[n][];
for(int i=0;i<n;i++){
be[i]=ir.nextIntArray(2);
}
Arrays.sort(be,new Comparator<int[]>(){
public int compare(int[] p,int[] q){
return Integer.compare(p[0],q[0]);
}
});
int[] a=new int[n],b=new int[n];
for(int i=0;i<n;i++){
a[i]=be[i][0];
b[i]=be[i][1];
}
int[] dp=new int[n];
int mi=n;
for(int i=0;i<n;i++){
int pp=lower_bound(a,0,i-1,a[i]-b[i]);
dp[i]=i-pp+((pp-1)<0?0:dp[pp-1]);
mi=Math.min(n-1-i+dp[i],mi);
}
out.println(mi);
}
public static int lower_bound(int[] a,int fromIndex,int toIndex,int val){
if(a[fromIndex]>=val) return fromIndex;
if(a[toIndex]<val) return toIndex+1;
int lb=fromIndex-1,ub=toIndex;
while(ub-lb>1){
int mid=(ub+lb)/2;
if(a[mid]>=val){
ub=mid;
}
else{
lb=mid;
}
}
return ub;
}
public static void main(String[] args) throws Exception{
ir=new InputReader(System.in);
out=new PrintWriter(System.out);
solve();
out.flush();
}
static class InputReader {
private InputStream in;
private byte[] buffer=new byte[1024];
private int curbuf;
private int lenbuf;
public InputReader(InputStream in) {this.in=in; this.curbuf=this.lenbuf=0;}
public boolean hasNextByte() {
if(curbuf>=lenbuf){
curbuf= 0;
try{
lenbuf=in.read(buffer);
}catch(IOException e) {
throw new InputMismatchException();
}
if(lenbuf<=0) return false;
}
return true;
}
private int readByte(){if(hasNextByte()) return buffer[curbuf++]; else return -1;}
private boolean isSpaceChar(int c){return !(c>=33&&c<=126);}
private void skip(){while(hasNextByte()&&isSpaceChar(buffer[curbuf])) curbuf++;}
public boolean hasNext(){skip(); return hasNextByte();}
public String next(){
if(!hasNext()) throw new NoSuchElementException();
StringBuilder sb=new StringBuilder();
int b=readByte();
while(!isSpaceChar(b)){
sb.appendCodePoint(b);
b=readByte();
}
return sb.toString();
}
public int nextInt() {
if(!hasNext()) throw new NoSuchElementException();
int c=readByte();
while (isSpaceChar(c)) c=readByte();
boolean minus=false;
if (c=='-') {
minus=true;
c=readByte();
}
int res=0;
do{
if(c<'0'||c>'9') throw new InputMismatchException();
res=res*10+c-'0';
c=readByte();
}while(!isSpaceChar(c));
return (minus)?-res:res;
}
public long nextLong() {
if(!hasNext()) throw new NoSuchElementException();
int c=readByte();
while (isSpaceChar(c)) c=readByte();
boolean minus=false;
if (c=='-') {
minus=true;
c=readByte();
}
long res = 0;
do{
if(c<'0'||c>'9') throw new InputMismatchException();
res=res*10+c-'0';
c=readByte();
}while(!isSpaceChar(c));
return (minus)?-res:res;
}
public double nextDouble(){return Double.parseDouble(next());}
public BigInteger nextBigInteger(){return new BigInteger(next());}
public int[] nextIntArray(int n){
int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n){
long[] a=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
public char[][] nextCharMap(int n,int m){
char[][] map=new char[n][m];
for(int i=0;i<n;i++) map[i]=next().toCharArray();
return map;
}
}
} | Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | 660989f244a5c0f0e01bdab11aa796e4 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | // -*- coding: utf-8 -*-
//import java.awt.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream;
if (args.length > 0 && args[0].equals("devTesting")) {
try {
inputStream = new FileInputStream(args[1]);
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
} else
inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
int[] a, b;
int[][] state;
void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
a = new int[n];
b = new int[(int) 1e6 + 1];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
b[a[i]] = in.nextInt();
}
Arrays.sort(a);
state = new int[n][2];
for (int[] i : state)
Arrays.fill(i, -1);
int ans = n - go(n - 1, 1);
out.println(ans);
}
int go(int p, int d) {
if (p < 0)
return 0;
if (state[p][d] != -1)
return state[p][d];
int[] nxp = {p - 1, p - 1};
nxp[1] = Arrays.binarySearch(a, 0, p, a[p] - b[a[p]] - 1);
if (nxp[1] < 0)
nxp[1] = ~nxp[1] - 1;
int ans = go(nxp[1], 0) + 1;
if (d == 1)
ans = Math.max(ans, go(nxp[0], 1));
state[p][d] = ans;
return ans;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public boolean hasInput() {
try {
if (tokenizer != null && tokenizer.hasMoreTokens()) {
return true;
}
reader.mark(1);
int ch = reader.read();
if (ch != -1) {
reader.reset();
return true;
}
return false;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | 89e65c968736986810be096b42ffa2a3 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | // -*- coding: utf-8 -*-
//import java.awt.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
InputStream inputStream;
if (args.length > 0 && args[0].equals("devTesting")) {
try {
inputStream = new FileInputStream(args[1]);
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
} else
inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
PairII[] ab;
int[][] state;
class PairII implements Comparable<PairII> {
int a, b;
PairII(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(PairII other) {
if (this.a != other.a)
return this.a - other.a;
return this.b - other.b;
}
}
void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
ab = new PairII[n];
for (int i = 0; i < n; ++i) {
int a = in.nextInt();
int b = in.nextInt();
ab[i] = new PairII(a, b);
}
Arrays.sort(ab);
state = new int[n][2];
for (int[] i : state)
Arrays.fill(i, -1);
int ans = n - go(n - 1, 1);
out.println(ans);
}
int go(int p, int d) {
if (p < 0)
return 0;
if (state[p][d] != -1)
return state[p][d];
int[] nxp = {p - 1, p - 1};
nxp[1] = Arrays.binarySearch(ab, 0, p, new PairII(ab[p].a - ab[p].b - 1, Integer.MAX_VALUE));
if (nxp[1] < 0)
nxp[1] = ~nxp[1] - 1;
int ans = go(nxp[1], 0) + 1;
if (d == 1)
ans = Math.max(ans, go(nxp[0], 1));
state[p][d] = ans;
return ans;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public boolean hasInput() {
try {
if (tokenizer != null && tokenizer.hasMoreTokens()) {
return true;
}
reader.mark(1);
int ch = reader.read();
if (ch != -1) {
reader.reset();
return true;
}
return false;
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | 9b259aa1d30883469610d104a43d379a | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Round336C {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int max = 0;
Beacon bc[] = new Beacon[n];
for(int i=0; i<n; i++){
bc[i] = new Beacon(sc.nextInt()+1,sc.nextInt());
max = Math.max(bc[i].a, max);
}
Arrays.sort(bc);
int k = 0;
int toThis[] = new int[max+1];
int lastAlive[] = new int[max+1];
for(int i=1; i<toThis.length; i++){
if(i == bc[k].a){
if(i-bc[k].b-1>=0){
//System.out.println(k+" "+bc[k].b+" "+bc[k].a);
toThis[i] = 1+toThis[i-bc[k].b-1];
}
else
toThis[i] = 1;
lastAlive[i] = k+1;
k++;
}
else{
lastAlive[i] = lastAlive[i-1];
toThis[i] = toThis[i-1];
}
}
// System.out.println(Arrays.toString(lastAlive));
// System.out.println(Arrays.toString(toThis));
int min = 999999999;
for(int i=0; i<n; i++){
min = Math.min(n-toThis[bc[i].a],min);
}
System.out.println(min);
}
static class Beacon implements Comparable<Beacon>{
int a;
int b;
public Beacon(int x, int y){a = x; b = y;}
@Override
public int compareTo(Beacon arg0) {
return this.a - arg0.a;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(FileReader f) {
br = new BufferedReader(f);
}
public boolean ready() throws IOException {
return br.ready();
}
Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | 227f2c7e653237f4ccbfeb1d591d43a0 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 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.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
public class Solution1 implements Runnable
{
static final long MAX = 1000000007L;
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Solution1(),"Solution1",1<<26).start();
}
long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
// method to return LCM of two numbers
long lcm(long a, long b)
{
return (a*b)/gcd(a, b);
}
final long bit = 60;
public void run()
{
InputReader sc= new InputReader(System.in);
PrintWriter w= new PrintWriter(System.out);
int n = sc.nextInt();
Pair[] p = new Pair[n];
for(int i = 0;i < p.length;i++){
p[i] = new Pair(sc.nextInt(),sc.nextInt());
}
Arrays.sort(p);
int[] ans = new int[n];
for(int i = 0;i < p.length;i++){
if(i == 0){
ans[i] = 0;
}else{
long pow = (p[i].a - p[i].b);
int tmp = bsearch(p, pow);
if(tmp == 0){
ans[i] = i;
}else if(tmp == i){
ans[i] = ans[tmp-1];
}else{
ans[i] = (i - (tmp)) + ans[tmp-1];
}
}
}
long fans = Long.MAX_VALUE;
for(int i = 0;i < n;i++){
fans = Math.min(fans,ans[i] + (n - i - 1));
}
w.println(fans);
w.close();
}
int bsearch(Pair[] p,long pow){
int l = 0;
int r = p.length-1;
int ans = -1;
int mid = l + (r - l)/2;
int remem = -1;
HashSet<Integer> hset = new HashSet();
while(true){
hset.add(mid);
if(fun(mid,p,pow)){
r = mid - 1;
}else{
l = mid + 1;
}
remem = mid;
mid = l + (r - l)/2;
if(hset.contains(mid)){
boolean ans1 = fun(mid,p,pow);
boolean ans2 = fun(remem,p,pow);
if(ans1 && ans2){
ans = Math.min(mid,remem);
}else if(ans1){
ans = mid;
}else if(ans2){
ans = remem;
}
break;
}
}
return ans;
}
boolean fun(int mid,Pair[] p,long pow){
if(pow <= p[mid].a){
return true;
}
return false;
}
static class Pair implements Comparable<Pair>{
int a;
long b;
Pair(){}
Pair(int a,long b){
this.a = a;
this.b = b;
}
public int compareTo(Pair p){
return Integer.compare(this.a,p.a);
}
}
} | Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | dfbf9e2927893f2d9e0596fa59bd13d5 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | import java.util.*;
import java.io.*;
public class ChainReaction {
public static void main(String[] args) throws IOException {
// Scanner in = new Scanner(new File("input.txt"));
Scanner in = new Scanner(System.in);
int b = in.nextInt();
int maxPos = -1;
int[] beacons = new int[1_000_001];
for (int i = 0; i < b; i++) {
int pos = in.nextInt();
beacons[pos] = in.nextInt();
}
int[] dp = new int[1_000_001];
if (beacons[0] != 0) {
dp[0] = 1;
}
int max = -1;
for (int i = 1; i < dp.length; i++) {
if (beacons[i] == 0) {
dp[i] = dp[i-1];
} else {
if (beacons[i] >= i) {
dp[i] = 1;
} else {
dp[i] = dp[i - beacons[i] - 1] + 1;
}
}
if (dp[i] > max) {
max = dp[i];
}
}
System.out.println(b - max);
// int[] dp = new int[beacons.get(beacons.size() - 1).pos + 1]; // dp[i] = # of beacons destroyed if beacon i is set off
// for (int i = 0; i < dp.length; i++) {
//
// }
}
static int destroyed(ArrayList<Beacon> beacons, int index) {
if (index == 0) {
return 0;
}
int destroyed = 0;
int i = index - 1;
while (i >= 0 && beacons.get(i).pos >= beacons.get(index).pos - beacons.get(index).pow) {
i--;
destroyed++;
}
return destroyed + destroyed(beacons, i);
}
}
class Beacon {
int pos, pow;
public Beacon(int ps, int pw) {
pos = ps;
pow = pw;
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | b0566ab91c86297c68f654f37878cd1c | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | import java.util.*;
public class codeforces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] dp = new int[1000001];
int[] beacon = new int[1000001];
for(int i = 0; i < n; ++i) {
beacon[sc.nextInt()] = sc.nextInt();
}
int potato = 0;
if(beacon[0] != 0)
dp[0] = 1;
for(int i = 1; i < 1000001; ++i) {
if(beacon[i] == 0)
dp[i] = dp[i - 1];
else {
if(beacon[i] >= i)
dp[i]= 1;
else
dp[i] = dp[i - beacon[i] - 1] + 1;
}
potato = Math.max(potato, dp[i]);
}
System.out.println(n - potato);
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | d4faa8640b6db6743ac7ebd556b67602 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | import java.util.Scanner;
public class codef8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int beacon[] = new int[1000001];
int pos[] = new int[num];
for (int i = 0; i < num; i++) {
int position = sc.nextInt();
beacon[position] = sc.nextInt();
pos[i] = position;
}
int dp[] = new int[1000001];
int max = 1;
if (beacon[0] != 0)
dp[0] = 1;
for (int i = 1; i <= 1000000; i++) {
if (beacon[i] == 0) {
dp[i] = dp[i-1];
}
else {
int j = i - beacon[i] - 1;
if (j < 0) {
dp[i] = 1;
}
else {
dp[i] = dp[j] + 1;
}
}
max = Math.max(max, dp[i]);
}
System.out.println(num-max);
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | 00ae3bca681699e0507aeaa955b68945 | train_001.jsonl | 1450888500 | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed. | 256 megabytes | import java.util.Scanner;
public class codef8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int beacon[] = new int[1000001];
int pos[] = new int[num];
for (int i = 0; i < num; i++) {
int position = sc.nextInt();
beacon[position] = sc.nextInt();
pos[i] = position;
}
int dp[] = new int[1000001];
int max = 0;
if (beacon[0] != 0)
dp[0] = 1;
for (int i = 1; i <= 1000000; i++) {
if (beacon[i] == 0) {
dp[i] = dp[i-1];
}
else {
int j = i - beacon[i] - 1;
if (j < 0) {
dp[i] = 1;
}
else {
dp[i] = dp[j] + 1;
}
}
max = Math.max(max, dp[i]);
}
System.out.println(num-max);
}
}
| Java | ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"] | 2 seconds | ["1", "3"] | NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42. | Java 8 | standard input | [
"dp"
] | bcd689387c9167c7d0d45d4ca3b0c4c7 | The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0 ≤ ai ≤ 1 000 000, 1 ≤ bi ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai ≠ aj if i ≠ j. | 1,600 | Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added. | standard output | |
PASSED | c0b753229c18c08a9e0347c522b53388 | train_001.jsonl | 1336145400 | As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
double s=input.scanInt();
double a=input.scanInt();
double b=input.scanInt();
double c=input.scanInt();
if(a==0 && b==0 && c==0) {
System.out.println(0+" "+0+" "+0);
return;
}
System.out.print((a*s)/(a+b+c));
System.out.print(" ");
System.out.print((b*s)/(a+b+c));
System.out.print(" ");
System.out.print((c*s)/(a+b+c));
System.out.println();
}
}
| Java | ["3\n1 1 1", "3\n2 0 0"] | 2 seconds | ["1.0 1.0 1.0", "3.0 0.0 0.0"] | null | Java 11 | standard input | [
"number theory",
"probabilities",
"math"
] | 0a9cabb857949e818453ffe411f08f95 | The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists. | 1,800 | Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) = - ∞. | standard output | |
PASSED | cf00aa5db677170db1d5b6327dfe9cfe | train_001.jsonl | 1336145400 | As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa·yb·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≤ x, y, z; x + y + z ≤ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1. | 256 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF186D extends PrintWriter {
CF186D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF186D o = new CF186D(); o.main(); o.flush();
}
void main() {
int s = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = a + b + c;
if (d == 0)
println("0 0 " + s);
else {
double t = (double) s / d;
println(a * t + " " + b * t + " " + c * t);
}
}
}
| Java | ["3\n1 1 1", "3\n2 0 0"] | 2 seconds | ["1.0 1.0 1.0", "3.0 0.0 0.0"] | null | Java 11 | standard input | [
"number theory",
"probabilities",
"math"
] | 0a9cabb857949e818453ffe411f08f95 | The first line contains a single integer S (1 ≤ S ≤ 103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0 ≤ a, b, c ≤ 103) — the numbers that describe the metric of mushroom scientists. | 1,800 | Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) = - ∞. | standard output | |
PASSED | a5608bf14a71f64153bb8acc5ec017bd | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Solution1366C {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int T = in.nextInt();
while (T-- > 0) {
int n = in.nextInt();
int m = in.nextInt();
int[][] mx = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mx[i][j] = in.nextInt();
}
}
solve(n, m, mx);
}
}
private static void solve(int n, int m, int[][] mx) {
int[][] dp = new int[2][n + m - 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[mx[i][j]][i + j]++;
}
}
int sum = 0;
for (int i = 0; i < (n + m - 1) / 2; i++) {
int zeros = dp[0][i] + dp[0][n + m - i - 2];
int ones = dp[1][i] + dp[1][n + m - i - 2];
sum += Math.min(zeros, ones);
}
System.out.println(sum);
}
}
| Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | aed5a8cc1bcd1210fed7da057b0d251e | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Abc{
static int arr[][];
static int visited1[][];
static int visited2[][];
static int n,m;
public static void main(String[] args) throws java.lang.Exception {
InputReader sc = new InputReader(System.in);
int test=sc.nextInt();
for (int xx=0;xx<test;xx++){
solve(sc);
}
}
static void dfs1(int i,int j,int h){
visited1[i][j]=h;
if (ok(i,j+1) && visited1[i][j+1]==0){
dfs1(i,j+1,h+1);
}
if (ok(i+1,j) && visited1[i+1][j]==0){
dfs1(i+1,j,h+1);
}
}
static boolean ok(int i, int j){
return i>=0 && j>=0 && i<n && j<m;
}
static void solve(InputReader sc){
n=sc.nextInt();m=sc.nextInt();
arr=new int[n][m];
int i=0;
while (i<n){
int j=0;
while (j<m){
arr[i][j]=sc.nextInt();
j++;
}
i++;
}
visited1 =new int[n][m];
visited2 =new int[n][m];
dfs1(0,0,1);
dfs2(n-1,m-1,1);
boolean vis[][]=new boolean[n][m];
int ans=0;
int l=(n+m-2)/2;
if ((n+m-2)%2==1)l++;
i=0;
while (i<=l){
int cnt[]=new int[2];
for (int j=0;j<n;j++){
for (int k=0;k<m;k++){
if (visited1[j][k]==i){
cnt[arr[j][k]]++;
vis[j][k]=true;
}
}
}
for (int j=0;j<n;j++){
for (int k=0;k<m;k++){
if (visited2[j][k]==i)cnt[arr[j][k]]++;
}
}
ans+=Math.min(cnt[0],cnt[1]);
i++;
}
System.out.println(ans);
}
static void dfs2(int i,int j,int height){
visited2[i][j]=height;
if (ok(i,j-1) && visited2[i][j-1]==0){
dfs2(i,j-1,height+1);
}
if (ok(i-1,j) && visited2[i-1][j]==0) {
dfs2(i-1,j,height+1);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt());
if (c < '0' || c > '9') throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt());
if (c < '0' || c > '9') throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | 280cb3b49c2586285649e812e8b37333 | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main {
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception {}
void solve(int TC) throws Exception{
int n = ni(), m = ni();
int[][] val = new int[2][n+m-1];
for(int i = 0; i< n; i++)
for(int j = 0; j< m; j++)
val[ni()][i+j]++;
int ans = 0;
for(int i = 0, j = n+m-2; i< j; i++, j--)
ans += Math.min(val[0][i]+val[0][j], val[1][i]+val[1][j]);
pn(ans);
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
static void debug(Object... o){System.out.println(Arrays.deepToString(o));}
final long IINF = (long)2e18;
final int INF = (int)1e6+2;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = true, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
int[][] make(int n, int[] from, int[] to, int e, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int[] from, int[] to, int e, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | bf6522f8b13e43a836ca208c4ff78836 | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Built using my Brain
* Actual solution is at the bottom
*
* @author Lenard Hoffstader
*/
public class cfjava
{
public static void main(String[] args)
{
OutputStream outputStream = System.out;
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(outputStream);
PROBLEM solver = new PROBLEM();
int t=1;
t = in.nextInt();
for(int i=0;i<t;i++){
solver.solve(in, out);
}
out.close();
}
static class PROBLEM
{
public void solve(FastReader in,PrintWriter out)
{
int n = in.nextInt();
int m = in.nextInt();
int mat[][] = new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
mat[i][j] = in.nextInt();
}
}
int len = n+m-2;
if(len%2==0){len=len/2-1;}
else len/=2;
int dp[][] = new int[2][len+3];
boolean vis[][] = new boolean[n][m];
Queue<pair<Integer,pair<Integer,Integer>>> q = new LinkedList<>();
q.add(new pair(0,new pair(0,0)));
while(!q.isEmpty()){
int l = q.peek().x;
int x = q.peek().y.x;
int y = q.poll().y.y;
if(l>len || vis[x][y]){continue;}
vis[x][y]=true;
// System.out.println("x="+x+" y="+y);
dp[mat[x][y]][l]++;
if(x+1<n && !vis[x+1][y])q.add(new pair(l+1,new pair(x+1,y)));
if(y+1<m && !vis[x][y+1])q.add(new pair(l+1,new pair(x,y+1)));
}
q.add(new pair(0,new pair(n-1,m-1)));
while(!q.isEmpty()){
int l = q.peek().x;
int x = q.peek().y.x;
int y = q.poll().y.y;
if(l>len || vis[x][y]){continue;}
vis[x][y]=true;
// System.out.println("x="+x+" y="+y);
dp[mat[x][y]][l]++;
if(x-1>=0 && !vis[x-1][y])q.add(new pair(l+1,new pair(x-1,y)));
if(y-1>=0 && !vis[x][y-1])q.add(new pair(l+1,new pair(x,y-1)));
}
int ans=0;
for(int i=0;i<=len;i++){
// out.println(dp[0][i] +" "+dp[1][i]);
ans+=Math.min(dp[0][i],dp[1][i]);
}
out.println(ans);
}
}
static class pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<pair<U, V>>
{
public U x;
public V y;
public pair(U x, V y) {
this.x = x;
this.y = y;
}
public int compareTo(pair<U, V> other) {
int i = x.compareTo(other.x);
if (i != 0) return i;
return y.compareTo(other.y);
}
public String toString() {
return x.toString() + " " + y.toString();
}
public boolean equals(Object obj){
if (this.getClass() != obj.getClass()) return false;
pair<U, V> other = (pair<U, V>) obj;
return x.equals(other.x) && y.equals(other.y);
}
public int hashCode(){
return 31 * x.hashCode() + y.hashCode();
}
}
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());}
boolean nextBoolean(){return !(nextInt()==0);}
// boolean nextBoolean(){return Boolean.parseBoolean(next());}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e){e.printStackTrace();}
return str;
}
}
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | 4cf81c6400defcfb958e1b14e194eb43 | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes |
import java.util.*;
import java.io.*;
public class PalindromicPaths {
// https://codeforces.com/contest/1366/problem/C
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("PalindromicPaths"));
int t = Integer.parseInt(in.readLine());
for (int k=0; k<t; k++ ) {
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arr = new int[n][m];
for (int i=0; i<n; i++) {
st = new StringTokenizer(in.readLine());
for (int j=0; j<m; j++ ) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
int max = n+m-1;
int[] ones = new int[max];
int[] zeroes = new int[max];
for (int sum = 0; sum < max; sum++ ) {
int curones =0;
int curzeroes = 0;
for (int row = 0; row < n; row++) {
int col = sum - row;
if (col < 0 || col >= m) continue;
if (arr[row][col] == 1) curones++;
else curzeroes++;
}
ones[sum] = curones;
zeroes[sum] = curzeroes;
}
int total =0;
for (int i=0; i< max; i++) {
int opp = max - i - 1;
if (i >= opp) break;
int total_ones = ones[i] + ones[opp];
int total_zeroes = zeroes[i] + zeroes[opp];
if (total_ones > total_zeroes) {
total += total_zeroes;
}
else {
total += total_ones;
}
}
System.out.println(total);
}
}
}
/*
Every diagonal will have to be the same, except for the middle one
Ex.
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
The first and last move have to be the same. 1 = 1
Second and second to last moves. These are already the same
0
0 0
0
Third and third to last moves. These are not all the same. Because there are
4 1's and 2 0's, it is more optimal to change the 2 0's into 1's
1 1
0 0
1 1
Fourth and fourth to last. Because there are
4 1's and 2 0's, it is more optimal to change the 2 0's into 1's
1 1
0 0
1 1
Fifth and fifth to last. Though, the fifth IS the fifth to last!
Therefore this is the middle, and so nothing needs to be changed.
*/ | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | c2256695bf5526a456215c346a927aff | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.io.*;
import java.util.*;
//import javafx.util.*;
import java.math.*;
//import java.lang.*;
public class Main
{
// static int n;
// static HashSet<Integer> adj[];
// static int dist[];
// static int remove[];
// static boolean isLeaf[];
// static Long dp[][];
// static int arr[];
// static boolean ok;
// static long arr[];
// static long sum[];
// static boolean ok;
static long mod=1000000007;
static final long oo=(long)1e18;
public static void main(String[] args) throws IOException {
// Scanner sc=new Scanner(System.in);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
br = new BufferedReader(new InputStreamReader(System.in));
int test=nextInt();
// int test=1;
outer: while(test--!=0){
int n=nextInt();
int m=nextInt();
int size=((n+m-1)/2);
int zero[]=new int[size];
int one[]=new int[size];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int a=nextInt();
int idx=Math.min((i+j),(n+m-1)-(i+j+1));
if(idx<size){
// continue;
if(a==0){
zero[idx]++;
}
else{
one[idx]++;
}
}
}
}
int ans=0;
for(int i=0;i<size;i++){
ans+=Math.min(zero[i],one[i]);
// pw.println(Math.min(zero[i],one[i]));
}
pw.println(ans);
}
pw.close();
}
static class Pair implements Comparable<Pair>{
int x;int y;
Pair(int x,int y){
// this.index=index;
this.x=x;
this.y=y;
//this.z=z;
}
public int compareTo(Pair p){
return x-p.x;
}
}
static void update(long tree[],int idx,long val){
while(idx<100006){
tree[idx]+=val;
idx+=(idx)&(-idx);
}
}
static long sum(long tree[],int idx){
long sum=0;
while(idx>0){
sum+=tree[idx];
idx-=(idx)&(-idx);
}
return sum;
}
public static BufferedReader br;
public static StringTokenizer st;
public static String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public static Integer nextInt() {
return Integer.parseInt(next());
}
public static Long nextLong() {
return Long.parseLong(next());
}
public static Double nextDouble() {
return Double.parseDouble(next());
}
// static class Pair{
// int x;int y;
// Pair(int x,int y,int z){
// this.x=x;
// this.y=y;
// // this.z=z;
// // this.z=z;
// // this.i=i;
// }
// }
// static class sorting implements Comparator<Pair>{
// public int compare(Pair a,Pair b){
// //return (a.y)-(b.y);
// if(a.y==b.y){
// return -1*(a.z-b.z);
// }
// return (a.y-b.y);
// }
// }
static long ncr(long n,long r){
if(r==0)
return 1l;
long val=ncr(n-1,r-1);
val=(n*val);
val=(val/r);
return val;
}
public static int[] na(int n)throws IOException{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = nextInt();
return a;
}
static class query implements Comparable<query>{
int l,r,idx,block;
static int len;
query(int l,int r,int i){
this.l=l;
this.r=r;
this.idx=i;
this.block=l/len;
}
public int compareTo(query a){
return block==a.block?r-a.r:block-a.block;
}
}
// static class sorting implements Comparator<Pair>{
// public int compare(Pair a1,Pair a2){
// if(o1.a==o2.a)
// return (o1.b>o2.b)?1:-1;
// else if(o1.a>o2.a)
// return 1;
// else
// return -1;
// }
// }
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 ||
n % 3 == 0)
return false;
for (int i = 5;
i * i <= n; i = i + 6)
if (n % i == 0 ||
n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// To compute x^y under modulo m
static long power(long x, long y, long m){
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
// (1,1)
// (3,2) (3,5)
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | 2c3e9d5b1a6e325648448dad76ceed67 | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
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);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.nextInt();
return array;
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int mod = (int)(1e9+7);
public static long pow(long a,long b)
{
long ans = 1;
while(b> 0)
{
if((b & 1)==1){
ans = (ans*a) % mod;
}
a = (a*a) % mod;
b = b>>1;
}
return ans;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
//IOUtils io = new IOUtils();
int t = in.nextInt();
while(t-- >0)
{
int n = in.nextInt();
int m = in.nextInt();
int[][] arr = new int[n][m];
for(int i=0;i<n;i++)
arr[i] = in.nextIntArray(m);
Map<Integer,Integer> ones = new HashMap<>();
Map<Integer,Integer> zeros = new HashMap<>();
int total = (n-1) + (m-1);
int half = total/2;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int dist = i+j;
if(dist>half)
{
dist = total - dist;
}
if(arr[i][j]==0)
{
zeros.put(dist,zeros.getOrDefault(dist, 0)+1);
}
else{
ones.put(dist,ones.getOrDefault(dist, 0)+1);
}
}
}
int res = 0;
for(int i=0;i<(total+1)/2;i++)
{
int o = ones.getOrDefault(i, 0);
int z = zeros.getOrDefault(i, 0);
res+=Math.min(o,z);
}
out.printLine(res);
}
out.flush();
out.close();
}
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | 7c09d6157096ae80a7d0a7077725a206 | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = input.nextInt();
while(t-->0) {
int n = input.nextInt();
int m = input.nextInt();
int arr[][];
if(n<m) {
arr = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
arr[j][i] = input.nextInt();
}
}
int temp = n;
n=m;
m=temp;
}
else {
arr= new int[n][m];
for(int i =0; i<n; i++) {
for(int j =0; j<m; j++) {
arr[i][j] = input.nextInt();
}
}
}
int count = 0;
int pathLen = m+n-1;
int a = 0;
int b = m+n-2;
while(a<b) {
int count0 = 0;
int count1 = 0;
for(int i=a, j=0; i>=0&&j<=m-1;i--,j++) {
if(arr[i][j]==0) {
count0++;
}
else {
count1++;
}
}
for(int i=b-m+1, j=m-1; i<=n-1&&j>=0; i++,j--) {
if(arr[i][j]==0) {
count0++;
}
else {
count1++;
}
}
if(count0==0||count1==0) {
//pass
}
else {
if(count0>count1) {
count+=count1;
}
else {
count+=count0;
}
}
a++;
b--;
}
System.out.println(count);
}
input.close();
}
}
| Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | a28e8aa934da16705a2060dd88e97aee | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
//Sub_To_Errichto
public class Main {
//static final long MOD = 1000000007L;
static final long MOD = 998244353L;
static final int INF = 50000000;
static final int NINF = -500000000;
static final long BASE = 31L;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int Q = sc.ni();
for (int q = 0; q < Q; q++) {
int N = sc.ni();
int M = sc.ni();
int P = N+M-1;
int[][] cnt = new int[P/2][2];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
int m = sc.ni();
int d = i+j;
if (d < P/2) {
cnt[d][m] += 1;
} else if (!(P%2==1 && d==P/2)) {
cnt[P-1-d][m] += 1;
}
}
}
int ans = 0;
for (int i = 0; i < P/2; i++)
ans += Math.min(cnt[i][0],cnt[i][1]);
pw.println(ans);
}
pw.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output | |
PASSED | c0b84390bf2c6b6b3a9829a5e4aa0d0b | train_001.jsonl | 1591886100 | You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic. | 256 megabytes | import java.util.*;
public class c89{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while(t-->0){
int n = s.nextInt();
int m = s.nextInt();
int arr[][] = new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
arr[i][j] = s.nextInt();
}
}
int ans = 0;
int ai=0;
int aj=0;
// int ca = 0;
int bi=n-1;
int bj=m-1;
// int cb = m-1;
int count = (m+n-1)/2;
while(count-->0){
int zeros = 0;
int ones = 0;
int i=ai;
int j=aj;
while(j>=0&&i<n){//////
if(arr[i][j]==0){
zeros++;
}else{
ones++;
}
i++;
j--;
}
aj++;
if(aj>=m){
aj--;
ai++;
}
i=bi;
j=bj;
while(i>=0&&j<m){
if(arr[i][j]==0){
zeros++;
}else{
ones++;
}
i--;
j++;
}
bj--;
if(bj<0){
bj++;
bi--;
}
// System.out.println("0s: "+zeros);
// System.out.println("1s: "+ones);
ans+=Math.min(zeros,ones);
}
System.out.println(ans);
}
}
} | Java | ["4\n2 2\n1 1\n0 1\n2 3\n1 1 0\n1 0 0\n3 7\n1 0 1 1 1 1 1\n0 0 0 0 0 0 0\n1 1 1 1 1 0 1\n3 5\n1 0 1 0 0\n1 1 1 1 0\n0 0 1 0 0"] | 1.5 seconds | ["0\n3\n4\n4"] | NoteThe resulting matrices in the first three test cases: $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ | Java 11 | standard input | [
"greedy",
"math"
] | b62586b55bcfbd616d936459c30579a6 | The first line contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 30$$$) — the dimensions of the matrix. Then $$$n$$$ lines follow, the $$$i$$$-th line contains $$$m$$$ integers $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$). | 1,500 | For each test case, print one integer — the minimum number of cells you have to change so that every path in the matrix is palindromic. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.