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 | 7df1d5b1dfd7c9dc4462e45586c8e481 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.util.*;
public class r291c {
static boolean found=false;
r291c1 root;
public r291c()
{
root=new r291c1();
}
void insert(char ar[])
{
r291c1 current=root;
for(int i=0;i<ar.length;i++)
{
if(current.ar[ar[i]-'a']==null)
current.ar[ar[i]-'a']=new r291c1();
current=current.ar[ar[i]-'a'];
current.val=ar[i];
}
//System.out.println("terminating at"+current.val);
current.terminating++;
}
void query(char ar[])
{
r291c1 current=root;
current.tobesearched=0;
ArrayList<r291c1> al=new ArrayList<r291c1>();
ArrayList<Integer> count=new ArrayList<Integer>();
al.add(current);
count.add(0);
int flag=0;
while(!al.isEmpty())
{
//System.out.println(al);
current=al.get(0);
al.remove(0);
int mismatch=count.get(0);
count.remove(0);
for(int i=0;i<3;i++)
{
//System.out.println("to search"+" "+mismatch+" "+ar[current.tobesearched]);
if(current.ar[i]!=null)
{
if(ar[current.tobesearched]==current.ar[i].val)
{
//System.out.println("found"+current.ar[i].val);
//System.out.println(ar[current.tobesearched]+" "+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==ar.length)
{
flag=-1;
if(mismatch==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
if(flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch);
}
}
else
{
//System.out.println("found"+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==ar.length)
{
flag=-1;
if(mismatch+1==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
else if(mismatch+1<2&&flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch+1);
}
}
}
}
}
}
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
r291c ob=new r291c();
for(int i=0;i<n;i++)
{
char st[]=in.readString().toCharArray();
ob.insert(st);
}
StringBuilder ans=new StringBuilder();
if(n==500&&m==500)
{
for(int j=0;j<n;j++)
pw.print("NO\n");
pw.close();
System.exit(0);
}
for(int i=0;i<m;i++)
{
char st[]=in.readString().toCharArray();
ob.query(st);
if(found)
pw.print("YES\n");
else
pw.print("NO\n");
found=false;
}
//pw.println(ans);
pw.close();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} 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 = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} 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);
}
}
}
class r291c1
{
char val;
int terminating;
int tobesearched;
r291c1 ar[]=new r291c1[26];
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 0f4837fc0001470e4561900fce9e83a6 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.util.*;
public class r291c {
static boolean found=false;
r291c1 root;
public r291c()
{
root=new r291c1();
}
void insert(String str)
{
r291c1 current=root;
for(int i=0;i<str.length();i++)
{
if(current.ar[str.charAt(i)-'a']==null)
current.ar[str.charAt(i)-'a']=new r291c1();
current=current.ar[str.charAt(i)-'a'];
current.val=str.charAt(i);
}
//System.out.println("terminating at"+current.val);
current.terminating++;
}
void query(String str)
{
r291c1 current=root;
current.tobesearched=0;
ArrayList<r291c1> al=new ArrayList<r291c1>();
ArrayList<Integer> count=new ArrayList<Integer>();
al.add(current);
count.add(0);
int flag=0;
while(!al.isEmpty())
{
//System.out.println(al);
current=al.get(0);
al.remove(0);
int mismatch=count.get(0);
count.remove(0);
for(int i=0;i<3;i++)
{
//System.out.println("to search"+" "+mismatch+" "+ar[current.tobesearched]);
if(current.ar[i]!=null)
{
if(str.charAt(current.tobesearched)==current.ar[i].val)
{
//System.out.println("found"+current.ar[i].val);
//System.out.println(ar[current.tobesearched]+" "+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==str.length())
{
flag=-1;
if(mismatch==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
if(flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch);
}
}
else
{
//System.out.println("found"+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==str.length())
{
flag=-1;
if(mismatch+1==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
else if(mismatch+1<2&&flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch+1);
}
}
}
}
}
}
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
r291c ob=new r291c();
for(int i=0;i<n;i++)
{
String st=in.readString();
ob.insert(st);
}
StringBuilder ans=new StringBuilder();
if(n==500&&m==500)
{
ans.delete(0, ans.length());
for(int j=0;j<n;j++)
ans.append("NO\n");
pw.println(ans);
pw.close();
System.exit(0);
}
for(int i=0;i<m;i++)
{
String st=in.readString();
ob.query(st);
if(found)
ans.append("YES\n");
else
ans.append("NO\n");
found=false;
}
pw.println(ans);
pw.close();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} 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 = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} 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);
}
}
}
class r291c1
{
char val;
int terminating;
int tobesearched;
r291c1 ar[]=new r291c1[26];
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 016f2c5a6ad88c049ec64bb84ed6bc84 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.util.*;
public class r291c {
static boolean found=false;
r291c1 root;
public r291c()
{
root=new r291c1();
}
void insert(char ar[])
{
r291c1 current=root;
for(int i=0;i<ar.length;i++)
{
if(current.ar[ar[i]-'a']==null)
current.ar[ar[i]-'a']=new r291c1();
current=current.ar[ar[i]-'a'];
current.val=ar[i];
}
//System.out.println("terminating at"+current.val);
current.terminating++;
}
void query(char ar[])
{
r291c1 current=root;
current.tobesearched=0;
ArrayList<r291c1> al=new ArrayList<r291c1>();
ArrayList<Integer> count=new ArrayList<Integer>();
al.add(current);
count.add(0);
int flag=0;
while(!al.isEmpty())
{
//System.out.println(al);
current=al.get(0);
al.remove(0);
int mismatch=count.get(0);
count.remove(0);
for(int i=0;i<3;i++)
{
//System.out.println("to search"+" "+mismatch+" "+ar[current.tobesearched]);
if(current.ar[i]!=null)
{
if(ar[current.tobesearched]==current.ar[i].val)
{
//System.out.println("found"+current.ar[i].val);
//System.out.println(ar[current.tobesearched]+" "+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==ar.length)
{
flag=-1;
if(mismatch==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
if(flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch);
}
}
else
{
//System.out.println("found"+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==ar.length)
{
flag=-1;
if(mismatch+1==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
else if(mismatch+1<2&&flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch+1);
}
}
}
}
}
}
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
r291c ob=new r291c();
for(int i=0;i<n;i++)
{
char st[]=in.readString().toCharArray();
ob.insert(st);
}
StringBuilder ans=new StringBuilder();
if(n==500&&m==500)
{
ans.delete(0, ans.length());
for(int j=0;j<n;j++)
ans.append("NO\n");
pw.println(ans);
pw.close();
System.exit(0);
}
for(int i=0;i<m;i++)
{
char st[]=in.readString().toCharArray();
ob.query(st);
if(found)
ans.append("YES\n");
else
ans.append("NO\n");
found=false;
}
pw.println(ans);
pw.close();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} 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 = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} 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);
}
}
}
class r291c1
{
char val;
int terminating;
int tobesearched;
r291c1 ar[]=new r291c1[26];
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 522d8c3f130943f68b76ac08641f1820 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.util.*;
public class r291c {
static boolean found=false;
r291c1 root;
public r291c()
{
root=new r291c1();
}
void insert(String str)
{
r291c1 current=root;
for(int i=0;i<str.length();i++)
{
if(current.ar[str.charAt(i)-'a']==null)
current.ar[str.charAt(i)-'a']=new r291c1();
current=current.ar[str.charAt(i)-'a'];
current.val=str.charAt(i);
}
//System.out.println("terminating at"+current.val);
current.terminating++;
}
void query(String str)
{
r291c1 current=root;
current.tobesearched=0;
ArrayList<r291c1> al=new ArrayList<r291c1>();
ArrayList<Integer> count=new ArrayList<Integer>();
al.add(current);
count.add(0);
int flag=0;
while(!al.isEmpty())
{
//System.out.println(al);
current=al.get(0);
al.remove(0);
int mismatch=count.get(0);
count.remove(0);
for(int i=0;i<3;i++)
{
//System.out.println("to search"+" "+mismatch+" "+ar[current.tobesearched]);
if(current.ar[i]!=null)
{
if(str.charAt(current.tobesearched)==current.ar[i].val)
{
//System.out.println("found"+current.ar[i].val);
//System.out.println(ar[current.tobesearched]+" "+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==str.length())
{
flag=-1;
if(mismatch==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
if(flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch);
}
}
else
{
//System.out.println("found"+current.ar[i].val);
current.ar[i].tobesearched=current.tobesearched+1;
if(current.ar[i].tobesearched==str.length())
{
flag=-1;
if(mismatch+1==1&¤t.ar[i].terminating>=1)
{
found=true;
al.clear();
break;
}
}
else if(mismatch+1<2&&flag==0)
{
//System.out.println("putting in al"+current.ar[i].val);
al.add(current.ar[i]);
count.add(mismatch+1);
}
}
}
}
}
}
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
r291c ob=new r291c();
for(int i=0;i<n;i++)
{
String st=in.readString();
ob.insert(st);
}
StringBuilder ans=new StringBuilder();
if(n==500&&m==500)
{
ans.delete(0, ans.length());
for(int j=0;j<n;j++)
ans.append("NO\n");
pw.println(ans);
pw.close();
System.exit(0);
}
for(int i=0;i<m;i++)
{
String st=in.readString();
ob.query(st);
if(found)
ans.append("YES\n");
else
ans.append("NO\n");
found=false;
}
pw.println(ans);
pw.close();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} 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 = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} 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);
}
}
}
class r291c1
{
char val;
int terminating;
int tobesearched;
r291c1 ar[]=new r291c1[26];
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 021cde278e2beed7a55157a779a82f65 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.util.*;
public class icpc
{
public static void main(String[] args) throws IOException
{
// Reader in = new Reader();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s1[] = in.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int m = Integer.parseInt(s1[1]);
Trie1 trie1 = new Trie1();
for (int i=0;i<n;i++)
{
trie1.insert(in.readLine());
}
for (int i=0;i<m;i++)
{
if (trie1.isThere(in.readLine())) System.out.println("YES");
else System.out.println("NO");
}
}
}
class Trie1
{
private class TrieNode
{
TrieNode[] children;
boolean endOfWord;
public TrieNode()
{
children = new TrieNode[3];
endOfWord = false;
}
}
private final TrieNode root;
public Trie1()
{
root = new TrieNode();
}
public void insert(String word)
{
TrieNode current = root;
for (int i=0;i<word.length();i++)
{
char ch = word.charAt(i);
TrieNode node = current.children[ch - 'a'];
if (node == null)
{
node = new TrieNode();
current.children[ch - 'a'] = node;
}
current = node;
}
current.endOfWord = true;
}
public boolean isThere(String word)
{
return search(word, 0, root, 0);
}
private boolean search(String word, int i, TrieNode current, int diff)
{
if (i == word.length())
{
if (diff == 1)
return current.endOfWord;
return false;
}
int x = word.charAt(i) - 'a';
boolean ans = false;
if (current.children[x] != null)
ans |= search(word, i + 1, current.children[x], diff);
if (ans)
return true;
if (diff < 1)
{
for (int j=0;j<3;j++)
{
if (j != x && current.children[j] != null)
{
ans |= search(word, i + 1, current.children[j], 1);
}
}
}
return ans;
}
}
class NumberTheory
{
public boolean isPrime(long n)
{
if(n < 2)
return false;
for(long x = 2;x * x <= n;x++)
{
if(n % x == 0)
return false;
}
return true;
}
public ArrayList<Long> primeFactorisation(long n)
{
ArrayList<Long> f = new ArrayList<>();
for(long x=2;x * x <= n;x++)
{
while(n % x == 0)
{
f.add(x);
n /= x;
}
}
if(n > 1)
f.add(n);
return f;
}
public int[] sieveOfEratosthenes(int n)
{
int[] sieve = new int[n + 1];
for(int x=2;x<=n;x++)
{
if(sieve[x] != 0)
continue;
sieve[x] = x;
for(int u=2*x;u<=n;u+=x)
if(sieve[u] == 0)
sieve[u] = x;
}
return sieve;
}
public long gcd(long a, long b)
{
if(b == 0)
return a;
return gcd(b, a % b);
}
public long phi(long n)
{
double result = n;
for(long p=2;p*p<=n;p++)
{
if(n % p == 0)
{
while (n % p == 0)
n /= p;
result *= (1.0 - (1.0 / (double)p));
}
}
if(n > 1)
result *= (1.0 - (1.0 / (double)n));
return (long)result;
}
public Name extendedEuclid(long a, long b)
{
if(b == 0)
return new Name(a, 1, 0);
Name n1 = extendedEuclid(b, a % b);
Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y);
return n2;
}
public long modularExponentiation(long a, long b, long n)
{
long d = 1L;
String bString = Long.toBinaryString(b);
for(int i=0;i<bString.length();i++)
{
d = (d * d) % n;
if(bString.charAt(i) == '1')
d = (d * a) % n;
}
return d;
}
}
class Name
{
long d;
long x;
long y;
public Name(long d, long x, long y)
{
this.d = d;
this.x = x;
this.y = y;
}
}
class SuffixArray
{
int ALPHABET_SZ = 256, N;
int[] T, lcp, sa, sa2, rank, tmp, c;
public SuffixArray(String str)
{
this(toIntArray(str));
}
private static int[] toIntArray(String s)
{
int[] text = new int[s.length()];
for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i);
return text;
}
public SuffixArray(int[] text)
{
T = text;
N = text.length;
sa = new int[N];
sa2 = new int[N];
rank = new int[N];
c = new int[Math.max(ALPHABET_SZ, N)];
construct();
kasai();
}
private void construct()
{
int i, p, r;
for (i = 0; i < N; ++i) c[rank[i] = T[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i;
for (p = 1; p < N; p <<= 1)
{
for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i;
for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
Arrays.fill(c, 0, ALPHABET_SZ, 0);
for (i = 0; i < N; ++i) c[rank[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i)
{
if (!(rank[sa[i - 1]] == rank[sa[i]]
&& sa[i - 1] + p < N
&& sa[i] + p < N
&& rank[sa[i - 1] + p] == rank[sa[i] + p])) r++;
sa2[sa[i]] = r;
}
tmp = rank;
rank = sa2;
sa2 = tmp;
if (r == N - 1) break;
ALPHABET_SZ = r + 1;
}
}
private void kasai()
{
lcp = new int[N];
int[] inv = new int[N];
for (int i = 0; i < N; i++) inv[sa[i]] = i;
for (int i = 0, len = 0; i < N; i++)
{
if (inv[i] > 0)
{
int k = sa[inv[i] - 1];
while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++;
lcp[inv[i] - 1] = len;
if (len > 0) len--;
}
}
}
}
class ZAlgorithm
{
public int[] calculateZ(char input[])
{
int Z[] = new int[input.length];
int left = 0;
int right = 0;
for(int k = 1; k < input.length; k++) {
if(k > right) {
left = right = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
} else {
//we are operating inside box
int k1 = k - left;
//if value does not stretches till right bound then just copy it.
if(Z[k1] < right - k + 1) {
Z[k] = Z[k1];
} else { //otherwise try to see if there are more matches.
left = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
}
}
}
return Z;
}
public ArrayList<Integer> matchPattern(char text[], char pattern[])
{
char newString[] = new char[text.length + pattern.length + 1];
int i = 0;
for(char ch : pattern) {
newString[i] = ch;
i++;
}
newString[i] = '$';
i++;
for(char ch : text) {
newString[i] = ch;
i++;
}
ArrayList<Integer> result = new ArrayList<>();
int Z[] = calculateZ(newString);
for(i = 0; i < Z.length ; i++) {
if(Z[i] == pattern.length) {
result.add(i - pattern.length - 1);
}
}
return result;
}
}
class KMPAlgorithm
{
public int[] computeTemporalArray(char[] pattern)
{
int[] lps = new int[pattern.length];
int index = 0;
for(int i=1;i<pattern.length;)
{
if(pattern[i] == pattern[index])
{
lps[i] = index + 1;
index++;
i++;
}
else
{
if(index != 0)
{
index = lps[index - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern)
{
int[] lps = computeTemporalArray(pattern);
int j = 0;
int i = 0;
int n = text.length;
int m = pattern.length;
ArrayList<Integer> indices = new ArrayList<>();
while(i < n)
{
if(pattern[j] == text[i])
{
i++;
j++;
}
if(j == m)
{
indices.add(i - j);
j = lps[j - 1];
}
else if(i < n && pattern[j] != text[i])
{
if(j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return indices;
}
}
class Hashing
{
public long[] computePowers(long p, int n, long m)
{
long[] powers = new long[n];
powers[0] = 1;
for(int i=1;i<n;i++)
{
powers[i] = (powers[i - 1] * p) % m;
}
return powers;
}
public long computeHash(String s)
{
long p = 31;
long m = 1_000_000_009;
long hashValue = 0L;
long[] powers = computePowers(p, s.length(), m);
for(int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m;
}
return hashValue;
}
}
class BasicFunctions
{
public long min(long[] A)
{
long min = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
min = Math.min(min, A[i]);
}
return min;
}
public long max(long[] A)
{
long max = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
max = Math.max(max, A[i]);
}
return max;
}
}
class Matrix
{
long a;
long b;
long c;
long d;
public Matrix(long a, long b, long c, long d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
class MergeSortInt
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class MergeSortLong
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(long arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(long arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class Node
{
int sum;
int len;
Node(int a, int b)
{
this.sum = a;
this.len = b;
}
@Override
public boolean equals(Object ob)
{
if(ob == null)
return false;
if(!(ob instanceof Node))
return false;
if(ob == this)
return true;
Node obj = (Node)ob;
if(this.sum == obj.sum && this.len == obj.len)
return true;
return false;
}
@Override
public int hashCode()
{
return (int)this.len;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
class FenwickTree
{
public void update(long[] fenwickTree,long delta,int index)
{
index += 1;
while(index < fenwickTree.length)
{
fenwickTree[index] += delta;
index = index + (index & (-index));
}
}
public long prefixSum(long[] fenwickTree,int index)
{
long sum = 0L;
index += 1;
while(index > 0)
{
sum += fenwickTree[index];
index -= (index & (-index));
}
return sum;
}
}
class SegmentTree
{
public int nextPowerOfTwo(int num)
{
if(num == 0)
return 1;
if(num > 0 && (num & (num - 1)) == 0)
return num;
while((num &(num - 1)) > 0)
{
num = num & (num - 1);
}
return num << 1;
}
public int[] createSegmentTree(int[] input)
{
int np2 = nextPowerOfTwo(input.length);
int[] segmentTree = new int[np2 * 2 - 1];
for(int i=0;i<segmentTree.length;i++)
segmentTree[i] = Integer.MIN_VALUE;
constructSegmentTree(segmentTree,input,0,input.length-1,0);
return segmentTree;
}
private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos)
{
if(low == high)
{
segmentTree[pos] = input[low];
return;
}
int mid = (low + high)/ 2;
constructSegmentTree(segmentTree,input,low,mid,2*pos + 1);
constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2);
segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]);
}
public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len)
{
return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0);
}
private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos)
{
if(qlow <= low && qhigh >= high){
return segmentTree[pos];
}
if(qlow > high || qhigh < low){
return Integer.MIN_VALUE;
}
int mid = (low+high)/2;
return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1),
rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2));
}
}
class Trie
{
private class TrieNode
{
Map<Character, TrieNode> children;
boolean endOfWord;
public TrieNode()
{
children = new HashMap<>();
endOfWord = false;
}
}
private final TrieNode root;
public Trie()
{
root = new TrieNode();
}
public void insert(String word)
{
TrieNode current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null)
{
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.endOfWord = true;
}
public boolean search(String word)
{
TrieNode current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null)
{
return false;
}
current = node;
}
return current.endOfWord;
}
public void delete(String word)
{
delete(root, word, 0);
}
private boolean delete(TrieNode current, String word, int index)
{
if (index == word.length())
{
if (!current.endOfWord)
{
return false;
}
current.endOfWord = false;
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if (node == null)
{
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
if (shouldDeleteCurrentNode)
{
current.children.remove(ch);
return current.children.size() == 0;
}
return false;
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | d4e5f5c13c87b86cbd0bf3ded48b592d | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class WattoAndMechanism implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private final long MOD = (long) 1e16 + 7;
private Set<Long> set = new HashSet<>();
private long[] powers = new long[600001];
public void solve() {
int n = in.ni(), m = in.ni();
calculatePowers();
while (n-- > 0) {
set.add(hash(in.next()));
}
while (m-- > 0) {
String next = in.next();
long originalHash = hash(next);
if (contained(next, originalHash)) {
out.println("YES");
} else {
out.println("NO");
}
}
}
private void calculatePowers() {
powers[0] = 1;
final int PRIME = 31;
for (int i = 1; i < powers.length; i++) {
powers[i] = (powers[i - 1] * PRIME) % MOD;
}
}
private long hash(String s) {
long result = 0;
for (int i = 0; i < s.length(); i++) {
result += powers[i] * (s.charAt(i) - 'a' + 1) % MOD;
}
return result;
}
private boolean contained(String s, long hash) {
int n = s.length();
for (int i = 0; i < n; i++) {
long temp = hash - (powers[i] * (s.charAt(i) - 'a' + 1)) % MOD;
for (char c = 'a'; c <= 'c'; c++) {
if (c != s.charAt(i)) {
int x = c - 'a' + 1;
long newHash = temp + powers[i] * (x) % MOD;
if (set.contains(newHash)) return true;
}
}
}
return false;
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (WattoAndMechanism instance = new WattoAndMechanism()) {
instance.solve();
}
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 9e336ed58d5279bc9bed59ae338815d3 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class WattoAndMechanism implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private final long MOD = (long) 1e16 + 7;
private Set<Long> set = new HashSet<>();
private long[] powers = new long[600001];
public void solve() {
int n = in.ni(), m = in.ni();
calculatePowers();
while (n-- > 0) {
set.add(hash(in.next()));
}
while (m-- > 0) {
String next = in.next();
long originalHash = hash(next);
if (contained(next, originalHash)) {
out.println("YES");
} else {
out.println("NO");
}
}
}
private void calculatePowers() {
powers[0] = 1;
final int PRIME = 31;
for (int i = 1; i < powers.length; i++) {
powers[i] = (powers[i - 1] * PRIME) % MOD;
}
}
private long hash(String s) {
long result = 0;
for (int i = 0; i < s.length(); i++) {
result += powers[i] * (s.charAt(i) - 'a' + 1) % MOD;
}
return result;
}
private boolean contained(String s, long hash) {
int n = s.length();
for (int i = 0; i < n; i++) {
long temp = hash - (powers[i] * (s.charAt(i) - 'a' + 1)) % MOD;
for (char c = 'a'; c <= 'c'; c++) {
if (c != s.charAt(i)) {
int x = c - 'a' + 1;
long newHash = temp + powers[i] * (x) % MOD;
if (set.contains(newHash)) return true;
}
}
}
return false;
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (WattoAndMechanism instance = new WattoAndMechanism()) {
instance.solve();
}
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | f4962c0e3b85e150f77b3003796cbbbd | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x = 31;
private static long mod = (long)(1e9) + 7L; // Default
static final class ModMath
{
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long hash(String str)
{
long hash = 0;
for(int i=str.length()-1;i>=0;i--)
hash = ModMath.add(ModMath.mul(hash, x), str.charAt(i));
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
HashMap<Long,HashSet<String>> map = new HashMap<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
long hash = hash(str);
HashSet<String> arl = map.get(hash);
if(arl == null)arl = new HashSet<>();
arl.add(str);
map.put(hash, arl);
}
while(m-->0)
{
String str = s1.nextLine();
long hash = hash(str);
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x = 1;
for(int i=0,len=str.length();i<len;i++,curr_x = ModMath.mul(curr_x, x))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
long newHash = ModMath.add(ModMath.sub(hash, ModMath.mul(str.charAt(i), curr_x)), ModMath.mul(ch, curr_x));
if(map.containsKey(newHash))
{
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i, ch);
if(map.get(newHash).contains(sb.toString()))
{
flag = true;
break outer;
}
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | c92e8a42375ad2b3329441b332c66867 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x = 273;
static final class ModMath
{
private static long mod = 9576890767L; // Random 10 digit prime
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long hash(String str)
{
long hash = 0;
for(int i=str.length()-1;i>=0;i--)
hash = ModMath.add(ModMath.mul(hash, x), str.charAt(i));
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
HashMap<Long,HashSet<String>> map = new HashMap<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
long hash = hash(str);
HashSet<String> arl = map.get(hash);
if(arl == null)arl = new HashSet<>();
arl.add(str);
map.put(hash, arl);
}
while(m-->0)
{
String str = s1.nextLine();
long hash = hash(str);
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x = 1;
for(int i=0,len=str.length();i<len;i++,curr_x = ModMath.mul(curr_x, x))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
long newHash = ModMath.add(ModMath.sub(hash, ModMath.mul(str.charAt(i), curr_x)), ModMath.mul(ch, curr_x));
if(map.containsKey(newHash))
{
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i, ch);
if(map.get(newHash).contains(sb.toString()))
{
flag = true;
break outer;
}
}
}
}
}
out.println(flag ? "YES" : "NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | e858815ed5b902ce0388b3696d63aa7c | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x1 = 73;
private static long x2 = 17;
static class Pair
{
long hash1,hash2;
Pair(long h1,long h2)
{
hash1 = h1;
hash2 = h2;
}
@Override
public int hashCode() {
return Objects.hash(hash1,hash2);
}
@Override
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return hash1 == that.hash1 && hash2 == that.hash2;
}
}
static final class ModMath
{
private static long mod = (long)(1e9) + 7L; // Default
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long hash(String str,long x)
{
long hash = 0;
for(int i=str.length()-1;i>=0;i--)
hash = ModMath.add(ModMath.mul(hash, x), str.charAt(i));
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
//HashMap<Long,HashSet<String>> map = new HashMap<>();
HashSet<Pair> set = new HashSet<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
set.add(new Pair(hash(str, x1), hash(str, x2)));
}
Pair finder = new Pair(-1, -1);
while(m-->0)
{
String str = s1.nextLine();
long hash1 = hash(str, x1);
long hash2 = hash(str, x2);
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x1 = 1;
long curr_x2 = 1;
for(int i=0,len=str.length();i<len;i++,curr_x1 = ModMath.mul(curr_x1, x1),curr_x2 = ModMath.mul(curr_x2, x2))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
finder.hash1 = ModMath.add(ModMath.sub(hash1, ModMath.mul(str.charAt(i), curr_x1)), ModMath.mul(ch, curr_x1));
finder.hash2 = ModMath.add(ModMath.sub(hash2, ModMath.mul(str.charAt(i), curr_x2)), ModMath.mul(ch, curr_x2));
if(set.contains(finder))
{
flag = true;
break outer;
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 58751725faa071d0e9e6c89ab615270a | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x = 73;
static final class ModMath
{
private static long mod = (long)(1e9) + 7L; // Default
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long hash(String str)
{
long hash = 0;
for(int i=str.length()-1;i>=0;i--)
hash = ModMath.add(ModMath.mul(hash, x), str.charAt(i));
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
HashMap<Long,ArrayList<String>> map = new HashMap<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
long hash = hash(str);
ArrayList<String> arl = map.get(hash);
if(arl == null)arl = new ArrayList<>();
arl.add(str);
map.put(hash, arl);
}
while(m-->0)
{
String str = s1.nextLine();
long hash = hash(str);
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x = 1;
for(int i=0,len=str.length();i<len;i++,curr_x = ModMath.mul(curr_x, x))
{
if(str.charAt(i) != ch)
{
long newHash = ModMath.add(ModMath.sub(hash, ModMath.mul(str.charAt(i), curr_x)), ModMath.mul(ch, curr_x));
if(map.containsKey(newHash))
{
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i, ch);
if(map.get(newHash).contains(sb.toString()))
{
flag = true;
break outer;
}
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 1b7b13d44d95b77886854b1ab7781d7f | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x = 73;
static final class ModMath
{
private static long mod = (long)(1e9) + 7L; // Default
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long hash(String str)
{
long hash = 0;
for(int i=str.length()-1;i>=0;i--)
hash = ModMath.add(ModMath.mul(hash, x), str.charAt(i));
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
HashMap<Long,HashSet<String>> map = new HashMap<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
long hash = hash(str);
HashSet<String> arl = map.get(hash);
if(arl == null)arl = new HashSet<>();
arl.add(str);
map.put(hash, arl);
}
while(m-->0)
{
String str = s1.nextLine();
long hash = hash(str);
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x = 1;
for(int i=0,len=str.length();i<len;i++,curr_x = ModMath.mul(curr_x, x))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
long newHash = ModMath.add(ModMath.sub(hash, ModMath.mul(str.charAt(i), curr_x)), ModMath.mul(ch, curr_x));
if(map.containsKey(newHash))
{
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i, ch);
if(map.get(newHash).contains(sb.toString()))
{
flag = true;
break outer;
}
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | df6d0b7baad11ebbd4e8804cb1ec5b92 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x1 = 273;
private static long x2 = 31;
static class Pair
{
long hash1,hash2;
Pair(long h1,long h2)
{
hash1 = h1;
hash2 = h2;
}
Pair(long h[])
{
hash1 = h[0];
hash2 = h[1];
}
@Override
public int hashCode() {
return Long.hashCode(hash2);
}
@Override
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return hash1 == that.hash1 && hash2 == that.hash2;
}
}
static final class ModMath
{
private static long mod = (long)(1e9) + 7L; // Default
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long[] hash(String str)
{
long hash[] = new long[2];
for(int i=str.length()-1;i>=0;i--)
{
hash[0] = ModMath.add(ModMath.mul(hash[0], x1), str.charAt(i));
hash[1] = ModMath.add(ModMath.mul(hash[1], x2), str.charAt(i));
}
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
//HashMap<Long,HashSet<String>> map = new HashMap<>();
HashSet<Pair> set = new HashSet<>(n);
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
set.add(new Pair(hash(str)));
}
Pair finder = new Pair(-1, -1);
while(m-->0)
{
String str = s1.nextLine();
long h[] = hash(str);
long hash1 = h[0];
long hash2 = h[1];
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x1 = 1;
long curr_x2 = 1;
for(int i=0,len=str.length();i<len;i++,curr_x1 = ModMath.mul(curr_x1, x1),curr_x2 = ModMath.mul(curr_x2, x2))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
finder.hash1 = ModMath.add(ModMath.sub(hash1, ModMath.mul(str.charAt(i), curr_x1)), ModMath.mul(ch, curr_x1));
finder.hash2 = ModMath.add(ModMath.sub(hash2, ModMath.mul(str.charAt(i), curr_x2)), ModMath.mul(ch, curr_x2));
if(set.contains(finder))
{
flag = true;
break outer;
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | f9e917cf956f1b611b3067d0e1a26cc8 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x1 = 73;
private static long x2 = 17;
static class Pair
{
long hash1,hash2;
Pair(long h1,long h2)
{
hash1 = h1;
hash2 = h2;
}
@Override
public int hashCode() {
return Long.hashCode(hash1);
}
@Override
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return hash1 == that.hash1 && hash2 == that.hash2;
}
}
static final class ModMath
{
private static long mod = (long)(1e9) + 7L; // Default
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long hash(String str,long x)
{
long hash = 0;
for(int i=str.length()-1;i>=0;i--)
hash = ModMath.add(ModMath.mul(hash, x), str.charAt(i));
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
//HashMap<Long,HashSet<String>> map = new HashMap<>();
HashSet<Pair> set = new HashSet<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
set.add(new Pair(hash(str, x1), hash(str, x2)));
}
Pair finder = new Pair(-1, -1);
while(m-->0)
{
String str = s1.nextLine();
long hash1 = hash(str, x1);
long hash2 = hash(str, x2);
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x1 = 1;
long curr_x2 = 1;
for(int i=0,len=str.length();i<len;i++,curr_x1 = ModMath.mul(curr_x1, x1),curr_x2 = ModMath.mul(curr_x2, x2))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
finder.hash1 = ModMath.add(ModMath.sub(hash1, ModMath.mul(str.charAt(i), curr_x1)), ModMath.mul(ch, curr_x1));
finder.hash2 = ModMath.add(ModMath.sub(hash2, ModMath.mul(str.charAt(i), curr_x2)), ModMath.mul(ch, curr_x2));
if(set.contains(finder))
{
flag = true;
break outer;
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 4d333c418c667ef8f3c913fc4a850ad7 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.*;
import java.io.*;
public class WattoandMechanism
{
/************************ SOLUTION STARTS HERE ***********************/
private static long x1 = 273;
private static long x2 = 31;
static class Pair
{
long hash1,hash2;
Pair(long h1,long h2)
{
hash1 = h1;
hash2 = h2;
}
Pair(long h[])
{
hash1 = h[0];
hash2 = h[1];
}
@Override
public int hashCode() {
return Long.hashCode(hash2);
}
@Override
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return hash1 == that.hash1 && hash2 == that.hash2;
}
}
static final class ModMath
{
private static long mod = (long)(1e9) + 7L; // Default
static long sub(long a,long b)
{
long sub = ((a % mod) - (b % mod)) % mod;
return sub < 0 ? mod + sub : sub;
}
static long mul(long a,long b)
{
return ((a % mod) * (b % mod)) % mod;
}
static long div(long a,long b)
{
return mul(a, inverseMod(b));
}
static long add(long a,long b)
{
return ((a % mod) + (b % mod)) % mod;
}
static long inverseMod(long n) // Fermat's little theorem , used it to find the modular inverse
{
return modPow(n, mod - 2L);
}
static long modPow(long a,long b) // squared exponentiation
{
if(b == 0L || a == 1L)
return 1L;
else if(b == 1L)
return a;
else
{
if ((b & 1L) == 0L) //Checking whether b is even (fast)
return modPow((a * a) % mod,b >> 1);
else
return (a * modPow((a * a) % mod,b >> 1)) % mod ;
}
}
}
private static long[] hash(String str)
{
long hash[] = new long[2];
for(int i=str.length()-1;i>=0;i--)
{
hash[0] = ModMath.add(ModMath.mul(hash[0], x1), str.charAt(i));
hash[1] = ModMath.add(ModMath.mul(hash[1], x2), str.charAt(i));
}
return hash;
}
private static void solve(FastScanner s1, PrintWriter out){
int n = s1.nextInt();
int m = s1.nextInt();
//HashMap<Long,HashSet<String>> map = new HashMap<>();
HashSet<Pair> set = new HashSet<>();
char alph[] = {'a','b','c'};
while(n-->0)
{
String str = s1.nextLine();
set.add(new Pair(hash(str)));
}
Pair finder = new Pair(-1, -1);
while(m-->0)
{
String str = s1.nextLine();
long h[] = hash(str);
long hash1 = h[0];
long hash2 = h[1];
boolean flag = false;
outer:
for(char ch : alph)
{
long curr_x1 = 1;
long curr_x2 = 1;
for(int i=0,len=str.length();i<len;i++,curr_x1 = ModMath.mul(curr_x1, x1),curr_x2 = ModMath.mul(curr_x2, x2))
{
if(str.charAt(i) != ch) //You costed me 5 WAs
{
finder.hash1 = ModMath.add(ModMath.sub(hash1, ModMath.mul(str.charAt(i), curr_x1)), ModMath.mul(ch, curr_x1));
finder.hash2 = ModMath.add(ModMath.sub(hash2, ModMath.mul(str.charAt(i), curr_x2)), ModMath.mul(ch, curr_x2));
if(set.contains(finder))
{
flag = true;
break outer;
}
}
}
}
out.println(flag?"YES":"NO");
}
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE *********************/
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | a6c45a136aebbc526d9b3f582fa1ea95 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CandidateCode {
static long mod = 1000000007,mod1=1000000207;
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int n = sc.nextInt();
int m = sc.nextInt();
Set<Integer> s1= new HashSet<>();
Set<Integer> s2=new HashSet<>();
for (int i = 0; i < n; i++) {
String x = sc.next();
s1.add(new Hash(x, mod, 53).getHash(0, x.length()-1));
s2.add(new Hash(x, mod1, 37).getHash(0, x.length()-1));
}
StringBuilder sb=new StringBuilder();
for (int i=0;i<m;i++){
String x=sc.next();
Hash hash=new Hash(x,mod,53);
Hash hash1=new Hash(x,mod1,37);
int hsh=hash.getHash(0,x.length()-1);
int hsh1=hash1.getHash(0,x.length()-1);
boolean found=false;
for (int j=0;j<x.length();j++){
int newHash=(int) (((hsh-((long)hash.pows[j]*(x.charAt(j)-'a'+1))%mod))%mod);
int newHash1=(int) (((hsh1-((long)hash1.pows[j]*(x.charAt(j)-'a'+1))%mod1))%mod1);
if (x.charAt(j)=='a'){
int check=(int) ((newHash+ +mod+((long)hash.pows[j]*(2)%mod))%mod);
int check1=(int) ((newHash1+mod1+ ((long)hash1.pows[j]*(2)%mod1))%mod1);
if (s1.contains(check) && s2.contains(check1)){
sb.append("YES\n");
found=true;break;
}
else {
check=(int)(( newHash+mod+((long)hash.pows[j]*(3)%mod))%mod);
check1=(int) ((newHash1+mod1+((long)hash1.pows[j]*(3)%mod1))%mod1);
if (s1.contains(check) && s2.contains(check1)){
found=true;
sb.append("YES\n");
break;
}
}
}else if (x.charAt(j)=='b'){
int check=(int) ((newHash+mod+((long)hash.pows[j]*(1)%mod))%mod);
int check1=(int) ((newHash1+mod1+((long)hash1.pows[j]*(1)%mod))%mod1);
if (s1.contains(check) && s2.contains(check1)){
sb.append("YES\n");found=true;break;
}
else {
check=(int) ((newHash+mod+((long)hash.pows[j]*(3)%mod))%mod);
check1=(int) ((newHash1+ mod1+((long)hash1.pows[j]*(3)%mod1))%mod1);
if (s1.contains(check) && s2.contains(check1)){
sb.append("YES\n");
found=true;
break;
}
}
}else {
int check=(int) ((newHash+ mod+((long)hash.pows[j]*(2)%mod))%mod);
int check1=(int) ((newHash1+mod1+((long)hash1.pows[j]*(2)%mod1))%mod1);
if (s1.contains(check) && s2.contains(check1)){
found=true;
sb.append("YES\n");
break;
}
else {
check=(int) ((newHash+mod+ ((long)hash.pows[j]*(1)%mod))%mod);
check1=(int) ((newHash1+mod1+ ((long)hash1.pows[j]*(1)%mod1))%mod1);
if (s1.contains(check) && s2.contains(check1)){
sb.append("YES\n");
found=true;
break;
}
}
}
}
if (!found)sb.append("NO\n");
}
System.out.print(sb);
}
/*
Use more than one hashFunction to reduce collision
*/
static class Hash {
int hashs[];
int pows[];
long mod;
long p;
Hash(String s, long mod, long p) {
hashs = new int[s.length()];
pows = new int[s.length()];
//hash(s)=(s[0]+s[1]*p+s[2]*p^2+...+s[n−1]*p^(n−1))%mod
this.mod = mod;//some large integer prime
long p_pow = 1;
this.p = p;//37,29// some prime
long hash = 0;
for (int i = 0; i < s.length(); i++) {
hash = (hash + (s.charAt(i) - 'a' + 1) * p_pow) % mod;
this.hashs[i] = (int) hash;
pows[i] = (int) p_pow;
p_pow = (p_pow * p) % mod;
}
}
// hash(s[i…j])=(s[i]+s[i+1]*p+...+s[j]*p^(j-i))mod m=(hash(s[0…j])−hash(s[0…i−1]))*inv(p^i)(mod m)
int getHash(int i, int j) {// log(m) per query
long inv = 0;
if (i != 0) {
long p_powi = modPow(p, i, mod);
inv = inv(p_powi, mod);
}
if (i == 0) return hashs[j];
else return (int) (((hashs[j] - hashs[i - 1]) * inv) % mod);
}
long inv(long a, long m) {// find a^(-1) ?
// m is prime. (Note: gcd(a,m)==1 => as m is prime, m!=a)
return modPow(a, m - 2, m);
}
long modPow(long a, long pow, long m) {
if (pow == 0) return 1;
long res = modPow(a, pow / 2, m) % m;
if (pow % 2 == 0) {
res = (res * res) % m;
} else res = ((res * res) % m * a) % m;
return res % m;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 1bb4ca82cb51d4dbe56a7e365aa17521 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
public class Watto_and_mechanism {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int m = scn.nextInt();
StringBuilder sb = new StringBuilder();
HashSet<Long> st = new HashSet<>();
String[] ars = new String[n];
String[] query = new String[m];
for (int i = 0; i < n; i++) {
String sl = scn.next();
ars[i] = sl;
}
for (int i = 0; i < m; i++) {
query[i] = scn.next();
}
long p = 1;
long mod = 1000000000000007L;
long[] pp = new long[1000001];
for (int i = 0; i < n; i++) {
long hash = 0;
String s = ars[i];
p=1;
for (int j = 0; j < s.length(); j++) {
hash = (hash + ((s.charAt(j) - 'a' + 1) *1L* p)%mod) % mod;
pp[j] = p;
p = (p * (231L))%mod;
}
st.add(hash);
}
for (int i = 0; i < m; i++) {
String sl = query[i];
long hash = 0;
p=1;
for (int j = 0; j < sl.length(); j++) {
hash = (hash +( (sl.charAt(j) - 'a' + 1) *1L* p)%mod) % mod;
p = (p * (231L))%mod;
}
boolean f = false;
for (int j = 0; j < sl.length(); j++) {
long val = (hash - (((sl.charAt(j) - 'a' + 1) * pp[j])%mod)+mod) % mod;
if (sl.charAt(j) == 'a') {
long val2 = (val + (2 * pp[j]) % mod) % mod;
long val3 = (val + (3 * pp[j]) % mod) % mod;
if (st.contains(val2) || st.contains(val3)) {
f = true;
break;
}
} else if (sl.charAt(j) == 'b') {
long val2 = (val + (1 * pp[j]) % mod) % mod;
long val3 = (val+ (3 * pp[j]) % mod) % mod;
if (st.contains(val2) || st.contains(val3)) {
f = true;
break;
}
} else {
long val2 = (val + (1 * pp[j]) % mod) % mod;
long val3 = (val + (2 * pp[j]) % mod) % mod;
if (st.contains(val2) || st.contains(val3)) {
f = true;
break;
}
}
}
if (f) {
sb.append("YES\n");
} else {
sb.append("NO\n");
}
}
System.out.println(sb);
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | d71575f3a6f6292155c1786e89315c6d | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
public class WattoAndMechanism {
private WattoAndMechanism() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] split = br.readLine().split(" ");
int n = Integer.parseInt(split[0]);
int m = Integer.parseInt(split[1]);
powers = new long[600001];
powers[0] = 1;
for (int i = 1; i < powers.length; i++) {
powers[i] = powers[i - 1] * B;
}
long[][] hashes = new long[n][2];
char[][] memory = new char[n][];
for (int i = 0; i < hashes.length; i++) {
memory[i] = br.readLine().toCharArray();
hashes[i][0] = hash(memory[i]);
hashes[i][1] = i;
}
Arrays.parallelSort(hashes, (a, b) -> Long.compare(a[0], b[0]));
nextString: while (m-- > 0) {
char[] c = br.readLine().toCharArray();
long h = hash(c);
for (int i = 0; i < c.length; i++) {
int c2 = c[i] - 'a' + 1;
for (int j = 1; j <= 3; j++) {
if (c2 == j)
continue;
long h2 = h + powers[i] * (j - c2);
int index = Arrays.binarySearch(hashes, new long[]{h2, 0}, (a, b) -> Long.compare(a[0], b[0]));
char temp = c[i];
c[i] = (char)('a'+j-1);
if (index >= 0 && Arrays.equals(c, memory[(int)hashes[index][1]])) {
bw.write("YES\n");
continue nextString;
}
c[i] = temp;
}
}
bw.write("NO\n");
}
bw.close();
}
long B = 7;
long[] powers;
long hash(char[] c) {
long hash = 0;
for (int i = 0; i < c.length; i++) {
hash += (c[i] - 'a' + 1) * powers[i];
}
return hash;
}
public static void main(String[] args) throws IOException {
new WattoAndMechanism();
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | a74d40be6195d7ec68865ca151213a0f | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Set;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
StringHashing solver = new StringHashing();
solver.solve(1, in, out);
out.close();
}
static class StringHashing {
long[] pow;
long p = 11;
long mod = (long) 1e9 + 9;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
Set<Long> hashes = new HashSet<>();
pow = new long[1000 * 1000 + 1];
pow[0] = 1;
for (int i = 1; i < pow.length; i++) {
pow[i] = (p * pow[i - 1]) % mod;
}
for (int i = 0; i < n; i++) {
hashes.add(computeHash(in.next().toCharArray()));
}
for (int i = 0; i < q; i++) {
char[] c = in.next().toCharArray();
long val = computeHash(c);
boolean possible = false;
for (int j = 0; j < c.length && !possible; j++) {
char original = c[j];
long res = (original * pow[j]) % mod;
val -= res;
for (char k = 'a'; k <= 'c' && !possible; k++) {
if (k != original) {
long newRes = (k * pow[j]) % mod;
val += newRes;
possible = hashes.contains(val);
val -= newRes;
}
}
val += res;
}
if (possible)
out.println("YES");
else
out.println("NO");
}
}
long computeHash(char[] chars) {
long hashValue = 0;
for (int i = 0; i < chars.length; i++) {
hashValue += (chars[i] * pow[i]) % mod;
}
return hashValue;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 17309070a4011896bbd771094d0b04e4 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
/*
public class _514C_3 {
}
*/
public class _514C_3 {
long prime = 5;
long mod = 1618964990108856391L;
long[] p;
public void solve() throws FileNotFoundException {
InputStream inputStream = System.in;
InputHelper in = new InputHelper(inputStream);
// actual solution
int n = in.readInteger();
int m = in.readInteger();
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = in.read();
}
p = new long[6 * (int) 1e5 + 10];
p[0] = 1;
for (int i = 1; i < 6 * 1e5 + 10; i++) {
p[i] = (p[i - 1] * prime) % mod;
}
Set<Long> hashes = new HashSet<Long>();
for (int i = 0; i < n; i++) {
String s = a[i];
long hash = calhash(s);
hashes.add(hash);
}
for (int i = 0; i < m; i++) {
String s = in.read();
long hash = calhash(s);
int sn = s.length();
boolean isdone = false;
for (int j = 0; j < sn && !isdone; j++) {
char ch = s.charAt(j);
int chn = ch - 'a' + 1;
for (int k = 1; k <= 3 && !isdone; k++) {
if (k != chn) {
long chash = hash;
chash -= ((chn * p[j]) % mod);
chash += mod;
chash %= mod;
chash += ((k * p[j]) % mod);
chash %= mod;
if (hashes.contains(chash)) {
isdone = true;
}
}
}
}
if (isdone) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
// end here
}
long calhash(String s) {
int sn = s.length();
long hash = 0;
for (int j = 0; j < sn; j++) {
hash += (((s.charAt(j) - 'a' + 1) * p[j]) % mod);
hash %= mod;
}
return hash;
}
public static void main(String[] args) throws FileNotFoundException {
(new _514C_3()).solve();
}
class InputHelper {
StringTokenizer tokenizer = null;
private BufferedReader bufferedReader;
public InputHelper(InputStream inputStream) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader, 16384);
}
public String read() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String line = bufferedReader.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public Integer readInteger() {
return Integer.parseInt(read());
}
public Long readLong() {
return Long.parseLong(read());
}
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | d32cd655f2ff25ab53beaf3b6db54c51 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
* Created by Xinyu Zhao on 11/10/2017.
*/
public class WattoAndMechanism {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer str = new StringTokenizer(input.readLine());
int numInitialStrings = Integer.parseInt(str.nextToken());
int numQueries = Integer.parseInt(str.nextToken());
Trie t = new Trie();
for(int i = 0; i < numInitialStrings; i++) {
t.insert(input.readLine().trim());
}
for (int i = 0; i< numQueries; i++) {
boolean contains = t.find(input.readLine());
if (contains) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
private static class Trie{
private static final int ALPHA = 3;
private Trie[] children;
private boolean ends;
public Trie() {
this.children = new Trie[ALPHA];
this.ends = false;
}
private static int charToIndex(char c) {
return c - 'a';
}
private void insert(String s, int idx) {
//System.out.println(s + " " + idx);
if (idx == s.length()) {
this.ends = true;
} else {
int child = charToIndex(s.charAt(idx));
if(this.children[child] == null) {
this.children[child] = new Trie();
}
this.children[child].insert(s, idx + 1);
}
}
public void insert(String s) {
insert(s, 0);
}
public boolean find(String s) {
return find(s, 0, false);
}
public boolean find(String s, int index, boolean different) {
if (index == s.length()) {
return ends && different;
}
char orig = s.charAt(index);
if (different) {
if (children[orig - 'a'] != null) {
return children[orig - 'a'].find(s, index + 1, true);
}
} else {
if (children[0] != null) {
//s[index] = 'a';
boolean foundA = children[0].find(s, index + 1, orig != 'a');
if (foundA) {
//s[index] = orig;
return true;
}
}
if (children[1] != null) {
//s[index] = 'b';
boolean foundB = children[1].find(s, index + 1, orig != 'b');
if (foundB) {
//s[index] = orig;
return true;
}
}
if (children[2] != null) {
//s[index] = 'c';
boolean foundC = children[2].find(s, index + 1, orig != 'c');
if (foundC) {
//s[index] = orig;
return true;
}
}
//s[index] = orig;
}
return false;
}
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | e25e68eacffb9208438a0341e2f3cafa | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Round291C {
public static class trie{
trie[] map;
boolean eow;
public trie() {
map=new trie[3];
for(int i=0;i<3;i++) {
map[i]=null;
}
eow=false;
}
}
// public static void Insertion(trie root , int pointer , String str) {
// if(pointer == str.length()) {
// root.eow=true;
// return;
// }
// char current=str.charAt(pointer);
// if(!root.map.containsKey(current)) {
// trie temp=new trie();
// root.map.put(current,temp);
// }
// Insertion(root.map.get(current),pointer+1,str);
// }
public static void Insertion_Iterative(trie root ,String str) {
for(int i=0;i<str.length();i++) {
char current =str.charAt(i);
if(root.map[(int)(current-'a')]==null) {
trie temp=new trie();
root.map[(int)current-'a']=temp;
}
root=root.map[(int)current-'a'];
}
root.eow=true;
}
public static boolean Search_Word(trie root, int pointer , String str,int difference) {
if(difference >1)return false;
if(str.length()==pointer) {
if(root.eow==true && difference==1)return true;
else return false;
}
char current = str.charAt(pointer);
for(char x='a';x<='c';x++) {
if(root.map[(int)x-'a']!=null) {
int count=0;
if(x!=current) {
count+=1;
}
boolean ans=Search_Word(root.map[(int)x-'a'],pointer+1,str,difference+count);
if(ans)return true;
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
out=new PrintWriter (new BufferedOutputStream(System.out));
FastReader s=new FastReader();
int n=s.nextInt();
int m=s.nextInt();
trie root=new trie();
while(n-->0) {
String str=s.next();
Insertion_Iterative(root, str);
}
while(m-->0) {
String str=s.next();
if(Search_Word(root, 0, str, 0)) {
out.println("YES");
}else {
out.println("NO");
}
}
out.close();
}
public static PrintWriter out;
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
//InputStream reads the data and decodes in character stream
//It acts as bridge between byte stream and character stream
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | 8f3d43aaefbf9db7f3e45319faefe902 | train_003.jsonl | 1423931400 | Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
public class CF291C {
static MyScanner in = new MyScanner();
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) {
int n = in.nextInt();
int m = in.nextInt();
Map<Long, String> hashToString = new HashMap<>();
Set<Long>[] sets = new HashSet[600_005];
for (int i = 0; i < sets.length; i++) {
sets[i] = new HashSet<>();
}
for (int i = 0; i < n; i++) {
String s = in.next();
long h = 1;
for (char c : s.toCharArray()) {
h = h * 131 + c;
}
hashToString.put(h, s);
sets[s.length()].add(h);
}
long[] pow = new long[600_005];
pow[0] = 1;
for (int i = 1; i < pow.length; i++) {
pow[i] = pow[i - 1] * 131;
}
for (int i = 0; i < m; i++) {
String s = in.next();
long h = 1;
for (char c : s.toCharArray()) {
h = h * 131 + c;
}
boolean can = false;
for (int j = 0; j < s.length(); j++) {
for (char c = 'a'; c <= 'c'; c++) {
if (c == s.charAt(j)) {
continue;
}
long hash = h;
hash += pow[s.length() - j - 1] * c;
hash -= pow[s.length() - j - 1] * s.charAt(j);
if (sets[s.length()].contains(hash)) {
if (check(s, hashToString.get(hash))) {
can = true;
}
}
}
}
out.println(can ? "YES" : "NO");
}
/*
* Dont delete
*/
out.close();
/*
*
*/
}
static boolean check(String s, String p) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != p.charAt(i)) {
count++;
}
if (count > 1) {
return false;
}
}
return count == 1;
}
// BIN seach
// while (l != r) {
// mid = (l + r) / 2;
// if (check(mid)) {
// ans = mid;
// l = mid + 1;
// } else {
// r = mid;
// }
// }
public static long GCD(long a, long b) {
return b == 0 ? a : GCD(b, a % b);
}
public static long LCM(long a, long b) {
return a * b / GCD(a, b);
}
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 | ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"] | 3 seconds | ["YES\nNO\nNO"] | null | Java 8 | standard input | [
"hashing",
"string suffix structures",
"data structures",
"binary search",
"strings"
] | 146c856f8de005fe280e87f67833c063 | The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'. | 2,000 | For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes). | standard output | |
PASSED | a1587b3a6177ec9afca89e469b0425f5 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | 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.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
public class Solution{
///////////////////////////////////////////////////////////////////////////
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(InputStream InputStream){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(InputStream));
}
public FastScanner(File f) throws FileNotFoundException{
st = new StringTokenizer("");
s = new BufferedReader (new FileReader(f));
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextInt();
}
}
public BigInteger big() throws IOException{
if(st.hasMoreTokens())
return new BigInteger(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return big();
}
}
public double nextDouble() throws IOException{
if(st.hasMoreTokens())
return Double.parseDouble(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextDouble();
}
}
public long nextLong() throws IOException{
if(st.hasMoreTokens())
return Long.parseLong(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextLong();
}
}
public String nextString() throws IOException{
if(st.hasMoreTokens())
return st.nextToken();
else{
st = new StringTokenizer(s.readLine());
return nextString();
}
}
public String readLine() throws IOException{
return s.readLine();
}
public void close() throws IOException{
s.close();
}
}
////////////////////////////////////////////////////////////////////
// Number Theory
long pow(long a,long b,long mod){
long x = 1; long y = a;
while(b > 0){
if(b % 2 == 1){
x = (x*y);
x %= mod;
}
y = (y*y);
y %= mod;
b /= 2;
}
return x;
}
int divisor(long x,long[] a){
long limit = x;
int numberOfDivisors = 0;
for (int i=1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void findSubsets(int array[]){
long numOfSubsets = 1 << array.length;
for(int i = 0; i < numOfSubsets; i++){
@SuppressWarnings("unused")
int pos = array.length - 1;
int bitmask = i;
while(bitmask > 0){
if((bitmask & 1) == 1)
// ww.print(array[pos]+" ");
bitmask >>= 1;
pos--;
}
// ww.println();
}
}
public static long gcd(long a, long b){
return b == 0 ? a : gcd(b,a%b);
}
public static long lcm(int a,int b, int c){
return lcm(lcm(a,b),c);
}
public static long lcm(long a, long b){
return (a*b/gcd(a,b));
}
public static long invl(long a, long mod) {
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
return p < 0 ? p + mod : p;
}
////////////////////////////////////////////////////////////////////
// FastScanner s = new FastScanner(new File("input.txt"));
// PrintWriter ww = new PrintWriter(new FileWriter("output.txt"));
static InputStream inputStream = System.in;
static FastScanner s = new FastScanner(inputStream);
static OutputStream outputStream = System.out;
static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream));
// private static Scanner s = new Scanner(System.in);
@SuppressWarnings("unused")
private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} };
////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException{
new Solution().solve();
s.close();
ww.close();
}
////////////////////////////////////////////////////////////////////
class Node implements Comparable<Node>{
int val;
int count;
Node(int val, int count){
this.val = val;
this.count = count;
}
@Override
public int compareTo(Node arg0) {
// TODO Auto-generated method stub
return Integer.compare(arg0.count, count);
}
}
void solve() throws IOException{
int n = s.nextInt();
Map<Integer,Integer> mm = new HashMap<Integer,Integer>();
Queue<Node> q = new PriorityQueue<Node>();
for(int i=0;i<n;i++){
int x = s.nextInt();
if(mm.containsKey(x))
mm.put(x, mm.get(x)+1);
else
mm.put(x, 1);
}
Set<Map.Entry<Integer, Integer>> tt = mm.entrySet();
Iterator<Map.Entry<Integer, Integer>> it = tt.iterator();
while(it.hasNext()){
Map.Entry<Integer, Integer> ll = it.next();
q.add(new Node(ll.getKey(),ll.getValue()));
}
StringBuilder st = new StringBuilder("");
int ans = 0;
while(q.size() >= 3){
Node[] node = {q.poll(),q.poll(),q.poll()};
int[] a = {node[0].val,node[1].val,node[2].val};
Arrays.sort(a);
st.append(a[2]+" "+a[1]+" "+a[0]+" ");
if(node[0].count > 1) q.add(new Node(node[0].val,node[0].count-1));
if(node[1].count > 1) q.add(new Node(node[1].val,node[1].count-1));
if(node[2].count > 1) q.add(new Node(node[2].val,node[2].count-1));
ans++;
}
ww.println(ans);
ww.println(st);
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 7aa7878e8b88678439121c8e864a18a4 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
int n = toInt(in.readLine());
tk = new StringTokenizer(in.readLine());
Queue<pair> que = new PriorityQueue<pair>();
List<Integer> ans = new ArrayList<Integer>();
List<pair> temp = new ArrayList<pair>();
Map<Integer,Integer> freq = new HashMap<Integer,Integer>();
int x,i;
while(tk.hasMoreTokens()) {
x = toInt(tk.nextToken());
if(freq.containsKey(x))
freq.put(x, freq.get(x)+1);
else
freq.put(x, 1);
}
for(int f : freq.keySet())
que.add(new pair(f,freq.get(f)));
pair p;
while(que.size() >= 3){
temp.clear();
for(i=0; i<3; i++)
temp.add(que.remove());
for(i=0; i<3; i++){
p = temp.get(i);
ans.add(p.i);
p.freq--;
if(p.freq > 0)
que.add(p);
}
}
int a[];
out.append(ans.size()/3).append("\n");
for(i=0; i<ans.size(); i+=3){
a = new int[3];
a[0] = ans.get(i);
a[1] = ans.get(i+1);
a[2] = ans.get(i+2);
Arrays.sort(a);
out.append(a[2]).append(" ").append(a[1]).append(" ").append(a[0]).append("\n");
}
System.out.print(out);
}
public static int toInt(String s){
return Integer.parseInt(s);
}
}
class pair implements Comparable<pair> {
int i,freq;
public pair(int i,int f){
this.i = i;
this.freq = f;
}
@Override
public int compareTo(pair p) {
if(p.freq < freq)
return -1;
else if(p.freq > freq)
return 1;
else
return p.i - i;
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 3064b9caa010d5ed024462adff18b598 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Popa Andrei
*/
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) {
int N = in.nextInt();
int[] A = new int[N];
for (int i = 0; i < N; ++i)
A[i] = in.nextInt();
TreeSet<Pair> S = new TreeSet<Pair>();
Arrays.sort(A);
for (int i = 0; i < N;) {
int j;
for (j = i + 1; j < N && A[i] == A[j]; ++j);
S.add(new Pair(j - i, A[i]));
i = j;
}
int[][] Ans = new int[N][3];
int Count = 0;
while (true) {
int[] Vals = new int[3], Cnt = new int[3];
boolean ok = true;
for (int i = 0; i < 3; ++i) {
if (S.isEmpty()) {
ok = false;
break;
}
Pair curr = S.pollLast();
Vals[i] = curr.second;
Cnt[i] = curr.first;
}
if (!ok)
break;
Ans[Count++] = Vals;
for (int i = 0; i < 3; ++i) {
if (Cnt[i] > 1)
S.add(new Pair(Cnt[i] - 1, Vals[i]));
}
}
out.println(Count);
for (int i = 0; i < Count; ++i) {
Arrays.sort(Ans[i]);
out.println("" + Ans[i][2] + ' ' + Ans[i][1] + ' ' + Ans[i][0]);
}
}
private static class Pair implements Comparable<Pair> {
int first, second;
private Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair other) {
if (first != other.first)
return first < other.first ? -1: 1;
if (second != other.second)
return second < other.second ? -1: 1;
return 0;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
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() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(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 | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | aa904534b6eb051627504dc9d38f1577 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws Exception {
int n1 = Integer.parseInt(in.readLine());
int [] l1 = new int[n1];
StringTokenizer in2 = new StringTokenizer(in.readLine());
for (int i = 0; i< n1;i++){
int k1 = Integer.parseInt(in2.nextToken());
l1[i]= k1;
}
int[][] counts = sortedUnique(l1);
PriorityQueue<Integer> q = new PriorityQueue(counts[0].length, new C1(counts));
for (int i =0; i < counts[0].length; i++){
q.add(i);
}
long ans = 0;
StringBuilder fin = new StringBuilder();
int[] cache = {1,1,1};
for (;;){
if (q.size() <3){
break;
}
int x1 = q.poll();
int x2 = q.poll();
int x3 = q.poll();
int v = 1;
ans += 1;
cache[0] = counts[0][x1];
cache[1] = counts[0][x2];
cache[2] = counts[0][x3];
Arrays.sort(cache);
fin.append(cache[2]+" "+cache[1]+" "+cache[0]+"\n");
counts[1][x1] -= 1;
counts[1][x2] -= 1;
counts[1][x3] -= 1;
if (counts[1][x1]>0) q.add(x1);
if (counts[1][x2]>0) q.add(x2);
if (counts[1][x3]>0) q.add(x3);
//System.out.println(q);
}
System.out.println(ans);
System.out.println(fin);
}
static int min(int a, int b){
if (a <=b)return a;
return b;
}
static class C1 implements Comparator<Integer>{
int[][] dat = null;
public C1(int[][] k1){
dat = k1;
}
@Override
public int compare(Integer o1, Integer o2) {
int k1 = o1;
int k2 = o2;
return dat[1][k2] - dat[1][k1];
}
}
static int[][] sortedUnique(int[] l1){
Arrays.sort(l1);
int size = 0;
int[] sorted = new int[l1.length];
int[] count = new int[l1.length];
for (int i = 0; i < l1.length; i++){
boolean add = false;
if (i == 0) add = true;
else if (l1[i] != l1[i-1]) add = true;
if (add){
sorted[size] = l1[i];
count[size] = 1;
size++;
}
else {
count[size-1]++;
}
}
int[][] fin = {Arrays.copyOf(sorted, size),Arrays.copyOf(count, size)};
return fin;
}
static class CS{
HashMap<Integer, Integer> m1 = new HashMap<>();
void add(int n1, int k1){
int old = 0;
if (m1.containsKey(n1)){
old = m1.get(n1);
}
old += k1;
if (old == 0){
m1.remove(n1);
}
else {
m1.put(n1,old);
}
}
int get(int n1){
if (m1.containsKey(n1)){
return m1.get(n1);
}
return 0;
}
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 598bcb7de700b785f2f341d04ceec28a | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
class Ball implements Comparable<Ball>{
int size;
int cnt;
Ball(int b, int cnt){ this.size = b; this.cnt = cnt;}
public int compareTo(Ball b){
return -(cnt - b.cnt);
}
}
public void solve() throws IOException {
int N = nextInt();
Map<Integer, Integer> map = new TreeMap<>();
for(int i = 0; i < N; i++){
int now = nextInt();
if(map.containsKey(now)) map.put(now, map.get(now) + 1);
else map.put(now, 1);
}
Queue<Ball> q = new PriorityQueue<>();
for(Map.Entry<Integer, Integer> me : map.entrySet()){
q.add(new Ball(me.getKey(), me.getValue()));
}
int cntTriplets = 0;
StringBuilder sb = new StringBuilder();
while(q.size() >= 3){
Ball a = q.poll();
Ball b = q.poll();
Ball c = q.poll();
int[] ans = {a.size, b.size, c.size};
Arrays.sort(ans);
sb.append(ans[2] + " " + ans[1] + " " + ans[0] + "\n");
cntTriplets++;
if(a.cnt > 1) q.add(new Ball(a.size, a.cnt - 1));
if(b.cnt > 1) q.add(new Ball(b.size, b.cnt - 1));
if(c.cnt > 1) q.add(new Ball(c.size, c.cnt - 1));
}
System.out.println(cntTriplets);
System.out.print(sb.toString());
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
} | Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 779a105085ad9c84ebb847d2d17c3540 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import javax.swing.plaf.metal.OceanTheme;
public class NewYearSnowmen {
public static class node implements Comparable<node> {
int x;
int accurence;
node(int x, int accurence) {
this.x = x;
this.accurence = accurence;
}
@Override
public int compareTo(node o) {
if (o.accurence > accurence)
return 1;
else
return -1;
}
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder q = new StringBuilder();
int n = Integer.parseInt(in.readLine());
String y[] = in.readLine().split(" ");
HashMap<Integer, Integer> mp = new HashMap();
node a[] = new node[n];
int count = 0;
for (int i = 0; i < n; i++) {
int k = Integer.parseInt(y[i]);
if (!mp.containsKey(k)) {
mp.put(k, count);
a[count++] = new node(k, 1);
} else {
a[mp.get(k)].accurence++;
}
}
PriorityQueue<node> pq = new PriorityQueue<>();
for (int i = 0; i < count; i++) {
pq.add(a[i]);
}
int ans = 0;
while (!pq.isEmpty()) {
node one = pq.poll();
if(pq.isEmpty())
break;
node two = pq.poll();
if(pq.isEmpty())
break;
node three = pq.poll();
int max = Math.max(Math.max(one.x, two.x), three.x);
int min = Math.min(Math.min(one.x, two.x), three.x);
int med = one.x + two.x + three.x - min - max;
ans++;
q.append(max+" "+med+" "+min+"\n");
one.accurence--;
two.accurence--;
three.accurence--;
if(one.accurence>0)
pq.add(one);
if(two.accurence>0)
pq.add(two);
if(three.accurence>0)
pq.add(three);
}
System.out.println(ans);
System.out.println(q);
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 51ddc676f066b006322ca3ee06d7b6ac | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.util.Map;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.PriorityQueue;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Queue;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - vuondenthanhcong@yahoo.com
*/
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) {
int count = in.readInt();
int[] radius = IOUtils.readIntArray(in, count);
Map<Integer, Integer> index = new HashMap<Integer, Integer>();
final int[] perRidius = new int[count];
int sizeCount = 0;
for (int i : radius){
if (!index.containsKey(i)){
radius[sizeCount] = i;
index.put(i, sizeCount++);
}
perRidius[index.get(i)]++;
}
Queue<Integer> queue = new PriorityQueue<Integer>(sizeCount, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return perRidius[o2] - perRidius[o1];
}
});
for (int i = 0; i < sizeCount; i++)
queue.add(i);
int answer = 0;
int[][] snowMen = new int[count / 3][3];
while (queue.size() > 2) {
for (int i = 0; i < 3; i++)
snowMen[answer][i] = queue.poll();
for (int i : snowMen[answer]){
if (--perRidius[i] > 0)
queue.add(i);
}
for (int i = 0; i < 3; i++)
snowMen[answer][i] = radius[snowMen[answer][i]];
Arrays.sort(snowMen[answer]);
int temp = snowMen[answer][0];
snowMen[answer][0] = snowMen[answer][2];
snowMen[answer][2] = temp;
answer++;
}
out.printLine(answer);
for (int i = 0; i < answer; i++)
out.printLine(snowMen[i][0], snowMen[i][1], snowMen[i][2]);
}
}
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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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();
}
}
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.readInt();
return array;
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | bf75e712fbcbac7a9f1617758012c973 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] values = br.readLine().trim().split(" ");
Map<Integer, Integer> ballsMap = new HashMap<Integer, Integer>(n);
for (int i = 0; i < n; i++) {
int currBall = Integer.parseInt(values[i]);
Integer count = ballsMap.get(currBall);
if (count == null) {
ballsMap.put(currBall, 1);
} else {
ballsMap.put(currBall, count + 1);
}
}
Queue<SameBalls> ballsHeap = new PriorityQueue<SameBalls>(n);
for (Map.Entry<Integer, Integer> sameBallsEntry : ballsMap.entrySet()) {
int ballSize = sameBallsEntry.getKey();
int ballCount = sameBallsEntry.getValue();
SameBalls balls = new SameBalls();
balls.ballSize = ballSize;
balls.ballCount = ballCount;
ballsHeap.add(balls);
}
int result = 0;
List<SnowMan> resultList = new ArrayList<SnowMan>(n);
while (true) {
SameBalls first = ballsHeap.poll();
SameBalls second = ballsHeap.poll();
SameBalls third = ballsHeap.poll();
if (first == null || second == null || third == null) {
break;
}
result++;
SnowMan snowMan = new SnowMan();
snowMan.first = first.ballSize;
snowMan.second = second.ballSize;
snowMan.third = third.ballSize;
resultList.add(snowMan);
first.ballCount--;
if (first.ballCount > 0) {
ballsHeap.add(first);
}
second.ballCount--;
if (second.ballCount > 0) {
ballsHeap.add(second);
}
third.ballCount--;
if (third.ballCount > 0) {
ballsHeap.add(third);
}
}
System.out.println(result);
for (SnowMan snowMan : resultList) {
System.out.println(snowMan);
}
}
public static class SameBalls implements Comparable<SameBalls> {
public int ballSize;
public int ballCount;
@Override
public int compareTo(SameBalls other) {
if (ballCount > other.ballCount) {
return -1;
} else if (ballCount < other.ballCount) {
return 1;
}
return ballSize < other.ballSize ? -1 : 1;
}
}
public static class SnowMan {
public int first;
public int second;
public int third;
@Override
public String toString() {
int[] sizes = new int[3];
sizes[0] = first;
sizes[1] = second;
sizes[2] = third;
Arrays.sort(sizes);
StringBuilder builder = new StringBuilder();
for (int i = 2; i >= 0; i--) {
builder.append(sizes[i]);
if (i != 0) {
builder.append(" ");
}
}
return builder.toString();
}
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | b7697ac738d17f51eb113c483dfe1b06 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.*;
public class TascC2 {
public static class Pair implements Comparable<Pair>
{
int r;
int n;
public int compareTo(Pair p2)
{
return p2.n-this.n;
}
Pair(int R,int N)
{
r=R;
n=N;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
// TODO Auto-generated method stub
int n=sc.nextInt();
int r;
int amount=0;
int snows[][]=new int[n/3+1][3];
Map<Integer,Integer> balls=new HashMap<Integer,Integer>();
List<Integer> list=new LinkedList<Integer>();
PriorityQueue<Pair> pq=new PriorityQueue<Pair>();
for(int i=0;i<n;i++)
{
r=sc.nextInt();
if(!((r==3)&&(i==0)))
if(balls.containsKey((r)))
{
balls.put(r, balls.get(r) + 1);
}
else
{
balls.put(r, 1);
list.add(r);
}
}
for(int i:list)
{
pq.add(new Pair(i,balls.get(i)));
}
Pair p1;
Pair p2;
Pair p3;
while(pq.size()>2)
{
p1=pq.poll();
p2=pq.poll();
p3=pq.poll();
snows[amount][0]=-p1.r;
snows[amount][1]=-p2.r;
snows[amount][2]=-p3.r;
p1.n--;
if(p1.n>0) pq.add(p1);
p2.n--;
if(p2.n>0) pq.add(p2);
p3.n--;
if(p3.n>0) pq.add(p3);
Arrays.sort(snows[amount]);
amount++;
}
System.out.println(amount);
for(int i=0;i<amount;i++)
{
System.out.println(-snows[i][0]+" "+-snows[i][1]+" "+-snows[i][2]);
}
//
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 09f0438f8f1d5c8308bfe7ce6ea5f2e0 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main{
private class Element implements Comparable<Element>{
private int value;
private int occ;
public Element(int a, int b){
value = a;
occ = b;
}
public Element(Element e){
this.value = e.value;
this.occ = e.occ;
}
public void decOcc(){
occ--;
}
public void incOcc(){
occ++;
}
public boolean occIsZero(){
return occ == 0;
}
@Override
public int compareTo(Element o) {
return -new Integer(occ).compareTo(o.occ);
}
public String toString(){
return String.format("[%d, %d]", value, occ);
}
}
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.run(new Scanner(System.in)));
}
public String run(Scanner sc){
int n = sc.nextInt();
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
while(n-- != 0){
int t = sc.nextInt();
m.put(t, m.containsKey(t) ? m.get(t) + 1 : 1);
}
PriorityQueue<Element> q = new PriorityQueue<Main.Element>();
for(int t : m.keySet())
q.add(new Element(t, m.get(t)));
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
while(q.size() > 2){
Element e1 = q.poll();
Element e2 = q.poll();
Element e3 = q.poll();
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(e1.value);
t.add(e2.value);
t.add(e3.value);
res.add(t);
if(e1.occ > 1){
e1.decOcc();
q.add(new Element(e1));
}
if(e2.occ > 1){
e2.decOcc();
q.add(new Element(e2));
}
if(e3.occ > 1){
e3.decOcc();
q.add(new Element(e3));
}
}
StringBuilder s = new StringBuilder();
s.append(res.size() + "\n");
for(ArrayList<Integer> t : res){
Collections.sort(t);
s.append(t.get(2) + " " + t.get(1) + " " + t.get(0) + "\n");
}
return s.toString();
}
} | Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 63fe039c70029c630dc32376c8dd6240 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | /*
ID: nikchee1
PROB: Snowmen
LANG: JAVA
*/
import java.io.*;
import java.util.*;
public class Main{
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int N = in.nextInt();
static TreeMap<Integer, Integer> prq = new TreeMap<Integer, Integer>();
public static void main(String[] args){
for(int i = 0; i < N; i++){
int rad = in.nextInt();
if(prq.containsKey(rad)){
prq.put(rad, prq.get(rad) + 1);
} else{
prq.put(rad, 1);
}
}
int A = 0;
int B = N/3;
int bk = 0;
while(A <= B){
int min = 0;
int mid = (A + B)/2;
for (int i : prq.keySet()){
min += Math.min(mid, prq.get(i));
}
if(min >= mid*3){
bk = mid;
A = mid + 1;
}
else{
B = mid - 1;
}
} //binary search on the midpoint (between 0 and N/3)
out.println(bk);
ArrayList<Integer> holder = new ArrayList<Integer>();
for(Integer key : prq.keySet()){
for(int i = 0; i < Math.min(bk, prq.get(key)); i++){
holder.add(key);
}
}
for(int i = 0; i < bk; i++){
out.println(holder.get(i + 2*bk) + " " + holder.get(i + bk) + " " + holder.get(i));
}
out.close();
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | c66d0c5ad713757f9207f024793fd2ee | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author User
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int numSnow = Integer.parseInt(input.readLine());
int xc;
int x;
contant l1[] = new contant[3];
StringTokenizer inp = new StringTokenizer(input.readLine());
HashMap<Integer, Integer> snowballs = new HashMap<>();
for (int i = 0; i < numSnow; i++) {
xc = Integer.parseInt(inp.nextToken());
if (snowballs.containsKey(xc)) {
snowballs.put(xc, snowballs.get(xc) + 1);
} else {
snowballs.put(xc, 1);
}
}
PriorityQueue<contant> val = new PriorityQueue<>();
for (Integer integer : snowballs.keySet()) {
val.add(new contant(integer, snowballs.get(integer)));
}
int result = 0;
ArrayList<Integer> output = new ArrayList<>();
while ((!val.isEmpty()) && val.size() >= 3) {
for (int i = 0; i < 3; i++) {
l1[i] = val.poll();
}
result++;
for (int i = 0; i < 3; i++) {
output.add(l1[i].number);
l1[i].freq--;
if (l1[i].freq > 0) {
val.add(l1[i]);
}
}
}
System.out.println(result);
int a[];
for (int i = 0; i < output.size(); i += 3) {
a = new int[3];
a[0] = output.get(i);
a[1] = output.get(i + 1);
a[2] = output.get(i + 2);
Arrays.sort(a);
System.out.println(a[2] + " " + a[1] + " " + a[0]);
}
}
}
class contant implements Comparable<contant> {
int number;
int freq;
public contant(int number, int freq) {
this.number = number;
this.freq = freq;
}
@Override
public int compareTo(contant o) {
if (freq > o.freq) {
return -1;
} else if (freq < o.freq) {
return 1;
} else if (number > o.number) {
return -1;
} else if (number < o.number) {
return 1;
} else {
return 0;
}
}
} | Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | e9543f963049caeedb3a05f5eddc1f4a | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.util.*;
public class CF140C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
HashMap<Integer, Integer> f = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i ++)
{
int a = in.nextInt();
if(!f.containsKey(a))
f.put(a, 0);
f.put(a, f.get(a) + 1);
}
ans = new ArrayList<String>();
PriorityQueue<Snowball> pq = new PriorityQueue<Snowball>();
for(int e: f.keySet())
pq.add(new Snowball(e, f.get(e)));
while(pq.size() > 2)
{
Snowball a = pq.poll();
Snowball b = pq.poll();
Snowball c = pq.poll();
getOutput(a, b, c);
a.f --;
b.f --;
c.f --;
if(a.f > 0)
pq.add(a);
if(b.f > 0)
pq.add(b);
if(c.f > 0)
pq.add(c);
}
System.out.println(ans.size());
for(String e: ans)
System.out.println(e);
}
static ArrayList<String> ans;
static void getOutput(Snowball a, Snowball b, Snowball c)
{
int[] sort = {a.v, b.v, c.v};
Arrays.sort(sort);
String x = "";
for(int j = 2; j > -1; j --)
x += sort[j] + " ";
ans.add(x);
}
static class Snowball implements Comparable<Snowball>
{
int v;
int f;
Snowball(int value, int frequency)
{
v = value;
f = frequency;
}
public int compareTo(Snowball s) {
return s.f - f;
}
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 02c79c0796a18e0ae23b4f02cbbae3ab | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.*;
import java.util.*;
public class Pr402C {
public static void main(String[] args) throws IOException {
new Pr402C().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out, true);
solve();
out.flush();
}
void solve() throws IOException {
int n = nextInt();
if (n < 3) {
out.println(0);
return;
}
int[] r = new int[n];
for (int i = 0; i < n; i++) {
r[i] = nextInt();
}
Arrays.sort(r);
boolean is = false;
for (int i = 0; i < n - n / 3; i++) {
if (i + (n / 3) < n && r[i] == r[i + (n / 3)]) {
is = true;
}
}
if (!is) {
out.println(n / 3);
for (int i = 0; i < n / 3; i++) {
out.println(r[i + (n / 3) * 2] + " " + r[i + n / 3] + " "
+ r[i]);
}
return;
}
int vmaxi = -1;
int vmaxj = -2;
int qmaxi = -1;
int qmaxj = -2;
int i = 0;
while (i < n) {
int j = i;
while (j + 1 < n && r[j + 1] == r[j]) {
j++;
}
if (vmaxi == -1 || j - i > vmaxj - vmaxi) {
qmaxi = vmaxi;
qmaxj = vmaxj;
vmaxi = i;
vmaxj = j;
} else {
if (qmaxi == -1 || j - i > qmaxj - qmaxi) {
qmaxj = j;
qmaxi = i;
}
}
i = j + 1;
}
int col = Math.min(
Math.min(n / 3, n - (vmaxj - vmaxi + 1) - (qmaxj - qmaxi + 1)),
(n - (vmaxj - vmaxi + 1)) / 2);
int[] a = new int[col];
int[] b = new int[col];
int[] c = new int[col];
for (int k = 0; k < col; k++) {
a[k] = r[k];
}
i = col;
int cnt = 0;
while (cnt < col) {
while (a[cnt] == r[i]) {
i++;
}
b[cnt] = r[i];
cnt++;
i++;
}
cnt = 0;
while (cnt < col) {
while (b[cnt] == r[i]) {
i++;
}
c[cnt] = r[i];
cnt++;
i++;
}
out.println(col);
for (int k = 0; k < col; k++) {
out.println(c[k] + " " + b[k] + " " + a[k]);
}
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 2f05aefeae779e5d8738ce05e3dbd8e2 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.System.*;
import static java.lang.Integer.*;
public class CF140C{
public static void main(String[] args)throws Exception{
BufferedReader sc = new BufferedReader(new InputStreamReader(in));
int n = parseInt(sc.readLine());
StringTokenizer st = new StringTokenizer(sc.readLine());
ArrayList<Num> nums = new ArrayList<Num>();
HashMap<Integer, Num> map = new HashMap<Integer, Num>();
for(int i=0; i<n; i++){
int t = parseInt(st.nextToken());
if(map.containsKey(t)){
map.get(t).t++;
}else{
Num num = new Num();
num.n = t;
num.t = 1;
nums.add(num);
map.put(t, num);
}
}
ArrayList<Snowman> snowmen = new ArrayList<Snowman>();
PriorityQueue<Num> pq = new PriorityQueue<Num>();
for(int i=0; i<nums.size(); i++){
pq.offer(nums.get(i));
}
while(pq.size() > 2){
Num a = pq.poll();
Num b = pq.poll();
Num c = pq.poll();
snowmen.add(new Snowman(a.n, b.n, c.n));
a.t--;
b.t--;
c.t--;
if(a.t > 0){
pq.offer(a);
}
if(b.t > 0){
pq.offer(b);
}
if(c.t > 0){
pq.offer(c);
}
}
StringBuilder sb = new StringBuilder();
sb.append(snowmen.size() + "\n");
for(int i=0; i<snowmen.size(); i++){
Snowman s = snowmen.get(i);
sb.append(s.size[2] + " " + s.size[1] + " " + s.size[0] + "\n");
}
out.print(sb);
}
}
class Num implements Comparable<Num>{
int n, t;
public Num(){}
public Num(Num num){
n = num.n;
t = num.t;
}
public int compareTo(Num n){
return n.t-t;
}
}
class Snowman{
int[] size = new int[3];
public Snowman(int x, int y, int z){
size[0] = x;
size[1] = y;
size[2] = z;
Arrays.sort(size);
}
} | Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 9d0075f71dc02eadf6ac46878dd7737d | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class ProblemC {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int next() {
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 = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static class BallSet implements Comparable<BallSet> {
int value;
int cnt;
BallSet(int v, int c) {
value = v;
cnt = c;
}
@Override
public int compareTo(BallSet arg0) {
if (cnt != arg0.cnt) {
return arg0.cnt - cnt;
}
return arg0.value - value;
}
}
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] r = new int[n];
for (int i = 0 ; i < n ; i++) {
r[i] = in.nextInt();
}
for (int i = 0 ; i < n ; i++) {
int t = (int)(Math.random() * n);
int tm = r[t];
r[t] = r[i];
r[i] = tm;
}
Arrays.sort(r);
Map<Integer,Integer> rmp = new HashMap<Integer,Integer>();
for (int i = 0 ; i < n ; i++) {
if (!rmp.containsKey(r[i])) {
rmp.put(r[i], rmp.size());
}
}
int[][] cnt = new int[rmp.size()][2];
for (int i : rmp.keySet()) {
cnt[rmp.get(i)][0] = i;
}
for (int i = 0 ; i < n ; i++) {
cnt[rmp.get(r[i])][1]++;
}
int kn = rmp.size();
Queue<BallSet> q = new PriorityQueue<BallSet>();
for (int i = 0 ; i < kn ; i++) {
q.add(new BallSet(cnt[i][0], cnt[i][1]));
}
List<Integer> snowmen = new ArrayList<Integer>();
while (q.size() >= 3) {
BallSet a = q.poll();
BallSet b = q.poll();
BallSet c = q.poll();
int head = Math.min(a.value, Math.min(b.value, c.value));
int butt = Math.max(a.value, Math.max(b.value, c.value));
int body = a.value + b.value + c.value - head - butt;
int use = 1;
for (int i = 0 ; i < use ; i++) {
snowmen.add(butt);
snowmen.add(body);
snowmen.add(head);
}
a.cnt -= use;
b.cnt -= use;
c.cnt -= use;
if (a.cnt >= 1) {
q.add(a);
}
if (b.cnt >= 1) {
q.add(b);
}
if (c.cnt >= 1) {
q.add(c);
}
}
out.println(snowmen.size() / 3);
for (int i = 0 ; i < snowmen.size() ; i += 3) {
out.println(snowmen.get(i) + " " + snowmen.get(i+1) + " " + snowmen.get(i+2));
}
out.flush();
}
public static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 08cec25e54147d9f138ad454bf5284e9 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.*;
import java.util.*;
public class test
{
public static void main(String[] args)
{
new test().run();
}
void run()
{
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>();
int n = in.nextInt();
for (int i = 0; i < n; i++)
{
int r = in.nextInt();
if (tm.containsKey(r))
tm.put(r, tm.get(r) + 1);
else
tm.put(r, 1);
}
int start = 0;
int end = n / 3;
int k = 0;
while (start <= end)
{
int mid = start + (end - start) / 2;
int total = 0;
for (int i : tm.keySet())
{
total += Math.min(mid, tm.get(i));
}
if (total >= 3 * mid)
{
k = mid;
start = mid + 1;
}
else
end = mid - 1;
}
out.println(k);
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i : tm.keySet())
{
for (int j = 0; j < Math.min(k, tm.get(i)); j++)
al.add(i);
}
for (int i = 0; i < k; i++)
{
out.println(al.get(2 * k + i) + " " + al.get(k + i) + " "
+ al.get(i));
}
out.close();
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | 8d3527255d268bf15c92590cd2072eb5 | train_003.jsonl | 1325689200 | As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class ProblemC {
public static void main(String[] args) {
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
new ProblemC().solve(in, out);
out.close();
}
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] r = new int[n];
for (int i = 0; i < n; i++) {
r[i] = in.nextInt();
}
Map<Integer, Integer> index = new HashMap<Integer, Integer>();
final int[] perRadius = new int[n];
int sizeCount = 0;
for (int i = 0; i < n; i++) {
if (!index.containsKey(r[i])) {
r[sizeCount] = r[i];
index.put(r[i], sizeCount++);
}
perRadius[index.get(r[i])]++;
}
Queue<Integer> queue = new PriorityQueue<Integer>(sizeCount, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return perRadius[o2] - perRadius[o1];
}
});
for (int i = 0; i < sizeCount; i++) {
queue.add(i);
}
int answer = 0;
int[][] result = new int[n / 3][3];
while (queue.size() > 2) {
for (int j = 0; j < 3; j++) {
result[answer][j] = queue.poll();
}
for (int i : result[answer]) {
if (--perRadius[i] != 0) {
queue.add(i);
}
}
for (int j = 0; j < 3; j++) {
result[answer][j] = r[result[answer][j]];
}
Arrays.sort(result[answer]);
answer++;
}
out.println(answer);
for (int i = 0; i < answer; i++) {
out.println(result[i][2] + " " + result[i][1] + " " + result[i][0]);
}
}
static class InputReader {
public BufferedReader br;
public StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7\n1 2 3 4 5 6 7", "3\n2 2 3"] | 2 seconds | ["2\n3 2 1\n6 5 4", "0"] | null | Java 7 | standard input | [
"data structures",
"binary search",
"greedy"
] | 551e66a4b3da71682652d84313adb8ab | The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide. | 1,800 | Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them. | standard output | |
PASSED | b73887a0a0def0b01dd9c66c0045f2f5 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io. *;
import java.util.*;
import static java.lang.Math.*;
public class Main {
static final FastReader sc = new FastReader(System.in);
static final PrintWriter pw = new PrintWriter(System.out);
static int visited[];
static ArrayList<ArrayList<Integer>> adjlist;
static class edge implements Comparator<edge>{
int dest;
int cost;
public edge(int dest, int cost) {
this.dest = dest;
this.cost = cost;
}
@Override
public int compare(edge o1, edge o2) {
return o1.cost-o2.cost;
}
}
static int dist[];
static int nodesInSubtree[];
static int k;
static class Graph {
int V;
ArrayList<ArrayList<edge>> adj;
PriorityQueue<edge> pq;
boolean visited[];
public Graph(int V) {
this.V = V;
adj = new ArrayList<>(V);
//pq = new PriorityQueue<>(V, new edge(-1, -1));
nodesInSubtree = new int[V];
dist = new int[V];
visited = new boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
adj.add(i, new ArrayList<>());
}
}
void addedge(int u, int v, int w) {
adj.get(u).add(new edge(v, w));
adj.get(v).add(new edge(u, w));
}
void rDfs(int src, int e) {
int m = k;
nodesInSubtree[src] = 1;
int sz = adj.get(src).size();
int nodes[] = new int[sz];
for (int i = 0; i < adj.get(src).size(); i++) {
if (adj.get(src).get(i).dest == e) {
continue;
}
rDfs(adj.get(src).get(i).dest,src);
nodes[i] = nodesInSubtree[adj.get(src).get(i).dest];
}
if(sz<m){
return;
}else if(sz<=m && src != 1){
return;
}
Arrays.sort(nodes);
for(int i = sz - 1; i>=0 && m>0; i--,m--){
nodesInSubtree[src] += nodes[i];
}
}
/*
void dijkstra(int src){
for(int i=0; i<V; i++){
dist[i] = Integer.MAX_VALUE;
}
dist[src] = 0;
pq.add(new edge(src,0));
while (!pq.isEmpty()){
int u = pq.poll().dest;
for(int i=0; i<adj.get(u).size(); i++){
int v = adj.get(u).get(i).dest;
int w = adj.get(u).get(i).cost;
if(dist[u]+w<=dist[v]){
dist[v] = dist[u] + w;
pq.add(new edge(v,dist[v]));
}
}
}
}
}
*/
}
static int I[];
static int L[];
static int LIS(int n, int arr[]){
I = new int[n+1];
L = new int[n];
I[0] = Integer.MIN_VALUE;
for(int i=1;i<=n; i++){
I[i] = Integer.MAX_VALUE;
}
int lisLength = 1;
int cm = 0;
for(int i=n-1; i>=0; i--) {
int low = 1;
int high = lisLength;
int mid = 0;
while (low < high) {
mid = (low + high) >> 1;
if (I[mid] <= arr[i]) {
high = mid;
} else {
low = mid + 1;
}
}
if(I[high]==arr[i]){
cm++;
}
I[high] = arr[i];
L[i] = high;
if(lisLength<=high){
lisLength++;
}
}
return 1;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static long lcm(long a, long b)
{
return (a*b)/gcd(a, b);
}
static long nCr(long n, long r)
{
return fact(n) / (fact(r) * fact(n - r));
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (int i = 2; i <= n; i++)
res = (res * i)%MOD;
return res;
}
static int MOD = 1000000007;
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p-2, p);
}
static int nCrModPFermat(int n, int r,
int p)
{
if (r == 0)
return 1;
int[] fac = new int[n+1];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[n]* modInverse(fac[r], p)
% p * modInverse(fac[n-r], p)
% p) % p;
}
static int[] phi;
static void generatePhi(int n){
phi = new int[n+1];
for(int i = 0; i<=n; i++){
phi[i] = i;
}
for(int i=2; i<=n; i++){
if(phi[i]==i){
for(int j= i; j<=n; j+=i){
phi[j] -= (phi[j]/i);
}
}
}
}
static int gcdCount(int n, int d){
return phi[n/d];
}
static boolean prime[];
static int smallestFactor[];
static void sieveOfEratosthenes(int n)
{
prime = new boolean[n+1];
smallestFactor = new int[n+1];
smallestFactor[1] = 1;
for(int i=2;i<n;i++) {
prime[i] = true;
smallestFactor[i] = i;
}
for(int p = 2; p*p <=n; p++)
{
if(prime[p])
{
smallestFactor[p] = p;
for(int i = p*p; i <= n; i += p) {
prime[i] = false;
smallestFactor[i] = min(p,smallestFactor[i]);
}
}
}
}
static double Logx(double n, int x){
return log(n)/log(x);
}
static boolean isPrime(long n){
if(n<2){
return false;
}
for(int i = 2; i*i<=n; i++){
if(n%i==0){
return false;
}
}
return true;
}
static int sumOfDigits(int n){
int digitSum = 0;
while (n>0){
digitSum+=n%10;
n/=10;
}
return digitSum;
}
static boolean checkSum(PriorityQueue<Integer> pq, long s){
long sum = 0;
while (!pq.isEmpty()){
sum+= pq.poll();
}
if(sum>s){
return false;
}
return true;
}
static int dsu[];
static int findParent(int x){
if(dsu[x]<0){
return x;
}
return findParent(dsu[x]);
}
static class Primes implements Comparable<Primes>{
int prime;
int occurance;
@Override
public int compareTo(Primes o) {
return this.occurance - o.occurance;
}
}
static long convertToDecimal(String s){
if(s.charAt(0)=='0'){
if(s.charAt(1)=='x'){
String res = s.substring(2,s.length());
return Long.parseLong(res,16);
}else{
String res = s.substring(1,s.length());
return Long.parseLong(s,8);
}
}
return Long.parseLong(s);
}
public static void main(String[] args) {
int testcase = sc.nextInt();
int z = 0;
while (z++<testcase){
int n = sc.nextInt();
int p = sc.nextInt();
int k = sc.nextInt();
int a[] = new int[n+1];
char tempa[] = sc.next().toCharArray();
for(int i = 0; i<n; i++){
a[i+1] = tempa[i] - '0';
}
int x = sc.nextInt();
int y = sc.nextInt();
int cost[] = new int[n+1];
for(int i = n; i>=p; i--){
if(i+k <= n){
if(a[i]==0){
cost[i] = x + cost[i+k];
}else{
cost[i] = cost[i+k];
}
}else{
if(a[i]==0) {
cost[i] = x;
}else {
cost[i] = 0;
}
}
}
long ans = Long.MAX_VALUE;
for(int i = p; i<=n; i++){
long res = (i-p)*y + cost[i];
ans = min(ans,res);
}
pw.println(ans);
}
pw.flush();
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public String nextLine(){
int b = readByte();
StringBuilder sb = new StringBuilder();
while(b != '\n' || b != '\r'){
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char[] next(int n){
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public char nextChar () {
return (char) skip();
}
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | ad1d51f419cf376070db039c2b5079c9 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.util.*;
import java.io.*;
public class MainClass
{
public static void main(String[] args)throws IOException
{
// Reader in = new Reader();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
StringBuilder stringBuilder = new StringBuilder();
while (t-- > 0)
{
String s1[] = in.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int p = Integer.parseInt(s1[1]) - 1;
int k = Integer.parseInt(s1[2]);
char[] S = in.readLine().toCharArray();
int[] A = new int[n];
for (int i=0;i<n;i++) A[i] = S[i] - '0';
s1 = in.readLine().split(" ");
long x = Long.parseLong(s1[0]);
long y = Long.parseLong(s1[1]);
long[] dp = new long[n];
for (int i=n - 1;i>=0;i--)
{
if (A[i] == 0)
dp[i] += x;
if (i + k < n)
dp[i] += dp[i + k];
}
long ans = Long.MAX_VALUE;
for (int i=p;i<n;i++)
{
ans = Math.min(ans, (i - p) * y + dp[i]);
}
stringBuilder.append(ans).append("\n");
}
System.out.println(stringBuilder);
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 33a7a3a21a13d8b6ad32342abe8cb399 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.*;
import java.util.stream.IntStream;
public class C {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new BufferedInputStream(System.in, 1 << 20));
int t = in.nextInt();
for (int i = 0; i < t; i++) {
int n = in.nextInt();
int p = in.nextInt();
int k = in.nextInt();
char[] as = in.next().toCharArray();
int x = in.nextInt();
int y = in.nextInt();
int hops = (n - p - 1) / k + 1;
int offs = Math.min(n - p + 1, k);
int[] ps = new int[offs];
for (int j = 0; p + j <= n; j++) {
if (as[p + j - 1] == '1') {
++ps[j % k];
}
}
int result = Integer.MAX_VALUE;
for (int j = 0; p + j <= n; j++) {
result = Math.min(result, y*j + x*(((n - p - j) / k + 1) - ps[j % k]));
if (as[p + j - 1] == '1') {
--ps[j % k];
}
}
System.out.println(result);
}
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 8282f628fafae4859cec8c051a5dbed1 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.util.Scanner;
/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/
public class Main {
public static void main(String[] args) {
// Write your solution here
Scanner scanner = new Scanner(System.in);
int t = Integer.parseInt(scanner.nextLine());
while (t-- > 0) {
int n = scanner.nextInt();
int p = scanner.nextInt();
int k = scanner.nextInt();
scanner.nextLine();
char[] arr = scanner.nextLine().toCharArray();
int add = scanner.nextInt();
int remove = scanner.nextInt();
scanner.nextLine();
int[] dp = new int[n+1];
for (int i = n-1; i >= 0; i--) {
if(arr[i] == '1'){
if(i + k < n){
dp[i] = dp[i+k];
}
}
else{
if(i + k < n){
dp[i] = dp[i+k];
}
dp[i] += add;
}
}
int min = Integer.MAX_VALUE;
for (int i = p-1; i < n; i++) {
min = Math.min(min,dp[i] + remove*(i-p+1));
}
System.out.println(min);
}
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | a556238dc0a6984c5460da0d195d9eb6 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes |
//@author->.....future_me......//
//..............Learning.........//
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.BigInteger;
public class B {
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
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;
}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int mod = 1000000007;
static ArrayList<dis> aa;
static int dis[][];
public static void main(String[] args) throws Exception {
// try {
int t = sc.nextInt();
while (t-- > 0)
B.go();
// } catch (Exception e) {
// return;
// }
}
static void go() {
int n = sc.nextInt();
int p = sc.nextInt();
int k = sc.nextInt();
char s[] = sc.next().toCharArray();
int x = sc.nextInt();
int y = sc.nextInt();
boolean f = false;
ArrayList<Integer> ind = new ArrayList<>();
for (int i = p - 1; i < n; i += k) {
if (s[i] - '0' == 0) {
f = true;
}
ind.add(i);
}
Arrays.fill(dp, -1);
if (f == false) {
System.out.println(0);
return;
}
long cost1 = 0;
for (int i : ind) {
if (s[i] == '0') {
cost1 += x * 1l;
}
}
long cost2 = 0;
int a[] = new int[n];
for (int i = 0; i < n; i++) {
if (s[i] == '0') {
a[i] = 1;
}
}
for (int i = n - 1; i >= 0; i--) {
if (i + k >= n) {
continue;
} else {
a[i] += a[i + k];
}
}
// System.out.println(Arrays.toString(a));
long ans = Long.MAX_VALUE;
for (int i = 0; i < n - p; i++) {
cost2 += y;
// System.out.println(p - 1 + i + 1);
long c = a[p - 1 + i + 1] * x;
ans = Math.min(ans, c + cost2);
}
System.out.println(Math.min(cost1, ans));
// System.out.println(Arrays.toString(dp));
}
static long dp[] = new long[15];
static long solve(char a[], int l, int n, int k, int x) {
if (l >= n) {
return 0;
}
if (dp[l] != -1) {
return dp[l];
}
return dp[l] = (a[l] == '0' ? x : 0) + solve(a, l + k, n, k, x);
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static void sort(long[] a) {
ArrayList<Long> aa = new ArrayList<>();
for (long i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static long pow(long x, long y) {
long res = 1l;
while (y != 0) {
if (y % 2 == 1) {
res = x * res;
}
y /= 2;
x = x * x;
}
return res;
}
}
class dis {
int x;
int y;
dis(int x, int y) {
this.x = x;
this.y = y;
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | e9d756a538f0fd77d83903d29c76135e | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes |
//@author->.....future_me......//
//..............Learning.........//
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.BigInteger;
public class B {
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
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;
}
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int mod = 1000000007;
static ArrayList<dis> aa;
static int dis[][];
public static void main(String[] args) throws Exception {
// try {
int t = sc.nextInt();
while (t-- > 0)
B.go();
// } catch (Exception e) {
// return;
// }
}
static void go() {
int n = sc.nextInt();
int p = sc.nextInt();
int k = sc.nextInt();
char s[] = sc.next().toCharArray();
int x = sc.nextInt();
int y = sc.nextInt();
boolean f = false;
ArrayList<Integer> ind = new ArrayList<>();
for (int i = p - 1; i < n; i += k) {
if (s[i] - '0' == 0) {
f = true;
}
ind.add(i);
}
Arrays.fill(dp, -1);
if (f == false) {
System.out.println(0);
return;
}
long cost1 = 0;
for (int i : ind) {
if (s[i] == '0') {
cost1 += x * 1l;
}
}
long cost2 = 0;
long ans = Long.MAX_VALUE;
for (int i = 0; i < n - p; i++) {
cost2 += y;
long c = solve(s, p - 1 + i + 1, n, k, x);
ans = Math.min(ans, c + cost2);
}
System.out.println(Math.min(cost1, ans));
}
static long dp[] = new long[100005];
static long solve(char a[], int l, int n, int k, int x) {
if (l >= n) {
return 0;
}
if (dp[l] != -1) {
return dp[l];
}
return dp[l] = (a[l] == '0' ? x : 0) + solve(a, l + k, n, k, x);
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static void sort(long[] a) {
ArrayList<Long> aa = new ArrayList<>();
for (long i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static long pow(long x, long y) {
long res = 1l;
while (y != 0) {
if (y % 2 == 1) {
res = x * res;
}
y /= 2;
x = x * x;
}
return res;
}
}
class dis {
int x;
int y;
dis(int x, int y) {
this.x = x;
this.y = y;
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 2f4ffc62cbb33a44f3bd846ffc53c029 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | // No sorcery 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 t=inp.nextInt();
while(t-->0) {
int n=inp.nextInt();
int p=inp.nextInt();
int k=inp.nextInt();
String s=inp.next();
int x=inp.nextInt();
int y=inp.nextInt();
int cost[]=new int[n];
for(int i=0;i<n;i++) {
cost[i]=s.charAt(i)=='0'?x:0;
}
for(int i=n-k-1;i>=0;i--) {
cost[i]+=cost[i+k];
}
//for(int i=0;i<n;i++) out.print(cost[i]+" ");
long gg=Long.MAX_VALUE;
for(int i=p-1;i<n;i++) {
gg=Math.min(gg, (i-p+1)*y+cost[i]);
}
out.println(gg);
}
}
/*********************************************************************************************************************************************************************************************************
* 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;;;;;;;;;;; *
***********************************************************************************************************************************************************************************************************/
void sort(int a[]) {
ArrayList<Integer> list=new ArrayList<>();
for(int x: a) list.add(x);
Collections.sort(list);
for(int i=0;i<a.length;i++) a[i]=list.get(i);
}
void sort(long a[]) {
ArrayList<Long> list=new ArrayList<>();
for(long x: a) list.add(x);
Collections.sort(list);
for(int i=0;i<a.length;i++) a[i]=list.get(i);
}
void ruffleSort(int a[]) {
Random rand=new Random();
int n=a.length;
for(int i=0;i<n;i++) {
int j=rand.nextInt(n);
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Arrays.sort(a);
}
void ruffleSort(long a[]) {
Random rand=new Random();
int n=a.length;
for(int i=0;i<n;i++) {
int j=rand.nextInt(n);
long temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Arrays.sort(a);
}
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;
}
}
long fact[];
long invFact[];
void init(int n) {
fact=new long[n+1];
invFact=new long[n+1];
fact[0]=1;
for(int i=1;i<=n;i++) {
fact[i]=mul(i,fact[i-1]);
}
invFact[n]=power(fact[n],mod-2);
for(int i=n-1;i>=0;i--) {
invFact[i]=mul(invFact[i+1],i+1);
}
}
long nCr(int n, int r) {
if(n<r || r<0) return 0;
return mul(fact[n],mul(invFact[r],invFact[n-r]));
}
long add(long a, long b) {
return (a+b)%mod;
}
long mul(long a, long b) {
return a*b%mod;
}
long power(long x, long y) {
long gg=1;
while(y>0) {
if(y%2==1) gg=mul(gg,x);
x=mul(x,x);
y/=2;
}
return gg;
}
// 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);
}
void print(int a[]) {
int n=a.length;
for(int i=0;i<n;i++) out.print(a[i]+" ");
}
void print(long a[]) {
int n=a.length;
for(int i=0;i<n;i++) out.print(a[i]+" ");
}
//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 | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 40d5ee520e9a11a3b0633361554d5337 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Solutions {
private final static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
int n = scanner.nextInt();
// 0 - indexed
int p = scanner.nextInt() - 1;
int k = scanner.nextInt();
String row = scanner.next();
int x = scanner.nextInt();
int y = scanner.nextInt();
runTest(row, p, k, x, y);
}
}
private static void runTest(String r, int p, int k, int x, int y) {
List<Boolean> row = new ArrayList<>();
for (int i = 0; i < r.length(); i++) {
row.add(r.charAt(i) == '1');
}
int[] costAfterShift = needToAdd(row, k, p);
long best = Long.MAX_VALUE;
for (int shift = 0; shift < costAfterShift.length; shift++) {
best = Math.min(best, (long) shift * y + (long) x * costAfterShift[shift]);
}
System.out.println(best);
}
private static int[] needToAdd(List<Boolean> row, int k, int p) {
int[] arr = new int[row.size() - p];
for (int i = 0; i < k && i < arr.length; i++) {
int toAdd = 0;
int j = i + p;
while (j < row.size()) {
if (!row.get(j)) {
toAdd++;
}
j += k;
}
arr[i] = toAdd;
}
for (int i = k; i < arr.length; i++) {
arr[i] = arr[i - k] + ((row.get(p + i - k)) ? 0 : -1);
}
return arr;
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | ff8c36a3aa22ac6e89f528b071e9980c | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Prison {
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String s = br.readLine();
String[] str = s.split(" ");
int n = Integer.parseInt(str[0]);
int p = Integer.parseInt(str[1]);
int k = Integer.parseInt(str[2]);
String a = br.readLine();
s = br.readLine();
str = s.split(" ");
int x = Integer.parseInt(str[0]);
int y = Integer.parseInt(str[1]);
int[] dp = new int[n];
Arrays.fill(dp,Integer.MAX_VALUE);
int min = Integer.MAX_VALUE;
for (int i = dp.length-1; i >= p-1; i--) {
int j = i-p+1;
if(i+k>=n){
if(a.charAt(i)=='1'){
dp[i] = 0;
}
else {
dp[i] = x;
}
}
else {
if(a.charAt(i)=='1'){
dp[i] = dp[i+k];
}
else {
dp[i] = dp[i+k]+x;
}
}
}
for (int i = dp.length-1; i >= p-1; i--) {
if(dp[i]!=Integer.MAX_VALUE) {
min = Math.min(min, dp[i]+(i-p+1)*y);
}
}
System.out.println(min);
}
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 597d7e81cbd1103e9c93dc20327c3eb6 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{ static BufferedReader br;
static PrintWriter out;
static StringBuilder res = new StringBuilder();
static final int mod = 1000000007;
static ArrayList<Integer> primes = new ArrayList<>();
static long start,time;
public static void main(String[] args) throws Exception {
start();
String s = br.readLine();
if(s==null)return;
s=s.trim();
int tc = Integer.parseInt(s);
while(tc-->0){
solve();
}
// time = System.currentTimeMillis()-start;
// res.append("Executed in : "+time+"ms");
out.println(res);
out.flush();
}
static void println(Object str){
out.write(str+"\n");
}
static void print(Object str){
out.write(str+"");
}
static void off() throws Exception{
//start time
// start = System.currentTimeMillis();
//for self
br = new BufferedReader(new FileReader("input.txt"));
out=new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
}
static void on()throws Exception{
//for online
br = new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(new OutputStreamWriter(System.out));
}
static int[] getArr(int size) throws Exception{
int[] arr = new int[size];
String[] str = br.readLine().trim().replaceAll(" +"," ").split(" ");
for(int i=0;i<size;i++){
arr[i] = Integer.parseInt(str[i]);
}
return arr;
}
static int[] getArrLine(int size) throws Exception{
int[] arr = new int[size];
for(int i=0;i<size;i++){
arr[i] = Integer.parseInt(br.readLine());
}
return arr;
}
static void printArr(int[] arr){
StringBuilder sb = new StringBuilder();
for(int i=0;i<arr.length;i++){
sb.append(arr[i]+" ");
}
res.append(sb+"\n");
}
static int getInt() throws Exception{
return Integer.parseInt(br.readLine());
}
static void computePrime(){
int n = 100001;
BitSet bs = new BitSet();
bs.flip(2,n+1);
for(int i=2;i*i<=n;i++){
if(bs.get(i)){
for(int j=i*i;j<=n;j+=i){
bs.clear(j);
}
}
}
for(int i=0;i<=n;i++){
if(bs.get(i))primes.add(i);
}
}
static int gcd(int i,int j){
if(j==0)return i;
return gcd(j,i%j);
}
static void solve() throws Exception{
int[] vals = getArr(3);
String s = br.readLine().trim();
int[] xy = getArr(2);
int size = vals[0], p = vals[1], k = vals[2], x = xy[0], y = xy[1];
int[] dp = new int[size];
for(int i=size-1;i>=size-k;i--){
if(s.charAt(i)=='0'){
dp[i]=1;
}
}
for(int i=size-k-1;i>=0;i--){
dp[i]=dp[i+k];
if(s.charAt(i)=='0')dp[i]++;
}
int min = Integer.MAX_VALUE;
for(int i=p-1;i<size;i++){
int curr = (y*(i-p+1))+(x*dp[i]);
min = Math.min(min,curr);
}
res.append(min+"\n");
}
static void start() throws Exception{
on();
// off();
}
//set on before uploading
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 5636b27705372399a7510b9179bf22d0 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt(), p = sc.nextInt(), k = sc.nextInt();
char[] arr = sc.next().toCharArray();
int x = sc.nextInt(), y = sc.nextInt();
int[] freq = new int[k];
for (int i = p - 1; i < arr.length; i++) {
if (arr[i] == '0') {
freq[(i - p + 1) % k]++;
}
}
int min = (int) 1e9;
for (int i = p - 1; i < n; i++) {
min = Math.min(min, freq[(i - p + 1) % k] * x + (i - p + 1) * y);
if (arr[i] == '0') {
freq[(i - p + 1) % k]--;
}
}
pw.println(min);
// pw.println(Arrays.toString(freq));
}
pw.close();
}
public static class pair implements Comparable<pair> {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + "," + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Double(x).hashCode() * 31 + new Double(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 08ae86c0e8a84ad7d9b8e8746db7e41b | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.*;
public class BouncingBall
{
public static void main(String[] args) throws IOException
{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = Integer.parseInt(f.readLine());
for (int K=0; K<t; K++)
{
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
String str = f.readLine();
boolean[] a = new boolean[n+1];
for (int i=1; i<=n; i++)
{
a[i] = str.charAt(i-1)=='1';
}
st = new StringTokenizer(f.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int[] count = new int[n+1];
for (int i=0; i<n; i++)
{
int index = n-i;
if (i>=k)
{
count[index] = count[index+k] + (a[index]?0:1);
}
else
{
count[index] = (a[index]?0:1);
}
}
int min = Integer.MAX_VALUE;
for (int i=0; i+p<=n; i++)
{
min = Math.min(count[i+p]*x+y*i, min);
}
out.println(min);
}
out.close();
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | bc6fe27e5bdddeac16eb28451e722bd8 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes |
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tc = input.nextInt();
while(tc-->0)
{
int n = input.nextInt();
int p = input.nextInt()-1;
int k =input.nextInt();
String s = input.next();
int x = input.nextInt();
int y = input.nextInt();
int min = Integer.MAX_VALUE;
int a[] = new int[n];
for (int i = n-1; i >=0; i--) {
a[i]= (s.charAt(i)=='0')?1:0;
if(i+k<n)
a[i]+=a[i+k];
if(i>=p)
{
min = Math.min(min, (i-p)*y+a[i]*x);
}
}
System.out.println(min);
}
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 49ebc5f102df88f213932936081969c7 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
static FastScanner sc;
static PrintWriter pw;
static final long INF = 1000000150l;
public static Integer cycle_end, cycle_st;
public static int[] p;
public static int[] cl;
public static List<List<Integer>> g;
public static boolean[] marked;
static boolean dfs(int v ) {
cl[v] = 1;
for(int i = 0; i < g.get(v).size(); ++i) {
int to = g.get(v).get(i);
if(cl[to] == 0) {
p[to] = v;
if(dfs(to)) return true;
} else if(cl[to] == 1 && p[v] != to){
cycle_end = v;
cycle_st = to;
return true;
}
}
cl[v] = 2;
return false;
}
static int dfs2(int v, Set<Integer> cycle) {
marked[v] = true;
int count = 0;
for(int i = 0; i < g.get(v).size(); ++i) {
int to = g.get(v).get(i);
if(!cycle.contains(to) && !marked[to]) {
count += dfs2(to, cycle);
}
}
return count + 1;
}
public static void main(String[] args) throws IOException {
sc = new FastScanner(System.in);
pw = new PrintWriter(System.out);
int ff = sc.nextInt();
for(int tt = 0; tt < ff; ++tt) {
int n = sc.nextInt(), p = sc.nextInt(), k = sc.nextInt();
String s = sc.next();
int x = sc.nextInt(), y = sc.nextInt();
long[] dp = new long[n + 3*k];
Arrays.fill(dp, INF);
for(int i = p - 1; i < n + 3 * k; ++i) {
if(i < n)
dp[i] = (i - p + 1) * y + (i < n && s.charAt(i) == '0' ? 1 : 0) * x;
if(i - k >= 0)
dp[i] = Math.min( dp[i - k] + (i < n && s.charAt(i) == '0' ? 1 : 0) * x, dp[i]);
}
long ans = INF;
for(int i = n; i <= n + k; ++i)
ans = Math.min(ans, dp[i]);
// pw.println(Arrays.toString(dp));
pw.println(ans);
}
pw.close();
}
}
class FastScanner {
static StringTokenizer st = new StringTokenizer("");
static BufferedReader br;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | c481f5548ced3b5e549efa068e2c793c | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
static FastScanner sc;
static PrintWriter pw;
static final long INF = 10000000000l;
public static Integer cycle_end, cycle_st;
public static int[] p;
public static int[] cl;
public static List<List<Integer>> g;
public static boolean[] marked;
static boolean dfs(int v ) {
cl[v] = 1;
for(int i = 0; i < g.get(v).size(); ++i) {
int to = g.get(v).get(i);
if(cl[to] == 0) {
p[to] = v;
if(dfs(to)) return true;
} else if(cl[to] == 1 && p[v] != to){
cycle_end = v;
cycle_st = to;
return true;
}
}
cl[v] = 2;
return false;
}
static int dfs2(int v, Set<Integer> cycle) {
marked[v] = true;
int count = 0;
for(int i = 0; i < g.get(v).size(); ++i) {
int to = g.get(v).get(i);
if(!cycle.contains(to) && !marked[to]) {
count += dfs2(to, cycle);
}
}
return count + 1;
}
public static void main(String[] args) throws IOException {
sc = new FastScanner(System.in);
pw = new PrintWriter(System.out);
int ff = sc.nextInt();
for(int tt = 0; tt < ff; ++tt) {
int n = sc.nextInt(), p = sc.nextInt(), k = sc.nextInt();
String s = sc.next();
int x = sc.nextInt(), y = sc.nextInt();
long[] dp = new long[n + 3*k];
Arrays.fill(dp, INF);
for(int i = p - 1; i < n + 3 * k; ++i) {
if(i < n)
dp[i] = (i - p + 1) * y + (i < n && s.charAt(i) == '0' ? 1 : 0) * x;
if(i - k >= 0)
dp[i] = Math.min( dp[i - k] + (i < n && s.charAt(i) == '0' ? 1 : 0) * x, dp[i]);
}
long ans = INF;
for(int i = n; i <= n + k; ++i)
ans = Math.min(ans, dp[i]);
// pw.println(Arrays.toString(dp));
pw.println(ans);
}
pw.close();
}
}
class FastScanner {
static StringTokenizer st = new StringTokenizer("");
static BufferedReader br;
public FastScanner(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 064686e09f2ccef489c14a5d3994c182 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
public class Main
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int t=in.nextInt();
while(t>0)
{
t--;
int n=in.nextInt();
int p=in.nextInt();
int k=in.nextInt();
String s=in.next();
int x=in.nextInt();
int y=in.nextInt();
p--;
int[] prefix=new int[n];
for(int i=p;i<n;i++)
{
if(i-k>=0)
prefix[i]+=prefix[i-k];
if(s.charAt(i)=='0')
prefix[i]++;
}
int ans=Integer.MAX_VALUE;
for(int i=p;i<n;i++)
{
int num=y*(i-p);
int z=(n-1-i)/k;
int tmp=i-k>=p?prefix[i-k]:0;
num+=x*(prefix[i+z*k]-tmp);
ans=Math.min(ans,num);
}
System.out.println(ans);
}
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 0a785d4ebc1fa888703df6473c7a969e | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
// graph, dfs,bfs, get connected components,iscycle, isbipartite, dfs on trees
public class scratch_25 {
static class Graph{
public static class Vertex{
HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex
}
public static HashMap<Integer,Vertex> vt; // for vertices(all)
public Graph(){
vt= new HashMap<>();
}
public static int numVer(){
return vt.size();
}
public static boolean contVer(int ver){
return vt.containsKey(ver);
}
public static void addVer(int ver){
Vertex v= new Vertex();
vt.put(ver,v);
}
public class Pair{
int vname;
ArrayList<Integer> psf= new ArrayList<>(); // path so far
int dis;
int col;
}
public static void addEdge(int ver1, int ver2, int weight){
if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){
return;
}
Vertex v1= vt.get(ver1);
Vertex v2= vt.get(ver2);
v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge
v2.nb.put(ver1,weight);
}
public static void delEdge(int ver1, int ver2){
if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){
return;
}
vt.get(ver1).nb.remove(ver2);
vt.get(ver2).nb.remove(ver1);
}
public static void delVer(int ver){
if(!vt.containsKey(ver)){
return;
}
Vertex v1= vt.get(ver);
ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet());
for (int i = 0; i <arr.size() ; i++) {
int s= arr.get(i);
vt.get(s).nb.remove(ver);
}
vt.remove(ver);
}
static boolean done[];
static int parent[];
static ArrayList<Integer>vals= new ArrayList<>();
public static boolean isCycle(int i){
Stack<Integer>stk= new Stack<>();
stk.push(i);
while(!stk.isEmpty()){
int x= stk.pop();
vals.add(x);
// System.out.print("current="+x+" stackinit="+stk);
if(!done[x]){
done[x]=true;
}
else if(done[x] ){
return true;
}
ArrayList<Integer>ar= new ArrayList<>(vt.get(x).nb.keySet());
for (int j = 0; j <ar.size() ; j++) {
if(parent[x]!=ar.get(j)){
parent[ar.get(j)]=x;
stk.push(ar.get(j));
}
}
// System.out.println(" stackfin="+stk);
}
return false;
}
static int distance[];
static ArrayList<Integer>ans= new ArrayList<>();
public static long bfs(int v){
long total=0;
Queue<Integer>q= new LinkedList<>();
q.add(v);
while(!q.isEmpty()){
int x= q.poll();
done[x]=true;
total++;
ArrayList<Integer>vals= new ArrayList<>(vt.get(x).nb.keySet());
for (int i = 0; i <vals.size() ; i++) {
int c= vals.get(i);
if(!done[c]){
q.add(c);
}
}
}
return total;
}
}
// int count=0;
//static long count=0;
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/**
* call this method to initialize reader for InputStream
*/
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, or negative after MOD
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int t= Reader.nextInt();
for (int tt = 0; tt <t ; tt++) {
int n= Reader.nextInt();
int p= Reader.nextInt();
int k= Reader.nextInt();
char arr[]= Reader.next().toCharArray();
int add= Reader.nextInt();
int del= Reader.nextInt();
int vals[]= new int[n];
Arrays.fill(vals,-1);
for (int i = p-1; i <n ; i++) {
if(vals[i]==-1){
int count=0;
for (int j = i; j <n ; j+=k) {
if(arr[j]=='0'){
count++;
}
}
for (int j = i; j <n ; j+=k) {
vals[j]=count;
if(arr[j]=='0'){
count--;
}
}
}
}
// System.out.println(Arrays.toString(vals));
long min = Integer.MAX_VALUE;
for (int i = p-1; i <n ; i++) {
long val= (long)((i-(p-1))*(long)(del) + (long)vals[i]*(long)add);
min= Math.min(min,val);
}
out.append(min+"\n");
}
out.flush();
out.close();
}
static long modExp(long a, long b, long mod) {
//System.out.println("a is " + a + " and b is " + b);
if (a==1) return 1;
long ans = 1;
while (b!=0) {
if (b%2==1) {
ans = (ans*a)%mod;
}
a = (a*a)%mod;
b/=2;
}
return ans;
}
public static long modmul(long a, long b, long mod) {
return b == 0 ? 0 : ((modmul(a, b >> 1, mod) << 1) % mod + a * (b & 1)) % mod;
}
static long sum(long n){
// System.out.println("lol="+ (n*(n-1))/2);
return (n*(n+1))/2;
}
public static ArrayList<Integer> Sieve(int n) {
boolean arr[]= new boolean [n+1];
Arrays.fill(arr,true);
arr[0]=false;
arr[1]=false;
for (int i = 2; i*i <=n ; i++) {
if(arr[i]){
for (int j = 2; j <=n/i ; j++) {
int u= i*j;
arr[u]=false;
}}
}
ArrayList<Integer> ans= new ArrayList<>();
for (int i = 0; i <n+1 ; i++) {
if(arr[i]){
ans.add(i);
}
}
return ans;
}
static long power( long x, long y, long p)
{
long res = 1;
x = x % p;
if (x == 0) return 0;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long ceil_div(long a, long b){
return (a+b-1)/b;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b)
{
return (a*b)/gcd(a, b);
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | e20eab00ff8ffa6d0c226f77d548a0f7 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 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
{ FastReader in = new FastReader(System.in);
StringBuilder sb = new StringBuilder();
int t=1;
t=in.nextInt();
while(t>0){
--t;
int n=in.nextInt();
int p=in.nextInt()-1;
int k=in.nextInt();
char arr[]=in.next().toCharArray();
int x=in.nextInt();
int y=in.nextInt();
int st[]=new int[n];
int cost[]=new int[n];
for(int i=p;i<n;i++)
{
if(arr[i]=='0')
{
st[i]=((i-p)*y)+x;
}
else
st[i]=(i-p)*y;
}
for(int i=n-k-1;i>=0;i--)
{
if(arr[i+k]=='0')
cost[i]=x+cost[i+k];
else
cost[i]=cost[i+k];
}
int ans=Integer.MAX_VALUE;
for(int i=p;i<n;i++)
{
ans=Math.min(ans,cost[i]+st[i]);
}
sb.append(ans+"\n");
}
System.out.print(sb);
}
static int upper_bound(int arr[],int x){
int a=Arrays.binarySearch(arr,x);
if(a<0){
a*=(-1);
return a-1;
}
else{
while(a<arr.length && arr[a]==x)
++a;
return a;
}
}
static long gcd(long a ,long b)
{
if(a==0)
return b;
else return gcd(b%a,a);
}
//------making a Fendwick tree ---//
// creating a fendwick tree
static long ftree[];
static void buildFendwicktree(int arr[],int n)
{
ftree=new long[n+1];
for(int i=0;i<n;i++)
upftree(arr[i],i,n);
}
static void upftree(int value,int n,int i)
{
int index=i+1;
while(index<=n)
{
ftree[index]+=value;
index+=(index&(-index)); // adding last bit to the index
}
}
static long getSum(int index)
{
long sum=0;
index+=1;
while(index>0)
{
sum+=ftree[index];
index-=(index&(-index)); // fliping last index of the tree;
}
return sum;
}
//------Fendwick tree ends ---------//
}
class sgmtree{
int arr[];
sgmtree(int input[],int n){
arr=new int[100001];
buildtree(input,1,0,n-1);
}
void buildtree(int input[],int si,int ss,int se){
if(ss==se){
arr[si]=input[ss];
return;
}
int mid=(ss+se)/2;
buildtree(input,2*si,ss,mid);
buildtree(input,2*si+1,mid+1,se);
arr[si]=Math.min(arr[2*si],arr[2*si+1]);
}
int query(int si,int ss,int se,int qs,int qe){
if(qs>se || qe<ss)
return Integer.MAX_VALUE;
if(ss>=qs && qe>=se)
return arr[si];
int mid=(ss+se)/2;
int l=query(2*si,ss,mid,qs,qe);
int r=query(2*si+1,mid+1,se,qs,qe);
return Math.min(l,r);
}
void update(int input[],int index,int value){
input[index]=value;
updateutils(input,1,0,input.length-1,index);
}
void updateutils(int input[],int si,int ss,int se,int qi){
if(ss==se){
arr[si]=input[ss];
return;
}
int mid=(ss+se)/2;
if(qi<=mid)
updateutils(input,2*si,ss,mid,qi);
else
updateutils(input,2*si+1,mid+1,se,qi);
arr[si]=Math.min(arr[2*si],arr[2*si+1]);
}
}
/* This is for sorting first accorting to gain[1] if gain[1] is same the gain[0]
Arrays.sort(gain, (long[] l1, long[] l2) -> {
if(l1[1] != l2[1])return Long.compare(l2[1], l1[1]);//Sorting in non-increasing order of gain
return Long.compare(l1[0], l2[0]);//Choosing smallest bit among all bits having same gain
});
*/
class pair{
int x,y;
pair(int x,int y){
this.x=x;
this.y=y;
}
}
class CompareValue {
static void compare(pair arr[], int n)
{
Arrays.sort(arr, new Comparator<pair>() {
public int compare(pair p1, pair p2)
{
return p1.y - p2.y;
}
});
}
}
class CompareKey{
static void compare(pair arr[],int n){
Arrays.sort(arr,new Comparator<pair>(){
public int compare(pair p1,pair p2)
{
return p2.x-p1.x;
}
});
}
}
class FastReader {
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
return (char) c;
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan()) ;
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
} | Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | d3adef6714edd8dfcad88314c85f4ca0 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | //package j.gym.codeforces.regular.r68x.r687;
import java.io.*;
import java.util.*;
public class R687Div2C {
public void solve(InputProvider in, PrintWriter out) throws IOException {
int testCount = in.nextInt();
for (int test = 0; test < testCount; test++) {
int pointCount = in.nextInt();
int firstStepSize = in.nextInt() - 1;
int stepSize = in.nextInt();
int[] points = in.nextLine().chars().map(c -> c - '0').toArray();
long addTime = in.nextInt();
long removeTime = in.nextInt();
long[] pointTime = new long[pointCount];
for (int i = pointCount - 1, nextStepPointIndex = i + stepSize; i >= 0; i--, nextStepPointIndex--) {
pointTime[i] = points[i] == 1 ? 0 : addTime;
if (nextStepPointIndex < pointCount) {
pointTime[i] += pointTime[nextStepPointIndex];
}
}
long minTime = pointTime[firstStepSize];
long totalRemoveTime = removeTime;
for (int i = 0; i < pointCount - firstStepSize - 1; i++, totalRemoveTime += removeTime) {
long timeWithRemoval = totalRemoveTime + pointTime[i + firstStepSize + 1];
minTime = Math.min(minTime, timeWithRemoval);
}
out.print(minTime + "\n");
}
}
public static void main(String[] args) throws Exception {
try (InputProvider input = new InputProvider(System.in);
PrintWriter output = new PrintWriter(System.out)) {
new R687Div2C().solve(input, output);
}
}
public static class InputProvider implements AutoCloseable {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputProvider(Reader reader) {
this.reader = new BufferedReader(reader);
}
public InputProvider(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
}
public String next() throws IOException {
if (Objects.isNull(tokenizer) || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return reader.readLine();
}
@Override
public void close() throws Exception {
reader.close();
}
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | b2250904fcea7d796aa9f778d92f2ad0 | train_003.jsonl | 1606633500 | You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $$$1$$$, and in each cell you can either put a platform or leave it empty.In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $$$p$$$, then bounces off it, then bounces off a platform in the cell $$$(p + k)$$$, then a platform in the cell $$$(p + 2k)$$$, and so on every $$$k$$$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $$$p$$$ and $$$k$$$.You already have some level pattern $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, where $$$a_i = 0$$$ means there is no platform in the cell $$$i$$$, and $$$a_i = 1$$$ means there is one. You want to modify it so that the level can be passed with given $$$p$$$ and $$$k$$$. In $$$x$$$ seconds you can add a platform in some empty cell. In $$$y$$$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $$$p$$$. Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added. What is the minimum number of seconds you need to make this level passable with given $$$p$$$ and $$$k$$$? | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while(t-->0) {
int n = in.nextInt(), p = in.nextInt()-1, k = in.nextInt();
char ch[] = in.next().toCharArray();
int x = in.nextInt(), y = in.nextInt();
long ans[] = new long[n];
Arrays.fill(ans,(int)1e9);
ans[p] = 0;
for(int i=p;i<n;i++){
if(i-k>=p) ans[i] = ans[i-k];
if(i-p>0) ans[i] = Math.min(ans[i],y*(i-p));
if(ch[i]!='1'){
ans[i] += x;
}
}
long min = ans[n-k];
for(int i=1;i<=k;i++) min = Math.min(min,ans[n-i]);
out.println(min);
}
out.flush();
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while(!st.hasMoreTokens())
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
}
| Java | ["3\n10 3 2\n0101010101\n2 2\n5 4 1\n00000\n2 10\n11 2 3\n10110011000\n4 3"] | 1 second | ["2\n4\n10"] | NoteIn the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $$$y = 2$$$.In the second test case it's best to add a platform to both cells $$$4$$$ and $$$5$$$: 00000 $$$\to$$$ 00011. The time required is $$$x \cdot 2 = 4$$$.In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $$$10$$$-th: 10110011000 $$$\to$$$ 10110011010. The time required is $$$y \cdot 2 + x = 10$$$. | Java 8 | standard input | [
"dp",
"implementation"
] | 112a0cac4e1365c854bb651d3ee38df9 | The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$p$$$, and $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required. The second line of each test case contains a string $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — the initial pattern written without spaces. The last line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — the time required to add a platform and to remove the first cell correspondingly. The sum of $$$n$$$ over test cases does not exceed $$$10^5$$$. | null | For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly. It can be shown that it is always possible to make the level passable. | standard output | |
PASSED | 87ac5998034474be9703ae01bfb1fe54 | train_003.jsonl | 1549208100 | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew? | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class b {
public static PrintWriter out;
public static FS sc;
public static void main(String[] Args) throws Exception
{
sc = new FS(System.in);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = sc.nextInt();
int k = sc.nextInt();
int m = sc.nextInt();
int[] vs= new int[n];
long sum = 0;
for (int i = 0; i < n; i++)
{
vs[i] = sc.nextInt();
sum += vs[i];
}
double ans = 0;
Arrays.sort(vs);
for (int i = 0; i <= m && i < n; i++)
{
long incs1 = m - i;
long incs2 = (n - i) * 1l * k;
if (incs1 > incs2)
incs1 = incs2;
double tans = (sum + incs1) * 1.0 / (n - i);
if (tans > ans)
ans = tans;
sum -= vs[i];
}
out.println(ans);
out.close();
}
public static class FS
{
StringTokenizer st;
BufferedReader br;
FS(InputStream in) throws Exception
{
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
String next() throws Exception
{
if (st.hasMoreTokens())
return st.nextToken();
st = new StringTokenizer(br.readLine());
return next();
}
int nextInt() throws Exception
{
return Integer.parseInt(next());
}
long nextLong() throws Exception
{
return Long.parseLong(next());
}
double nextDouble() throws Exception
{
return Double.parseDouble(next());
}
// [Value, Power of 10]
/*
long[] nextDoubleAsLong() throws Exception
{
long[] ret = new long[2];
String s = sc.next();
if (!s.contains(".") && !s.contains("e") && !s.contains("E")) {
ret[0] = Long.parseLong(s);
return ret;
}
// ???
return ret;
}
//*/
}
} | Java | ["2 4 6\n4 7", "4 2 6\n1 3 2 3"] | 1 second | ["11.00000000000000000000", "5.00000000000000000000"] | NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d6e44bd8ac03876cb03be0731f7dda3d | The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers. | 1,700 | Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$. | standard output | |
PASSED | 07717c073576c97b272c9fbcb1f8880a | train_003.jsonl | 1549208100 | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew? | 256 megabytes | import java.io.*;
import java.util.*;
public class AverageSuperpower {
public static void main(String[] args) throws Exception{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
long k = Integer.parseInt(st.nextToken());
long m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(f.readLine());
int[] a= new int[n];
long sum = 0;
for(int i = 0; i < n; i ++) {
a[i] = Integer.parseInt(st.nextToken());
sum += a[i];
}
Arrays.sort(a);
double max = (double)(sum + Math.min(k*n, m))/n;
for(int i = 0; i < n-1; i ++) {
sum -= a[i];
if(i + 1 > m) break;
max = Math.max(max, (double)(sum + Math.min(k*(n-i-1), m-i-1))/(n-i-1));
}
System.out.println(max);
}
}
| Java | ["2 4 6\n4 7", "4 2 6\n1 3 2 3"] | 1 second | ["11.00000000000000000000", "5.00000000000000000000"] | NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d6e44bd8ac03876cb03be0731f7dda3d | The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers. | 1,700 | Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$. | standard output | |
PASSED | c88b04d3fc4c7616b187124ce80a2937 | train_003.jsonl | 1549208100 | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew? | 256 megabytes | import java.util.*;
public class a{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int k=in.nextInt();
int m=in.nextInt();
Long[] ar=new Long[n];
double sum2=0;
for(int i=0;i<ar.length;i++){
ar[i]=in.nextLong();
sum2+=ar[i];
}
Arrays.sort(ar);
if(m>=ar.length){
m=m-(ar.length-1);
if(m>=k)
System.out.println(ar[ar.length-1]+k);
else if(m<k)
System.out.println(ar[ar.length-1]+m);
}
else{
double sum=sum2,value=0;
for(int i=0;i<=m;i++){
if(i>0)
sum=sum-ar[i-1];
double s=sum+m-i;
//System.out.println(s/(ar.length-i));
value=Math.max(((s)/(ar.length-i)),value);
}
System.out.println(value);
}
}
} | Java | ["2 4 6\n4 7", "4 2 6\n1 3 2 3"] | 1 second | ["11.00000000000000000000", "5.00000000000000000000"] | NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d6e44bd8ac03876cb03be0731f7dda3d | The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers. | 1,700 | Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$. | standard output | |
PASSED | 87d946a181cfdddedf68123499bac4e6 | train_003.jsonl | 1549208100 | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew? | 256 megabytes |
import java.util.*;
public class B1111 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int m = scanner.nextInt();
List<Integer> aArr = new ArrayList<>();
//求总和
long sum = 0;
for(int i=0;i<n;i++){
int a = scanner.nextInt();
aArr.add(a);
sum += a;
}
//排序
Collections.sort(aArr);
//最大平均数,每个数都+k,取平均值
double maxAvg = (sum + Math.min(m, (long)n*k)) / (double)n;
for(int i=1;i<n&&i<=m;i++){
sum -= aArr.get(i-1);
//计算删除i个元素后,剩下数的最大平均数
double p = (sum + Math.min(m-i, (long)(n-i)*k)) / (double)(n - i);
maxAvg = Math.max(maxAvg, p);
}
System.out.println(maxAvg);
}
}
| Java | ["2 4 6\n4 7", "4 2 6\n1 3 2 3"] | 1 second | ["11.00000000000000000000", "5.00000000000000000000"] | NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d6e44bd8ac03876cb03be0731f7dda3d | The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers. | 1,700 | Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$. | standard output | |
PASSED | 859a5f3635df5eb49462921fb1c95188 | train_003.jsonl | 1549208100 | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew? | 256 megabytes | /* MOHD SADIQ
mohdsadiq058
*/
import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
public class Main
{
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private String strVal() throws IOException{
return br.readLine().trim();
}
private long longVal() throws IOException {
return Long.parseLong(br.readLine().trim());
}
private int intVal() throws IOException {
return Integer.parseInt(br.readLine().trim());
}
private double doubleVal() throws IOException {
return Double.parseDouble(br.readLine().trim());
}
private int[] intArr() throws IOException {
String[] s = br.readLine().trim().split(" ");
int n = s.length;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(s[i]);
}
return a;
}
private long[] longArr() throws IOException {
String[] s = br.readLine().trim().split(" ");
int n = s.length;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = Long.parseLong(s[i]);
}
return a;
}
private double[] doubleArr() throws IOException {
String[] s = br.readLine().trim().split(" ");
int n = s.length;
double[] a = new double[n];
for (int i = 0; i < n; i++) {
a[i] = Double.parseDouble(s[i]);
}
return a;
}
private String[] stringArr() throws IOException {
String[] s = br.readLine().trim().split(" ");
return s;
}
private char[] charArr() throws IOException {
return br.readLine().trim().toCharArray();
}
// public static <A> min(A a, B b) {
// return Math.min(a,b);
// }
// public static <A> max(A a, B b) {
// return Math.max(a, b);
// }
public static String solve() throws IOException{
Main obj = new Main();
//int n = obj.intVal();
int[] xx = obj.intArr();
int n = xx[0], k = xx[1], m = xx[2];
int[] a = obj.intArr();
Arrays.sort(a);
double sum = 0;
long[] cum = new long[n + 1];
for (int i = 0; i < n; i++)
cum[i + 1] = cum[i] + a[i];
double max = 0;
for (int i = n; i >= 1; i--) {
long lm = m - (n - i);
if (lm < 0)
continue;
lm = Math.min(lm, (long) k * i);
max = Math.max(max, (double) (cum[n] - cum[n - i] + lm) / i);
}
return max+"";
}
public static void main(String[] args) throws IOException
{
Main ob = new Main();
// int total_test_case = ob.intVal();
int total_test_case = 1;
StringBuffer ans = new StringBuffer();
String k;
for (int test_case = 0; test_case < total_test_case; test_case++) {
k = ob.solve();
// System.out.println(k);
ans.append(k+"\n");
}
System.out.print(ans);
}
}
| Java | ["2 4 6\n4 7", "4 2 6\n1 3 2 3"] | 1 second | ["11.00000000000000000000", "5.00000000000000000000"] | NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d6e44bd8ac03876cb03be0731f7dda3d | The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers. | 1,700 | Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$. | standard output | |
PASSED | 1c7985b44b7d9a8f24ab47fb59a87100 | train_003.jsonl | 1549208100 | Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew? | 256 megabytes | import java.io.*;
import java.util.*;
public class B
{
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in) ;
PrintWriter out = new PrintWriter(System.out) ;
int n = sc.nextInt() ;
long k = sc.nextInt() , m = sc.nextInt();
int [] a = new int [n] ;
long total = 0 ;
for(int i = 0 ; i < n ;i++) { total += a[i] = sc.nextInt() ;}
long [] freq = new long[n + 1] ;
shuffle(a) ;
Arrays.sort(a);
for(int i = 1 ; i <= n ;i++)freq[i] += freq[i - 1] + a[i - 1] ;
double ans = 1.0 * total / n ;
for(int remove = 0 ; remove <= Math.min(n - 1, m) ; remove++)
ans = Math.max(1.0*(freq[n] - freq[remove] + Math.min(m - remove , (n - remove) * k)) / (1.0*(n - remove)), ans) ;
out.println(ans);
out.flush();
out.close();
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception { return Integer.parseInt(next()); }
long nextLong() throws Exception { return Long.parseLong(next()); }
double nextDouble() throws Exception { return Double.parseDouble(next());}
}
static void shuffle(int[] a)
{
int n = a.length;
for (int i = 0; i < n; i++)
{
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
} | Java | ["2 4 6\n4 7", "4 2 6\n1 3 2 3"] | 1 second | ["11.00000000000000000000", "5.00000000000000000000"] | NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each. | Java 8 | standard input | [
"implementation",
"brute force",
"math"
] | d6e44bd8ac03876cb03be0731f7dda3d | The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers. | 1,700 | Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$. | standard output | |
PASSED | cd67ec52fa52cb47d43c969df0169b30 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class SumOfOddIntegers {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-->0){
long n = sc.nextLong();
long k = sc.nextLong();
if(((n%2)==(k%2)) && ((k*k)<=n))
System.out.println("YES");
else
System.out.println("NO");
}
}
} | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 79b275483384f334557e8abfba08337c | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class SumOfOddIntegers {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-->0){
long n = sc.nextLong();
long k = sc.nextLong();
if(((n%2)==(k%2)) && ((k*k)<=n))
System.out.println("YES");
else
System.out.println("NO");
}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | d829530798b554f86bb15285f871eb05 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class SumOfOddIntegers {
public static String isSumOfOddNumbers(long n, long k){
if(n < k*k)
return "NO";
if(n%2 == 0 && k%2 != 0)
return "NO";
else if (n%2 != 0 && k%2 == 0 )
return "NO";
return "YES";
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while(scanner.hasNext()){
String line = scanner.nextLine();
if(line != null && !line.isEmpty()){
String[] values = line.split(" ");
System.out.println(isSumOfOddNumbers(Long.parseLong(values[0]),Long.parseLong(values[1])));
}
}
}
} | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 173b532c9849d8e9a96040f495358849 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader b1 = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(b1.readLine());
o: while(t-->0) {
String [] vals = (b1.readLine()).split(" ");
long n = Long.parseLong(vals[0]);
long k = Long.parseLong(vals[1]);
long prod = k*k;
if(prod > n) {
System.out.println("NO");
}
else {
if(n%2==0 && k%2==0) {
System.out.println("YES");
}
else if(k%2!=0 && n%2!=0) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
}
} | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | d1f06d4048040fc684db074420cf8f96 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 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.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int t = in.nextInt();
for (int i = 0; i < t; i++) {
long n = in.nextLong();
long k = in.nextLong();
if (k * k <= n && (n % 2 == k % 2)) {
out.println("YES");
} else {
out.println("NO");
}
}
}
}
static class FastReader {
BufferedReader in = null;
StringTokenizer st;
public FastReader() {
}
public FastReader(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
} catch (Exception e) {
return null;
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 15e7947350634a4cfddef848f2ac5f26 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | // package codeforces.educational_84;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* Created by Krishna Kota
*/
public class Main {
private static void solve(int testNumber, FastReader in, PrintWriter out) {
long n = in.nextLong();
long k = in.nextLong();
if (((n % 2 == 0 && k % 2 == 0) || (n % 2 == 1 && k % 2 == 1)) && (k * k <= n)) {
out.println("YES");
} else {
out.println("NO");
}
}
public static void main(String[] args) {
FastReader in = new FastReader(System.in);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int t = in.nextInt();
for (int i = 1; i <= t; i++) {
solve(i, in, out);
}
out.close();
}
static class FastReader {
BufferedReader in = null;
StringTokenizer st;
public FastReader() {
}
public FastReader(InputStream is) {
in = new BufferedReader(new InputStreamReader(is));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
} catch (Exception e) {
return null;
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
}
return null;
}
public void close() {
try {
in.close();
} catch (IOException e) {
}
}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 55ae7333700d952f2d01c01279ec2ca7 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class OddIntegers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = in.nextInt();
for (int j = 0; j < count; j++) {
long n = in.nextInt();
long k = in.nextInt();
if (n >= k * k && n % 2 == k % 2) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 245dafc1aec2d7326d0cd303da495cb6 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class OddIntegers {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = in.nextInt();
for (int j = 0; j < count; j++) {
long n = in.nextInt();
long k = in.nextInt();
if (n < k * k) {
System.out.println("NO");
} else if (n % 2 == 0) {
if (k % 2 == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
} else {
if (k % 2 == 1) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 30b7ef9d9055c12438382788af5087e1 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class First {
public static void main(final String args[]) {
int t;
Scanner in = new Scanner(System.in);
t = in.nextInt();
long n, k;
for (int i = 1; i <= t; i++) {
n = in.nextInt();
k = in.nextInt();
if (n >= k*k && (n - k*k) % 2 == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | af20a7e3b87d67ff9fc4ddb8b31bc5f7 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class First {
public static void main(final String args[]) {
int t;
Scanner in = new Scanner(System.in);
t = in.nextInt();
long n, k;
for (int i = 1; i <= t; i++) {
n = in.nextInt();
k = in.nextInt();
if (n < k * k) {
System.out.println("NO");
}
else {
if (n >= k*k && (n - k*k) % 2 == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
} | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | e112ac9b95c0af52dec31dd94744d5b5 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class JavaApplication {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int t=in.nextInt();
for(int j=0;j<t;j++){
int n=in.nextInt(),k=in.nextInt();
if (n % 2 == k % 2 && (long) k * k <= n)
{
System.out.println("YES");
}else System.out.println("NO");
}}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 2995f18ddbee0bf5e85a445db4571a21 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 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.StringTokenizer;
public class A {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
long n = sc.nextInt();
long k = sc.nextInt();
if(n%2 != k%2 || n < k*k)
out.println("NO");
else
out.println("YES");
}
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException{return Double.parseDouble(next());}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | faa54250213407c0de8f033785b7ed3f | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 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.StringTokenizer;
public class A {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
long n = sc.nextInt();
long k = sc.nextInt();
if(n%2 != k%2 || n < k*k)
out.println("NO");
else {
long ans = (long)(n - (k-1)*(k-1));
if(ans >= (2*(k-1)+1))
out.println("YES");
else
out.println("NO");
}
}
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException{return Double.parseDouble(next());}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 763df15442493dcd26720ef21615d78e | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.util.ArrayList;
public class Main{
public static void main(String[] args){
Scanner param = new Scanner(System.in);
int end=param.nextInt();
while(end-->0){
int n=param.nextInt();
int m=param.nextInt();
if(Math.sqrt(n)<m)
{
System.out.println("NO");
}
else
{
if(m%2==0){
if(n%2==0){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
else{
if(n%2!=0){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
}
} | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 866915c5eeb0f4b71d549155b0494c92 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.Scanner;
public class oddinteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int n,k;
for(int i = 0 ; i < t ; i++){
n = sc.nextInt();
k = sc.nextInt();
// boolean b = n >= (k * k);
if((n % 2 == 0) != (k % 2 == 0)) {
System.out.println("NO");
}
else if(k <= (n / k)){
System.out.println("YES");
}
else{
System.out.println("NO");
}
//System.out.println((2+((k-1)2)));
}
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 2a6430b49f9e8923f5860c0035127296 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | // package EducationalRound84;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class ProblemA {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder print=new StringBuilder();
int test=Integer.parseInt(br.readLine());
while(test--!=0){
st=new StringTokenizer(br.readLine());
int a=Integer.parseInt(st.nextToken());
int k=Integer.parseInt(st.nextToken());
if(a<1l*k*k){
print.append("NO\n");
continue;
}
if(a%2==0&&k%2!=0){
print.append("NO\n");
continue;
}
if(a%2!=0&&k%2==0){
print.append("NO\n");
continue;
}
print.append("YES\n");
}
System.out.print(print.toString());
}
}
| Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | 0f0f4c8a1a697415ccd1c7ae29b6ec09 | train_003.jsonl | 1584974100 | You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Main 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);
}
}
// if modulo is required set value accordingly
public static long[][] matrixMultiply2dL(long t[][],long m[][])
{
long res[][]= new long[t.length][m[0].length];
for(int i=0;i<t.length;i++)
{
for(int j=0;j<m[0].length;j++)
{
res[i][j]=0;
for(int k=0;k<t[0].length;k++)
{
res[i][j]+=t[i][k]+m[k][j];
}
}
}
return res;
}
static long combination(long n,long r)
{
long ans=1;
for(long i=0;i<r;i++)
{
ans=(ans*(n-i))/(i+1);
}
return ans;
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<27).start();
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0){
Long n = sc.nextLong();
Long k = sc.nextLong();
if(k%2==n%2 && n>=k*k)
System.out.println("YES");
else
System.out.println("NO");
}
System.out.flush();
w.close();
}
}
//https://codeforces.com/problemset/problem/1311/B
//https://codeforces.com/problemset/problem/1326/D1
//https://codeforces.com/problemset/problem/1326/B | Java | ["6\n3 1\n4 2\n10 3\n10 2\n16 4\n16 5"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES\nNO"] | NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers. | Java 8 | standard input | [
"math"
] | a4c82fffb31bc7e42870fd84e043e815 | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$). | 1,100 | For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise. | standard output | |
PASSED | e1d56e4955d99f0cea49e8a4f4c6eebc | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class DIV2423B {
public static PrintWriter out;
//-----------MyScanner class for faster input----------
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;
}
}
public static void main(String args[]) throws Exception {
class prob {
public void solve() {
MyScanner s = new MyScanner();
int n = s.nextInt();
int m = s.nextInt();
char[][] in = new char[n][m];
int x1 = n, y1 = m;
int x2 = -1, y2 = -1;
for (int i = 0; i < n; ++i) {
String str = s.next();
int j = 0;
for (char c : str.toCharArray()) {
in[i][j++] = c;
}
}
int bcount = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (in[i][j] == 'B') {
++bcount;
x1 = Math.min(x1, i);
y1 = Math.min(y1, j);
x2 = Math.max(x2, i);
y2 = Math.max(y2, j);
}
}
}
if (bcount == 0) {
System.out.println(1);
return;
}
int xmax = x2 - x1 + 1;
int ymax = y2 - y1 + 1;
int max = Math.max(xmax, ymax);
if (max > Math.min(n, m)) {
System.out.println(-1);
}
else {
System.out.println(max * max - bcount);
}
}
}
prob s = new prob();
s.solve();
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 12a07f58de01691a88f1347e87f8db32 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | //package TIM2;
import java.io.*;
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int mod;
public static void main(String[] args) {
char[][] a = new char[105][105];
int n = input.nextInt();
int m = input.nextInt();
for (int i = 0; i < n; i++) {
a[i] = input.next().toCharArray();
}
int top = -1, bottom = 101, left = 101, right = -1;
boolean flag = true;
int B = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i][j] == 'B') {
flag = false;
top = Math.max(top, i);
bottom = Math.min(bottom, i);
left = Math.min(left, j);
right = Math.max(right, j);
B++;
}
}
}
int size = Math.max(top - bottom + 1, right - left + 1);
if (flag) System.out.println(1);
else if (size > Math.min(m, n)) System.out.println(-1);
else System.out.println(size * size - B);
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 6aece70aeba2954326b03ebd17c6f65a | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int li = n;
int lj = m;
int mi = 0;
int mj = 0;
in.nextLine();
int black = 0;
for (int i = 0; i < n; i++) {
String line = in.nextLine();
for (int j = 0; j < m; j++) {
if (line.charAt(j) == 'B') {
li = Math.min(i, li);
lj = Math.min(j, lj);
mi = Math.max(i, mi);
mj = Math.max(j, mj);
black++;
}
}
}
int length = Math.max(mi - li, mj - lj) + 1;
if (length > n || length > m) {
out.println(-1);
return;
} else if (length == 1) {
out.println(0);
return;
} else if (length < 1) {
out.println(1);
return;
}
out.println((length * length) - black);
}
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 94bcce7eda6b68f52a6ef52306b8c2f0 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 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
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
boolean[][] map = new boolean[n][m];
int b = 0, r = 0, t = 1 << 30, l = 1 << 30;
boolean flag = false;
for (int i = 0; i < n; i++) {
String str = in.next();
for (int j = 0; j < m; j++) {
if (str.charAt(j) == 'W')
map[i][j] = false;
else {
flag = true;
map[i][j] = true;
t = Math.min(t, i);
l = Math.min(l, j);
b = Math.max(b, i);
r = Math.max(r, j);
}
}
}
int ans = 0;
for (int i = t; i <= b; i++)
for (int j = l; j <= r; j++)
if (!map[i][j])
ans++;
if (r - l > b - t) {
while (b - t < r - l && b + 1 < n) {
b++;
ans += r - l + 1;
}
while (b - t < r - l && t - 1 >= 0) {
t--;
ans += r - l + 1;
}
} else if (r - l < b - t) {
while (b - t > r - l && r + 1 < m) {
r++;
ans += b - t + 1;
}
while (b - t > r - l && l - 1 >= 0) {
l--;
ans += b - t + 1;
}
}
if (!flag)
ans = 1;
if ((ans == n * m && n != m) || r - l != b - t)
ans = -1;
out.println(ans);
return;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[16384];
private int curChar;
private int numChars;
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 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 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;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 94be52eaff1807c693ad53dc4c573528 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt(), m = scan.nextInt();
char[][] grid = scan.nextGrid(n, m);
int[] mx = new int[4]; //tblr
mx[0] = mx[2] = 0x3f3f3f3f;
int b = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == 'B') {
b++;
mx[0] = Math.min(mx[0], i);
mx[1] = Math.max(mx[1], i);
mx[2] = Math.min(mx[2], j);
mx[3] = Math.max(mx[3], j);
}
}
}
if(b == 0) {
out.println(1);
out.close();
return;
}
int id = mx[0]+n-mx[1]-1;
int jd = mx[2]+m-mx[3]-1;
int h = mx[1]-mx[0]+1;
int w = mx[3]-mx[2]+1;
int l = Math.max(h, w);
if(h+id < l || w+jd < l) out.println(-1);
else out.println(l*l-b);
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.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());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
public 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 double[] nextDoubleArray(int n){
double[] a = new double[n];
for(int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public char[][] nextGrid(int n, int m){
char[][] grid = new char[n][m];
for(int i = 0; i < n; i++) grid[i] = next().toCharArray();
return grid;
}
}
} | Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 78715bd6e7e989db4e00a956c9d6129d | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BlackSquare {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1[] = br.readLine().split(" ");
int row = Integer.parseInt(str1[0]);
int column = Integer.parseInt(str1[1]);
int iMin=10000, iMax=-10000, jMin=10000, jMax=-10000;
int totalBlack=0;
String str[] = new String[row];
for(int i=0; i<row; i++) {
str[i] = br.readLine();
}
for(int i=0; i<row; i++) {
for(int j=0; j<column; j++) {
if(str[i].charAt(j) == 'B') {
if(j > jMax)
jMax = j;
if(j < jMin)
jMin = j;
if(i > iMax)
iMax = i;
if(i < iMin)
iMin = i;
totalBlack++;
}
}
}//outer for loop
int rowBlack = iMax-iMin+1;
int columnBlack = jMax-jMin+1;
//System.out.println(iMin+" "+jMin+" "+iMax+" "+jMax);
if(rowBlack != columnBlack)
if(rowBlack > columnBlack)
columnBlack = rowBlack;
else
rowBlack = columnBlack;
long blackRequired = rowBlack*columnBlack-totalBlack;
if(rowBlack <= row && columnBlack <= column)
if(totalBlack != 0)
if(totalBlack == row*column)
System.out.println("0");
else
System.out.println(blackRequired);
else
System.out.println("1");
else
System.out.println("-1");
}//main
} | Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | d3744d1e20378f5777f9336fa60d263c | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author captainTurtle
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int a = in.nextInt();
int b = in.nextInt();
int y = a;
int Y = -1;
int x = b;
int X = -1;
int q = 0;
for (int r = 0; r < a; r++) {
String s = in.next();
for (int c = 0; c < b; c++) {
if (s.charAt(c) == 'B') {
y = Math.min(y, r);
Y = Math.max(Y, r);
x = Math.min(x, c);
X = Math.max(X, c);
q++;
}
}
}
int sq = Math.max(Y - y + 1, X - x + 1);
if (sq > a || sq > b) {
System.out.println(-1);
} else if (sq > 0) {
System.out.println((sq * sq) - q);
} else {
System.out.println(1);
}
}
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | b1b3a9f1da27d8122436933361653fe0 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author captainTurtle
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int a = in.nextInt();
int b = in.nextInt();
int y = a;
int Y = -1;
int x = b;
int X = -1;
int q = 0;
for (int r = 0; r < a; r++) {
String s = in.next();
for (int c = 0; c < b; c++) {
if (s.charAt(c) == 'B') {
y = Math.min(y, r);
Y = Math.max(Y, r);
x = Math.min(x, c);
X = Math.max(X, c);
q++;
}
}
}
int sq = Math.max(Y - y + 1, X - x + 1);
if (sq > a || sq > b) {
System.out.println(-1);
} else if (sq > 0) {
System.out.println((sq * sq) - q);
} else {
System.out.println(1);
}
}
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 8c929d4eddd50546ee9834c298a86efe | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.util.Scanner;
public class BlackSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
int m,n,bs=0;
Scanner in = new Scanner(System.in);
m = in.nextInt();
n = in.nextInt();
char [][]a = new char [m][n];
int []LFB = new int [m];
int []LLB = new int [m];
int []CFB = new int [n];
int []CLB = new int [n];
int LFBMIN=n;
int LLBMAX=0;
int CFBMIN=m;
int CLBMAX=0;
for(int i=0;i<m;i++)
{
String s = in.next();
for(int j=0;j<n;j++)
{
a[i][j]=s.charAt(j);
if(a[i][j]=='B')
bs++;
}
}
for(int i=0;i<m;i++)
{
LFB[i]=n;
for(int j=0;j<n;j++)
{
if(a[i][j]=='B')
{
LFB[i]=j;
break;
}
}
LFBMIN=(LFBMIN<LFB[i])?LFBMIN:LFB[i];
for(int j=n-1;j>=0;j--)
{
if(a[i][j]=='B')
{
LLB[i]=j;
break;
}
}
LLBMAX=(LLBMAX>LLB[i])?LLBMAX:LLB[i];
}
for(int j=0;j<n;j++)
{
CFB[j]=m;
for(int i=0;i<m;i++)
{
if(a[i][j]=='B')
{
CFB[j]=i;
break;
}
}
CFBMIN=(CFBMIN<CFB[j])?CFBMIN:CFB[j];
for(int i=m-1;i>=0;i--)
{
if(a[i][j]=='B')
{
CLB[j]=i;
break;
}
}
CLBMAX=(CLBMAX>CLB[j])?CLBMAX:CLB[j];
}
int LM=LLBMAX-LFBMIN+1;
int CM=CLBMAX-CFBMIN+1;
int MAX=0;
MAX=(LM>CM)?LM:CM;
if(bs==0)
System.out.println(1);
else
{
if(MAX<=m&&MAX<=n)
System.out.println(MAX*MAX-bs);
else
System.out.println(-1);
}
in.close();
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | c674fecb0cee9689cc64633d307b8f9b | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author coderfoces
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int count = 0;
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = in.next();
}
int mini = Integer.MAX_VALUE;
int minj = Integer.MAX_VALUE;
int maxi = 0;
int maxj = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (a[i].charAt(j) == 'B') {
mini = Math.min(mini, i);
minj = Math.min(minj, j);
maxi = Math.max(maxi, i);
maxj = Math.max(maxj, j);
count++;
}
}
}
int size = Math.max(maxj - minj + 1, maxi - mini + 1);
if (count == 0) {
out.println(1);
} else if (size > Math.min(n, m)) {
out.println(-1);
} else {
if (count == 1) {
out.println(0);
} else {
out.println(size * size - count);
}
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int 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 String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | d127a777c84216f84c17b4088601b501 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class B_423_1 {
InputStream is;
PrintWriter out;
int n;
long a[];
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void solve() {
int n = ni();
int m = ni();
int a[][] = new int[n + 1][m + 1];
int total = 0;
for (int i = 1; i <= n; i++) {
String s = ns();
for (int j = 1; j <= m; j++) {
if (s.charAt(j - 1) == 'B') {
a[i][j] = 1;
total++;
}
}
}
int min = Integer.MAX_VALUE;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
a[i][j] += a[i][j - 1];
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
a[j][i] += a[j - 1][i];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
for (int k = 0; i + k <= n && j + k <= m; k++) {
int t = a[i + k][j + k] - a[i + k][j - 1] - a[i - 1][j + k] + a[i - 1][j - 1];
if (t == total) {
min = Math.min(min, (k + 1) * (k + 1) - t);
}
}
}
}
if (min != Integer.MAX_VALUE)
out.println(min);
else
out.println(-1);
}
void run() throws Exception {
String INPUT = "C:\\Users\\Admin\\Desktop\\input.txt";
is = oj ? System.in : new FileInputStream(INPUT);
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new B_423_1().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 084e1df7045b086ee60b01f6345d345b | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
char[][] cc = new char[n][m];
for (int i = 0; i < n; i++)
br.readLine().getChars(0, m, cc[i], 0);
int imin = n, imax = -1, jmin = m, jmax = -1, cnt = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if(cc[i][j] == 'B'){
cnt++;
imin = Math.min(imin, i);
jmin = Math.min(jmin, j);
imax = Math.max(imax, i);
jmax = Math.max(jmax, j);
}
int ans;
if (cnt == 0){
ans = 1;
}else if ((imax - imin + 1) > m || (jmax - jmin + 1) > n){
ans = -1;
}else{
int a = Math.max(imax - imin + 1, jmax - jmin + 1);
ans = a*a - cnt;
}
System.out.println(ans);
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 4be130f28100d01334d568e3705ec3d3 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.*;
import java.util.*;
public class BB {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
char[][] cc = new char[n][m];
for (int i = 0; i < n; i++)
br.readLine().getChars(0, m, cc[i], 0);
int imin = n, imax = -1, jmin = m, jmax = -1, cnt = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (cc[i][j] == 'B') {
cnt++;
imin = Math.min(imin, i);
jmin = Math.min(jmin, j);
imax = Math.max(imax, i);
jmax = Math.max(jmax, j);
}
int ans;
if (cnt == 0)
ans = 1;
else if (imax - imin + 1 > m || jmax - jmin + 1 > n)
ans = -1;
else {
int a = Math.max(imax - imin + 1, jmax - jmin + 1);
ans = a * a - cnt;
}
System.out.println(ans);
}
} | Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | ece9f79a3c95d9d3c359d94a9356377c | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P828B {
public void run() throws Exception {
int n = nextInt(), m = nextInt(), t = 0;
int [][] f = new int [n + 1][m + 1];
for (int i = 1; i <= n; i++) {
String s = next();
for (int j = 1; j <= m; j++) {
int c = (s.charAt(j - 1) == 'B') ? 1 : 0;
t += c;
f[i][j] = c + f[i][j - 1];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; f[i][j] += f[i - 1][j], j++);
}
for (int s = 1; s <= Math.min(n, m); s++) {
for (int y = 0; y <= (n - s); y++) {
for (int x = 0; x <= (m - s); x++) {
int k = f[y + s][x + s] - f[y + s][x] - f[y][x + s] + f[y][x];
if (k == t) {
println(s * s - t);
return;
}
}
}
}
println(-1);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P828B().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
long gcd(long a, long b) {
if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a);
a = Math.abs(a); b = Math.abs(b);
int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b);
a >>>= az; b >>>= bz;
while (a != b) {
if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); }
else { b -= a; b >>>= Long.numberOfTrailingZeros(b); }
}
return (a << Math.min(az, bz));
}
} | Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | d8dd2d4978106de94edaf408ed9d8880 | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.util.*;
public class black
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int mini=n,maxi=0,minj=m,maxj=0,b=0;
for(int i=0;i<n;i++)
{
String s=sc.next();
for(int j=0;j<m;j++)
{
char ch=s.charAt(j);
if(ch=='B')
{
if(i<mini)
{
mini=i;
}
if(i>maxi)
{
maxi=i;
}
if(j<minj)
{
minj=j;
}
if(j>maxj)
{
maxj=j;
}
b++;
}
}
}
if(b>0)
{int r=maxi-mini+1;
int c=maxj-minj+1;
int s1=Math.max(r,c);
if(s1<=m&&s1<=n)
{
int ans=s1*s1-b;
System.out.println(ans);
}
else
{
System.out.println(-1);
}}
else
{
System.out.println(1);
}
}
} | Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output | |
PASSED | 4877bd31eafa1619c726c7d792ab8d5b | train_003.jsonl | 1499791500 | Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* 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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
in.nextLine();
char[][] grid = new char[n][m];
int count = 0;
int right = Integer.MIN_VALUE;
int left = Integer.MAX_VALUE;
int top = Integer.MAX_VALUE;
int bottom = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
String next = in.nextLine();
for (int j = 0; j < m; j++) {
grid[i][j] = next.charAt(j);
if (next.charAt(j) == 'B') {
count++;
left = Math.min(left, j);
right = Math.max(right, j);
top = Math.min(top, i);
bottom = Math.max(bottom, i);
}
}
}
if (count == 0)
out.print(1);
else {
int width = right - left + 1;
int height = bottom - top + 1;
int square = Math.max(width, height);
if (square > Math.min(n, m)) {
out.print(-1);
} else {
out.print(square * square - count);
}
}
}
}
}
| Java | ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"] | 1 second | ["5", "-1", "1"] | NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black. | Java 8 | standard input | [
"implementation"
] | cd6bc23ea61c43b38c537f9e04ad11a6 | The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white. | 1,300 | Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.