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 | 96e66d285b6c10853f4e7a8d7fe4b1fe | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main {
public static void main (String [] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s[] = br.readLine().split(" ");
int n = Integer.parseInt(s[0]);
byte k = Byte.parseByte(s[1]);
if(k>n || (k==1 && n>1))
System.out.print(-1);
else
if(k==1)
System.out.print('a');
else{
for(int i=1 ; i<=n-(k-2) ; i++)
if(i%2==0)
System.out.print('b');
else
System.out.print('a');
for(int i=0 ; i<(k-2) ; i++)
System.out.print((char)(99+i));
}
}
} | Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | 2380ce368ed270b3ab1f8fd074c9f4d8 | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes | import java.util.*;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.ArrayList;
public class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
// long sum = 0;
// for(int i = 0;i<n;i++)
// {
// int a = scan.nextInt();
// int b = scan.nextInt();
// sum+=(b-a)+1;
//
// }
// System.out.println(k-sum%k==k?0:k-sum%k);
StringBuilder sb = new StringBuilder("");
if(k==1&&n==1)
{
System.out.println('a');
return;
}
if(n<k||k==1)
{
System.out.print(-1);
return;
}
for(int i = 0;i<=n-k+1;i++)
{
if(i+1==(n-k+2))
sb.append("a");
else
{
sb.append("ab");
i++;
}
}
char g;
if(sb.length()==0)
g='a';
else
if(sb.length()==1)
g='b';
else
g='c';
int c = 0;
for(int i = 0;i<k-2;i++)
{
sb.append(g);
g++;
}
System.out.print(sb);
}
} | Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | 1a5f94bedc888fd59bf0993452ef674f | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes | import java.util.*;
import java.lang.StringBuilder;
public class PoloStringsWithStringBuilder
{
public static void main(String[] args)
{
// Set up scanner
Scanner sc = new Scanner(System.in);
// System.out.println("Input n");
int n = sc.nextInt();
// System.out.println("Input k");
int k = sc.nextInt();
if (k==1 && n==1)
{
System.out.println("a");
return;
}
if (k>n || k == 1)
{
System.out.println(-1);
return;
}
StringBuilder answer = new StringBuilder(100000);
int cyclenum = n - k + 2;
for (int i=0; i<cyclenum/4; i++)
{
answer.append("abab");
}
if (cyclenum % 4 == 3)
{
answer.append("aba");
}
else if (cyclenum % 4 == 2)
{
answer.append("ab");
}
else if (cyclenum % 4 == 1)
{
answer.append("a");
}
int rest = k-2;
if (rest <= 0)
{
System.out.println(answer);
return;
}
char ch = 'c';
for (int j=0; j<rest; j++)
{
answer.append(ch);
ch++;
}
System.out.println(answer.toString());
}
}
| Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | 2d16c7d5d668d3d800948da7e87c3981 | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes |
import java.io.*;
import java.util.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author N-AssassiN
*/
public class Main {
private static BufferedReader reader;
private static BufferedWriter out;
private static StringTokenizer tokenizer;
//private final static String filename = "filename";
/**
* call this method to initialize reader for InputStream and OututStream
*/
private static void init(InputStream input, OutputStream output) {
reader = new BufferedReader(new InputStreamReader(input));
out = new BufferedWriter(new OutputStreamWriter(output));
//reader = new BufferedReader(new FileReader(filename + ".in"));
//out = new BufferedWriter(new FileWriter(filename + ".out"));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
private static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
init(System.in, System.out);
int n = nextInt();
int k = nextInt();
if (n < k) {
System.out.println("-1");
} else if (k == 1) {
if (n == 1) {
out.write("a\n");
} else {
out.write("-1\n");
}
out.flush();
} else {
int flag = n - k + 2;
boolean odd = false;
for (int i = 0; i < flag; i++) {
if (odd) {
out.write("b");
odd = false;
} else {
out.write("a");
odd = true;
}
}
int count = 'c';
for (int i = flag; i < n; i++) {
out.write(((char) (count++)) + "");
}
out.write("\n");
out.flush();
}
}
} | Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | b793851a2eba71b3749cbc36f9262e62 | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes | import java.util.Scanner;
public class PoloString {
boolean[] charsUsed;
public static void main(String[] args) {
new PoloString().solve();
}
private void solve() {
charsUsed = new boolean[256];
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
System.out.print(findString(n, k));
}
/**
*
* @param n The length of the string
* @param k The number of unique characters
*/
private String findString(int n, int k) {
if (n < k) {
return "-1";
}
if (k == 1 && n > 1) {
return "-1";
}
int i = 0;
int length = 0;
StringBuilder s = new StringBuilder();
while (length < n) {
s.append((char)(i + 'a'));
length++;
// if cannot repeat characters anymore
if (n - length <= k - 1 ) {
i++;
}
else {
// swap between 0 and one
i ^= 1;
}
// special case for when switching between states
if (n - length == k && i == 1) {
s.append((char)(1 + 'a'));
s.append((char)(0 + 'a'));
length += 2;
i = 2;
}
}
return s.toString();
}
}
| Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | 4bad5b20e2749fc5b3c0387307087ce6 | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes | import java.util.Scanner;
public class ganaremos {
public static void main(String[] args) {
Scanner leer = new Scanner(System.in);
int x = leer.nextInt(),j = leer.nextInt(),i;
if(x < j || (x > 1 && j == 1)) {
System.out.println(-1);
return;
}
int[] s = new int[x];
for (i = 0; i < x; i++){
s[i] = i & 1;
}
int extra = j - 2;
for (i = 0; i < extra; i++){
s[x - extra + i] = i + 2;}
char[] ans = new char[x];
for (i = 0; i < x; i++){
ans[i] = (char) (s[i] + 'a');
}
System.out.println(new String(ans));
}
} | Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | 9e866478afbd77dc8ce30d0865163c99 | train_004.jsonl | 1364916600 | Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes. | 256 megabytes | import java.util.Scanner;
public class Code176Adiv1 {
public static void main(String[] args) {
int n,k;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
k = scanner.nextInt();
if((k>n) || (n!=1 && k==1)){
System.out.println("-1");
System.exit(0);
}
char[] alpha = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
if(n==k && n<=26){
for(int i=1;i<=n;i++)
System.out.print(alpha[i-1]);
}else{
k-=2;
for(int i=0;i<n-k;i++) System.out.print(alpha[i%2]);
for(int i=n-k,m=2;i<n;i++,m++) System.out.print(alpha[m]);
}
}
}
| Java | ["7 4", "4 7"] | 2 seconds | ["ababacd", "-1"] | null | Java 6 | standard input | [
"greedy"
] | 2f659be28674a81f58f5c587b6a0f465 | A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters. | 1,300 | In a single line print the required string. If there isn't such string, print "-1" (without the quotes). | standard output | |
PASSED | 5d50dae61a28a9d7fe1a82639484a8c1 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | //package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class CF_1196_Dq {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
while(q-->0) {
int n=sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
String rgb="RGB";
// int dp[][][]=new int[s.length()][3][k];
// for(int i[][]:dp) for(int j[]:i) Arrays.fill(j,-1);
// System.out.println(min(s,"RGB",0,0,0,k,dp));
int min=Integer.MAX_VALUE;
for(int i=0;i<=s.length()-k;++i) {
for(int j=0;j<rgb.length();++j) {
int count=0;
// int j2=j;
for(int kk=i,j2=j;kk<i+k;++kk,j2=(j2+1)%3) {
if(s.charAt(kk)!=rgb.charAt(j2)) {
count++;
}
// j2=(j2+1)%rgb.length();
}
min=Math.min(count,min);
}
}
System.out.println(min);
}
}
public static int min(String a, String b,int i, int j, int k, int k2, int dp[][][]) {
if(k==k2)
return 0;
if(i==a.length())
return 999999;
if(dp[i][j][k]!=-1)
return dp[i][j][k];
if(a.charAt(i)!=b.charAt(j)) {
return dp[i][j][k]=Math.min(min(a,b,i+1,j,0,k2,dp),Math.min(min(a,b,i,(j+1)%3,0,k2,dp),1+min(a,b,i+1,j,k+1,k2,dp)));
} else
return dp[i][j][k]=min(a,b,i+1,(j+1)%3,k+1,k2,dp);
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 28bf37500dba6370bd6c36262760af0e | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
for(int i=0;i<n;i++){
int x = 0;
int l = sc.nextInt();
int r = sc.nextInt();
String str = sc.nextToken();
String c1 = gen1(l);
String c2 = gen2(l);
String c3 = gen3(l);
int tm1 = check(str.substring(0,r),c1);
int tm2 = check(str.substring(0,r),c2);
int tm3 = check(str.substring(0,r),c3);
x=min(tm1,tm2,tm3,Integer.MAX_VALUE);
for(int f=0,j=r;j<l;j++,f++){
char re = str.charAt(f);
char one=c1.charAt(f);
char two=c2.charAt(f);
char thr=c3.charAt(f);
tm1-=(re!=one?1:0);
tm2-=(re!=two?1:0);
tm3-=(re!=thr?1:0);
re = str.charAt(j);
one=c1.charAt(j);
two=c2.charAt(j);
thr=c3.charAt(j);
tm1+=(re!=one?1:0);
tm2+=(re!=two?1:0);
tm3+=(re!=thr?1:0);
x=min(tm1,tm2,tm3,x);
}
pw.println(x);
}
pw.close();
}
static int min(int a,int b, int c,int d){
if(d<a&&d<b&&d<c)
return d;
else if(a<b&&a<c){
return a;
}
else if(b<c)return b;
return c;
}
static int check(String str, String str1){
int ct=0;
for(int i =0;i<str.length();i++){
if(str.charAt(i)!=str1.charAt(i))ct++;
}
return ct;
}
static String gen1(int len){
StringBuilder s = new StringBuilder();
for(int i=0;i<len;i++){
if(i%3==0){
s.append("R");
}
if(i%3==1){
s.append("G");
}
if(i%3==2){
s.append("B");
}
}
return s.toString();
}
static String gen2(int len){
StringBuilder s = new StringBuilder();
for(int i=0;i<len;i++){
if(i%3==0){
s.append("G");
}
if(i%3==1){
s.append("B");
}
if(i%3==2){
s.append("R");
}
}
return s.toString();
}
static String gen3(int len){
StringBuilder s = new StringBuilder();
for(int i=0;i<len;i++){
if(i%3==0){
s.append("B");
}
if(i%3==1){
s.append("R");
}
if(i%3==2){
s.append("G");
}
}
return s.toString();
}
}
@SuppressWarnings("all")
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 69b852b21e9ae057668c561a5b9014c9 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class Solution {
static class Node{
int R,G,B;
Node(){
this(0,0,0);
}
Node(int r,int g,int b){
this.R = r;
this.G = g;
this.B = b;
}
void addition(Node node){
this.R+=node.R;
this.G+=node.G;
this.B+=node.B;
}
Node subtraction(Node node){
return new Node(this.R-node.R,this.G-node.G,this.B-node.B);
}
void init(char c){
this.R = c=='R'?1:0;
this.G = c=='G'?1:0;
this.B = c=='B'?1:0;
}
int getRGB(int i){
if(i==0)return this.R;
else if(i==1)return this.G;
else if(i==2)return this.B;
return -1;
}
}
public static void main(String []args){
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int q = in.nextInt();
int n,k;
Node []nodes = new Node[2000+5];
for(int i=0;i<nodes.length;i++){
nodes[i] = new Node();
}
int a,b,c;
char []chars = new char[2000+5];
while(q--!=0){
n = in.nextInt();k=in.nextInt();
String s = in.nextLine();
chars = in.nextLine().toCharArray();
for(int i=0;i<Math.min(3,n);i++){
nodes[i].init(chars[i]);
}
for(int i=3;i<n;i++){
nodes[i].init(chars[i]);
nodes[i].addition(nodes[i-3]);
}
int result = Integer.MAX_VALUE;
for(int i=0;i+k-1<n;i++){
int end = i+k-1;
a = 0;b=0;c=0;
for(int j=0;j<Math.min(k,3);j++){
int len = (end-j-i)/3 + 1;
Node temp = null;
if(end-j-3*len<0){
temp = nodes[end-j];
}else{
temp = nodes[end-j].subtraction(nodes[end-j-3*len]);
}
a += temp.getRGB((end-j-i)%3);
b += temp.getRGB((end-j-i+1)%3);
c += temp.getRGB((end-j-i+2)%3);
}
result = Math.min(result,Math.min(k-a,Math.min(k-b,k-c)));
if(result==0){
break;
}
}
out.println(result);
}
out.close();
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 339bb147becc0501918338eb63730cc1 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class RGBSubstring {
private static void solve(int K, String N)
{
String rgb = "RGB";
int min = K;
for (int i = 0; i < N.length() - K + 1; i++)
{
for (int index = 0; index < 3; index++) {
int hold = index;
int changes = 0;
for (int j = i; j < K + i; j++) {
if (changes > min) {break;}
if (N.charAt(j) != rgb.charAt(index)) {
changes++;
}
index++;
index = index % 3;
}
index = hold;
if (changes < min) {
min = changes;
}
}
}
System.out.println(min);
}
public static void main(String[] args) throws IOException {
int Q = nextInt();
for (int i = 0; i < Q; i++){
int L = nextInt(); int K = nextInt();
String N = nextString();
solve(K, N);
}
}
private static StringTokenizer line = new StringTokenizer("");
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
private static String nextString() throws IOException
{
if (line.hasMoreTokens())
{
return line.nextToken();
} else {
line = new StringTokenizer(in.readLine());
return line.nextToken();
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 0139e65866bd13f5ee8bf962763b01d1 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class NewClass3 {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++){
int n,k;
n=sc.nextInt();
k=sc.nextInt();
String s=sc.next();
int min=k;
for(int j=0;j<n-k+1;j++){
String temp=s.substring(j,j+k);
char ch[]={'R','G','B'};
int t1=0;
for(int y=0;y<3;y++){
t1=y;
int sum=0;
for(int w=0; w<temp.length();w++){
if(ch[t1%3]!=temp.charAt(w)){
sum++;
}
t1++;
}
if(sum<min){
min=sum;
}
}
}
System.out.println(min);
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 4455f9766fa564e7d3b5d234cd5defd2 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | /* MOHD SADIQ */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static long parseLong(String s) {
s = s.trim();
return Long.parseLong(s);
}
public static int parseInt(String s) {
s = s.trim();
return Integer.parseInt(s);
}
public static int[] intArray(String t) {
String[] s = t.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;
}
public static long[] longArray(String t) {
String[] s = t.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;
}
public static String solve() throws IOException {
int[] tt = intArray(br.readLine());
int n = tt[0], k = tt[1];
String s = br.readLine().trim();
char[] c = s.toCharArray();
char[] pat = {'R', 'G', 'B'};
int max = 0;
for (int i = 0; i < n; i++) {
int ind;
if (c[i] == 'R')
ind = 0;
else if (c[i] == 'G')
ind = 1;
else ind = 2;
int count = 0;
for (int j = i; j < n && j < i + k; j++) {
if (c[j] == pat[ind]) {
count++;
}
ind = (ind + 1) % 3;
}
max = Math.max(count, max);
}
if (max >= k)
return String.valueOf(0);
else return String.valueOf(k-max);
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
int total_test_case =Integer.parseInt(br.readLine().trim());
StringBuffer ans = new StringBuffer();
for(int test_case =0;test_case<total_test_case;test_case++){
ans.append(solve()+"\n");
}
System.out.print(ans);
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | b4826c2dc2a2b07f1f09bc3d334a781d | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | //TEMPLATE
import java.util.*;
import java.math.*;
public class Main {
static Scanner scan;
public static void println(Object s){System.out.println(s);}
public static void print(Object s){System.out.print(s);}
public static int nextInt(){return scan.nextInt();}
public static int nextIntL(){int i = scan.nextInt(); scan.nextLine(); return i;}
public static String nextLine(){return scan.nextLine();}
public static void main(String[] args) {scan = new Scanner(System.in);solution();}
//Solution goes below:
public static void solution(){
int q = nextIntL();
String rgb = "RGB";
for(int i = 0; i<q;i++){
int which; //debug
int n = nextInt();
int k = nextInt();
nextLine();
char[] s = nextLine().toCharArray();
int[] startsums = new int[3];
int max = 0;
for(int j =0; j<k;j++){
//print("asdf");
startsums[(rgb.indexOf(s[j])+(-j)%3+3)%3]++;
}
for(int a=0;a<3;a++){
if(startsums[a]>max){
max = startsums[a];
//println(a);
}
}
for(int j = k; j<n; j++){
//print("asdf");
startsums[(rgb.indexOf(s[j])+(-j)%3+3)%3]++;
startsums[(rgb.indexOf(s[j-k])+(k-j)%3+3)%3]--;
for(int a=0;a<3;a++){
if(startsums[a]>max){
max = startsums[a];
//println(a);
}
}
}
println(k-max);
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | a16b5e2871f9dcacc5b11f4d33096ba5 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | //TEMPLATE
import java.util.*;
import java.math.*;
public class Main {
static Scanner scan;
public static void println(Object s){System.out.println(s);}
public static void print(Object s){System.out.print(s);}
public static int nextInt(){return scan.nextInt();}
public static int nextIntL(){int i = scan.nextInt(); scan.nextLine(); return i;}
public static String nextLine(){return scan.nextLine();}
public static void main(String[] args) {scan = new Scanner(System.in);solution();}
//Solution goes below:
public static void solution(){
int q = nextIntL();
String rgb = "RGB";
int n;
int k;
char[] s;
int[] startsums;
int max;
for(int i = 0; i<q;i++){
n = nextInt();
k = nextInt();
nextLine();
s = nextLine().toCharArray();
startsums = new int[3];
max = 0;
for(int j =0; j<k;j++){
//print("asdf");
startsums[(rgb.indexOf(s[j])+(-j)%3+3)%3]++;
}
for(int a=0;a<3;a++){
if(startsums[a]>max){
max = startsums[a];
//println(a);
}
}
for(int j = k; j<n; j++){
//print("asdf");
startsums[(rgb.indexOf(s[j])+(-j)%3+3)%3]++;
startsums[(rgb.indexOf(s[j-k])+(k-j)%3+3)%3]--;
for(int a=0;a<3;a++){
if(startsums[a]>max){
max = startsums[a];
}
}
}
println(k-max);
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | e3a36694fc3db295d4e649b531427ad0 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.File;
import java.util.Scanner;
import java.util.StringTokenizer;
public class p048 {
public static void main(String args[]) throws Exception {
// StringTokenizer stok = new StringTokenizer(new Scanner(new File("C:/Users/Arunkumar/Downloads/input.txt")).useDelimiter("\\A").next());
StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next());
StringBuilder sb = new StringBuilder();
int q = Integer.parseInt(stok.nextToken());
while(q-->0) {
int n = Integer.parseInt(stok.nextToken());
int k = Integer.parseInt(stok.nextToken());
int min = Integer.MAX_VALUE;
char[] s = stok.nextToken().toCharArray();
min = Math.min(dos(s,n,k,0), Math.min(dos(s,n,k,1),dos(s,n,k,2)));
sb.append(min+" ");
}
System.out.println(sb);
}
private static int dos(char[] s, int n, int k, int id) {
char[] t = "RGB".toCharArray();
int[] d = new int[n+1];
int i=0;
int ret = Integer.MAX_VALUE;
while(++i<=n) {
d[i]+=d[i-1];
if(s[i-1]!=t[(i+id)%3])d[i]++;
if(i>=k) ret = Math.min(ret, d[i]-d[i-k]);
}
return ret;
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 708c4860c44c1684ed1374c1fc258f1b | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class RGBSubstring {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class TaskA {
long mod = (long)(1000000007);
public void solve(int testNumber, InputReader in, PrintWriter out) {
while(testNumber-->0){
int n = in.nextInt();
int k = in.nextInt();
String s = in.next();
// String b[] = new String[3];
// b[0] = "";
// b[1] = "";
// b[2] = "";
// int x = n/3;
// int y = n%3;
// b[0] += "RGB";
// b[1] += "GBR";
// b[2] += "BRG";
// if(y!=0){
// b[0] += "RGB".substring(0 , y);
// b[1] += "GBR".substring(0 , y);
// b[2] += "BRG".substring(0 , y);
// }
int a[][] = new int[3][n+1];
for(int i=0;i<n;i++){
int j = i%3;
String b = "";
if(j == 0)
b = "RGB";
else if(j==1)
b = "GBR";
else
b = "BRG";
if(s.charAt(i) == b.charAt(0)){
a[0][i+1] = 1;
continue;
}
else if(s.charAt(i) == b.charAt(1)){
a[1][i+1] = 1;
continue;
}
else
a[2][i+1] = 1;
}
for(int i=1;i<=n;i++)
for(int j=0;j<3;j++)
a[j][i] += a[j][i-1];
int max = Integer.MIN_VALUE;
for(int i=0;i<3;i++){
for(int j=k;j<=n;j++)
max = Math.max(max , a[i][j] - a[i][j-k]);
}
out.println(k - max);
}
}
class Combine{
int value;
int delete;
Combine(int val , int delete){
this.value = val;
this.delete = delete;
}
}
class Sort2 implements Comparator<Combine>{
public int compare(Combine a , Combine b){
if(a.value > b.value)
return 1;
else if(a.value == b.value && a.delete>b.delete)
return 1;
else if(a.value == b.value && a.delete == b.delete)
return 0;
return -1;
}
}
public int lowerBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>=x)
return -1;
if(a.get(r)<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid-1)<x)
return mid-1;
else if(a.get(mid)>=x)
r = mid-1;
else if(a.get(mid)<x && a.get(mid+1)>=x)
return mid;
else if(a.get(mid)<x && a.get(mid+1)<x)
l = mid+1;
}
return mid;
}
public int upperBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>x)
return l;
if(a.get(r)<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid+1)>x)
return mid+1;
else if(a.get(mid)<=x)
l = mid+1;
else if(a.get(mid)>x && a.get(mid-1)<=x)
return mid;
else if(a.get(mid)>x && a.get(mid-1)>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.floor((Math.log(number) / Math.log(base)));
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
if(a%b==0)
return b;
return gcd(b , a%b);
}
public void print2d(int a[][] , PrintWriter out){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
out.print(a[i][j] + " ");
out.println();
}
out.println();
}
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
out.println();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 247e342a26ff8c1e1104f3019442eab0 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-->0){
String[] ar = br.readLine().split(" ");
int n = Integer.parseInt(ar[0]);
int k = Integer.parseInt(ar[1]);
String s = br.readLine();
String uni = "RGB";
String r = "";
String g = "";
String b = "";
int f = 0;
int j = 1;
int m =2;
for(int i=0; i<k; i++){
r = r+uni.charAt(f);
g = g+uni.charAt(j);
b = b+uni.charAt(m);
if(f==2){
f=0;
}else{
f++;
}
if(j==2){
j=0;
}else{
j++;
}
if(m==2){
m=0;
}else{
m++;
}
}
int min = Integer.MAX_VALUE;
for(int i=0; i<=n-k; i++){
int count1 = 0;
int count2 =0;
int count3 =0;
int v =0;
for(int p=i; p<k+i; p++){
if(s.charAt(p)!=r.charAt(v)){
count1++;
}
if(s.charAt(p)!=g.charAt(v)){
count2++;
}
if(s.charAt(p)!=b.charAt(v)){
count3++;
}
v++;
}
min = Math.min(min, count1);
min = Math.min(min, count2);
min = Math.min(min, count3);
}
System.out.println(min);
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 510f0b0cfa77a2077568297b7922f66d | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | // This template code suggested by KT BYTE Computer Science Academy
// for use in reading and writing files for USACO problems.
// https://content.ktbyte.com/problem.java
import java.util.*;
import java.io.*;
public class RGBSubstring {
static StreamTokenizer in;
static int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
static String next() throws IOException {
in.nextToken();
return in.sval;
}
static int n;
static int k;
static char[] charList;
static int[] initial_counts;
public static void main(String[] args) throws Exception {
in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int q = nextInt();
for (int i = 0; i < q; i++) {
n = nextInt();
k = nextInt();
String string = next();
charList = string.toCharArray();
// initial counts for RGB, GBR, BRG
initial_counts = new int[3];
initialization();
int result = Integer.MAX_VALUE;
int cur = Math.min(Math.min(initial_counts[0], initial_counts[1]), initial_counts[2]);
result = Math.min(result, cur);
for (int j = 1; j <= n - k; j++) {
int indexToRemove = j-1;
int indexToAdd = j+k-1;
edit(indexToRemove, indexToAdd);
cur = Math.min(Math.min(initial_counts[0], initial_counts[1]), initial_counts[2]);
result = Math.min(result, cur);
}
out.println(result);
}
out.close();
}
static void remove(int indexToRemove) {
char remove = charList[indexToRemove];
int mod = indexToRemove % 3;
if (remove == 'R') {
if (mod == 0) {
initial_counts[1]--;
initial_counts[2]--;
}
else if (mod == 1) {
initial_counts[0]--;
initial_counts[1]--;
}
else {
initial_counts[0]--;
initial_counts[2]--;
}
}
else if (remove == 'G') {
if (mod == 0) {
initial_counts[0]--;
initial_counts[2]--;
}
else if (mod == 1) {
initial_counts[1]--;
initial_counts[2]--;
}
else {
initial_counts[0]--;
initial_counts[1]--;
}
}
else {
if (mod == 0) {
initial_counts[0]--;
initial_counts[1]--;
}
else if (mod == 1) {
initial_counts[0]--;
initial_counts[2]--;
}
else {
initial_counts[1]--;
initial_counts[2]--;
}
}
}
static void add(int indexToAdd) {
char add = charList[indexToAdd];
int mod = indexToAdd % 3;
if (mod == 0) {
if (add == 'R') {
initial_counts[1]++;
initial_counts[2]++;
}
else if (add == 'G') {
initial_counts[0]++;
initial_counts[2]++;
}
else {
initial_counts[0]++;
initial_counts[1]++;
}
}
else if (mod == 1) {
if (add == 'R') {
initial_counts[0]++;
initial_counts[1]++;
}
else if (add == 'G') {
initial_counts[1]++;
initial_counts[2]++;
}
else {
initial_counts[0]++;
initial_counts[2]++;
}
}
else {
if (add == 'R') {
initial_counts[0]++;
initial_counts[2]++;
}
else if (add == 'G') {
initial_counts[0]++;
initial_counts[1]++;
}
else {
initial_counts[1]++;
initial_counts[2]++;
}
}
}
static void edit(int indexToRemove, int indexToAdd) {
remove(indexToRemove);
add(indexToAdd);
}
static void initialization() {
for (int j = 0; j < k; j++) {
if (charList[j] == 'R') {
if (j % 3 == 0) {
initial_counts[1]++;
initial_counts[2]++;
}
else if (j % 3 == 1){
initial_counts[0]++;
initial_counts[1]++;
}
else {
initial_counts[0]++;
initial_counts[2]++;
}
}
else if (charList[j] == 'G') {
if (j % 3 == 0) {
initial_counts[0]++;
initial_counts[2]++;
}
else if (j % 3 == 1){
initial_counts[1]++;
initial_counts[2]++;
}
else {
initial_counts[0]++;
initial_counts[1]++;
}
}
else {
if (j % 3 == 0) {
initial_counts[0]++;
initial_counts[1]++;
}
else if (j % 3 == 1){
initial_counts[0]++;
initial_counts[2]++;
}
else {
initial_counts[1]++;
initial_counts[2]++;
}
}
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | a4655557886c94a04093e57fe2c912af | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class substring{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int q=s.nextInt();
while(q>0){
int n=s.nextInt();
int k=s.nextInt();
s.nextLine();
String str=s.nextLine();
String str1="RGB";
String str2="GBR";
String str3="BRG";
for(int m=0;m<(k/3);m++){
str1=str1+"RGB";
str2=str2+"GBR";
str3=str3+"BRG";
}
int min=k+1;
for(int i=0;i<=n-k;i++){
int c1=0,c2=0,c3=0;
for(int j=i,l=0;l<k;j++,l++){
if(str1.charAt(l)!=str.charAt(j)){
c1++;
}
if(str2.charAt(l)!=str.charAt(j)){
c2++;
}
if(str3.charAt(l)!=str.charAt(j)){
c3++;
}
}
int least=(c1<c2&&c1<c3)?c1:(c2<c3?c2:c3);
if(min>least){
min=least;
}
}
System.out.println(min);
q--;
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 4b1df04ba9a3a0bd6aeb5822234f9d4e | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 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.
*/
//package d2.rgb.substring.hard.version;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
/**
*
* @author edwardxiao
*/
public class D2RGBSubstringHardVersion {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int q = readInt();
for (; q > 0; q--) {
int n = readInt(), k = readInt();
char[] a = read().toCharArray();
int[] c1 = new int[n]; // each c stores 1 if corect, 0 if not correct; c1 starts r, g, b, respectively
int[] c2 = new int[n];
int[] c3 = new int[n];
//System.out.println(Arrays.toString(a));
Deque<Integer> q1 = new LinkedList<>();
Deque<Integer> q2 = new LinkedList<>();
Deque<Integer> q3 = new LinkedList<>();
int cnt1 = 0, cnt2 = 0, cnt3 = 0, max1 = 0, max2 = 0, max3 = 0;
for (int i = 0; i < n; i++) {
if (i % 3 == 0) {
if (a[i] == 'R') {
c1[i]++;
} else if (a[i] == 'G') {
c2[i]++;
} else {
c3[i]++;
}
} else if (i % 3 == 1) {
if (a[i] == 'G') {
c1[i]++;
} else if (a[i] == 'B') {
c2[i]++;
} else {
c3[i]++;
}
} else {
if (a[i] == 'B') {
c1[i]++;
} else if (a[i] == 'R') {
c2[i]++;
} else {
c3[i]++;
}
}
if (c1[i] > 0) {
cnt1++;
}
q1.add(c1[i]);
if (c2[i] > 0) {
cnt2++;
}
q2.add(c2[i]);
if (c3[i] > 0) {
cnt3++;
}
q3.add(c3[i]);
if (q1.size() > k) {
if (q1.pollFirst() > 0) {
cnt1--;
}
}
if (q2.size() > k) {
if (q2.pollFirst() > 0) {
cnt2--;
}
}
if (q3.size() > k) {
if (q3.pollFirst() > 0) {
cnt3--;
}
}
max1 = Math.max(max1, cnt1);
max2 = Math.max(max2, cnt2);
max3 = Math.max(max3, cnt3);
//System.out.println(q1);
//System.out.println(q2);
//System.out.println(q3);
}
//System.out.println(Arrays.toString(c1));
//System.out.println(Arrays.toString(c2));
//System.out.println(Arrays.toString(c3));
println(Math.min(Math.min(k - max1, k - max2), k - max3));
}
}
final private static int BUFFER_SIZE = 1 << 16;
private static DataInputStream din = new DataInputStream(System.in);
private static byte[] buffer = new byte[BUFFER_SIZE];
private static int bufferPointer = 0, bytesRead = 0;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static 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 static String read() throws IOException {
byte[] ret = new byte[1000000];
int idx = 0;
byte c = Read();
while (c <= ' ') {
c = Read();
}
do {
ret[idx++] = c;
c = Read();
} while (c != -1 && c != ' ' && c != '\n' && c != '\r');
return new String(ret, 0, idx);
}
public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private static byte Read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) {
return;
}
din.close();
}
static void print(Object o) {
System.out.print(o);
}
static void println(Object o) {
System.out.println(o);
}
static void flush() {
System.out.flush();
}
static void println() {
System.out.println();
}
static void exit() throws IOException {
din.close();
pr.close();
System.exit(0);
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 112f7985e4ba587c8b8bed90f69d9880 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import javax.print.DocFlavor;
import java.awt.*;
import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
public class Main {
static class pair {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static long pow(long a, int e) {
long res = 1;
while (e > 0) {
res *= a;
e--;
}
return res;
}
static char next(char c) {
if (c == 'R')
return 'G';
if (c == 'G')
return 'B';
return 'R';
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter out = new PrintWriter(System.out);
int q = Integer.parseInt(br.readLine());
int[] movex = {-1, 0, 1, 0};
int[] movey = {0, 1, 0, -1};
// System.out.print(Math.ceil(1.0));
for (int i = 0; i < q; i++) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
char[] R =new char[k];
char[] G =new char[k];
char[] B =new char[k];
R[0]='R';
G[0]='G';
B[0]='B';
for (int j = 1; j < k; j++) {
R[j] = next(R[j - 1]);
G[j] = next(G[j - 1]);
B[j] = next(B[j - 1]);
}
char[] c = new char[n];
String s = br.readLine();
for (int j = 0; j < n; j++) {
c[j] = s.charAt(j);
}
if (k == 1)
out.println(0);
else {
int beg = 0;
int end = k - 1;
int min = n + 1;
int ans = 0;
int ans2,ans3;ans2=ans3=0;
while (end < n) {
for (int j = beg; j <= end; j++) {
if(c[j]!=R[j-beg]){
ans++;
}
if(c[j]!=G[j-beg]){
ans2++;
}
if(c[j]!=B[j-beg]){
ans3++;
}
}
ans=Math.min(ans,ans2);
ans=Math.min(ans,ans3);
min = Math.min(min, ans);
if (min == 0)
break;
beg++;
end++;
ans =ans2=ans3= 0;
}
out.println(min);
}
}
out.flush();
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 355b71f0c28e14505c967928e6e7cc83 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class cf575 {
public void robot()throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
line = br.readLine();
String[] str= line.split(" ");
int q = Integer.parseInt(str[0]);
for (int iq=0;iq<q;iq++){
line = br.readLine();
str = line.split(" ");
int n = Integer.parseInt(str[0]);
int k = Integer.parseInt(str[1]);
String s = br.readLine();
int[] a = new int[n];
int[] b = new int[n];
int[] c = new int[n];
for(int i=0;i<n;i++){
if(i%3==2){
if(s.charAt(i)!='B'){
a[i]=1;
}
}
else if(i%3==1){
if(s.charAt(i)!='G'){
a[i]=1;
}
}
else if(i%3==0){
if(s.charAt(i)!='R'){
a[i]=1;
}
}
}
for(int i=0;i<n;i++){
if(i%3==2){
if(s.charAt(i)!='R'){
b[i]=1;
}
}
else if(i%3==1){
if(s.charAt(i)!='B'){
b[i]=1;
}
}
else if(i%3==0){
if(s.charAt(i)!='G'){
b[i]=1;
}
}
}
for(int i=0;i<n;i++){
if(i%3==2){
if(s.charAt(i)!='G'){
c[i]=1;
}
}
else if(i%3==1){
if(s.charAt(i)!='R'){
c[i]=1;
}
}
else if(i%3==0){
if(s.charAt(i)!='B'){
c[i]=1;
}
}
}
int ans = 2000;
int t1=0,t2=0,t3=0;
for(int i=0;i<k;i++){
t1+=a[i];
t2+=b[i];
t3+=c[i];
}
ans=Math.min(t1,Math.min(t2,t3));
int index=0;
// System.out.println("t2: "+t2);
for(int i=k;i<n;i++){
t1-=a[index];
t2-=b[index];
t3-=c[index];
index++;
t1+=a[i];
t2+=b[i];
t3+=c[i];
// System.out.println("t2: "+t2);
int temp=Math.min(t1,Math.min(t2,t3));
ans = Math.min(temp,ans);
}
// System.out.println(a[0]+" " + a[1]+" "+a[2]+" "+a[3]+" "+a[4]);
// System.out.println(b[0]+" " + b[1]+" "+b[2]+" "+b[3]+" "+b[4]);
// System.out.println(c[0]+" " + c[1]+" "+c[2]+" "+c[3]+" "+c[4]);
System.out.println(ans);
}
}
public static void main(String[] args) throws IOException {
cf575 c = new cf575();
c.robot();
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// String line;
// line = br.readLine();
// String[] str= line.split(" ");
// int q = Integer.parseInt(str[0]);
// for (int iq=0;iq<q;iq++){
// line = br.readLine();
// str = line.split(" ");
// int n = Integer.parseInt(str[0]);
// int k = Integer.parseInt(str[1]);
// String s = br.readLine();
// int ans = Integer.MAX_VALUE;
// for(int i=0;i<=n-k;i++){
// int temp=0;
// if(s.charAt(i)=='R'){
// for(int j=i;j<i+k;j++){
// if((j-i)%3==2){
// if(s.charAt(j)!='B'){
// temp++;
// }
// }
// else if((j-i)%3==1){
// if(s.charAt(j)!='G'){
// temp++;
// }
// }
// else if(s.charAt(j)!='R'){
// temp++;
// }
// }
// }
// else if(s.charAt(i)=='G'){
// for(int j=i;j<i+k;j++){
// if((j-i)%3==2){
// if(s.charAt(j)!='R'){
// temp++;
// }
// }
// else if((j-i)%3==1){
// if(s.charAt(j)!='B'){
// temp++;
// }
// }
// else if(s.charAt(j)!='G'){
// temp++;
// }
// }
// }
// else{
// for(int j=i;j<i+k;j++){
// if((j-i)%3==2){
// if(s.charAt(j)!='G'){
// temp++;
// }
// }
// else if((j-i)%3==1){
// if(s.charAt(j)!='R'){
// temp++;
// }
// }
// else if(s.charAt(j)!='B'){
// temp++;
// }
// }
// }
// if(temp<ans) ans=temp;
// }
// System.out.println(ans);
// }
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 1d4307722e772e0f1924068293b3d89b | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static HashMap<Character, Character> next = new HashMap<>();
public static void main(String[] args) {
next.put('R', 'G');
next.put('G', 'B');
next.put('B', 'R');
Scanner scanner = new Scanner(System.in);
long q = scanner.nextLong();
for (int i = 0; i < q; i++) {
int n = scanner.nextInt(), k = scanner.nextInt();
String s = scanner.next();
int minChange = n;
for (int j = 0; j < s.length() - k + 1; j++) {
char[] c = {'R', 'G', 'B'};
int[] change = {0, 0, 0};
for (int l = 0; l < 3; l++)
if (s.charAt(j) != c[l])change[l]++;
for (int l = j; l < j + k - 1; l++) {
for (int m = 0; m < 3; m++) {
if (s.charAt(l + 1) != next.get(c[m])){
change[m]++;
}
c[m] = next.get(c[m]);
}
}
for (int m = 0; m < 3; m++)
minChange = Math.min(minChange, change[m]);
}
System.out.println(minChange);
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 59bdfa1df7c53b4b2220e86e0c12a623 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class D1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
sc.nextLine();
for(int qq=0;qq<q;qq++) {
int n = sc.nextInt();
int k = sc.nextInt();
sc.nextLine();
String word = sc.nextLine();
String str ="RGB";
int minChanges=Integer.MAX_VALUE;
for(int i=0;i<=n-k;i++) {
String currWord = word.substring(i,i+k);
for (int pos=0; pos<3; pos++) {
int numChanges=0;
for(int j=0; j<k; j++) {
int currPos = (j+pos)%3;
if(currWord.charAt(j)!=str.charAt(currPos)) {
numChanges++;
}
}
if(numChanges<minChanges) {
minChanges=numChanges;
}
}
}
System.out.println(minChanges);
}
sc.close();
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | bacb0fe57eabee6c99efb8be2da58647 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t-->0)
{
String s[]=(br.readLine()).split(" ");
int n=Integer.parseInt(s[0]);
int k=Integer.parseInt(s[1]);
char ch[]=(br.readLine()).toCharArray();
int ar[]=new int[n];
for(int i=0;i<n;i++)
{
if(ch[i]=='R')
{
ar[i]=0;
}
else if(ch[i]=='G')
{
ar[i]=1;
}
else
{
ar[i]=2;
}
}
int mat[][]=new int[3][3];
mat[0][1]=2;
mat[0][2]=1;
mat[1][0]=1;
mat[1][2]=2;
mat[2][0]=2;
mat[2][1]=1;
boolean pos[][]=new boolean[3][n];
for(int i=0;i<n;i++)
{
pos[mat[ar[i]][i%3]][i]=true;
}
int ct=0;
for(int i=0;i<k;i++)
{
if(pos[0][i]==true)
{
ct++;
}
}
int max=ct;
int p1=1;
int p2=p1+k-1;
for(int i=1;i<=n-k;i++)
{
if(pos[0][p1-1])
{
ct--;
}
if(pos[0][p2])
{
ct++;
}
if(ct>max)
{
max=ct;
}
p1++;
p2++;
}
p1=1;
p2=p1+k-1;
ct=0;
for(int i=0;i<k;i++)
{
if(pos[1][i]==true)
{
ct++;
}
}
if(ct>max)
{
max=ct;
}
for(int i=1;i<=n-k;i++)
{
if(pos[1][p1-1])
{
ct--;
}
if(pos[1][p2])
{
ct++;
}
if(ct>max)
{
max=ct;
}
p1++;
p2++;
}
p1=1;
p2=p1+k-1;
ct=0;
for(int i=0;i<k;i++)
{
if(pos[2][i]==true)
{
ct++;
}
}
if(ct>max)
{
max=ct;
}
for(int i=1;i<=n-k;i++)
{
if(pos[2][p1-1])
{
ct--;
}
if(pos[2][p2])
{
ct++;
}
if(ct>max)
{
max=ct;
}
p1++;
p2++;
}
pw.println(k-max);
}
pw.flush();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | c1e4d27eace271d4562c73a1fe1a97a5 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.InputMismatchException;
public class D575 {
public static int ans(int[] arr, int N, int K) {
int min = Integer.MAX_VALUE;
for(int t = 0; t < 3; t++) {
int start = 0;
int end = 0;
int temp = 0;
boolean[] error = new boolean[N];
while(end < K) {
if(arr[end] != (t+end) % 3) {
temp++;
error[end] = true;
}
end++;
}
min = Math.min(temp, min);
while(end < N) {
if(error[start]) {
temp--;
}
start++;
if(arr[end] != (t+end) % 3) {
temp++;
error[end] = true;
}
end++;
min = Math.min(temp, min);
}
}
return min;
}
public static void main(String[] args) {
FastScanner in = new FastScanner(System.in);
int Q = in.nextInt();
StringBuilder sb = new StringBuilder();
HashMap<Character, Integer> map = new HashMap<>();
map.put('R', 0);
map.put('G', 1);
map.put('B', 2);
while(Q --> 0) {
int N = in.nextInt();
int K = in.nextInt();
String g = in.next();
int[] arr = new int[N];
for(int i = 0; i < arr.length; i++) {
char c = g.charAt(i);
arr[i] = map.get(c);
}
int result = ans(arr, N, K);
sb.append(result);
sb.append("\n");
}
System.out.print(sb);
}
/**
* Source: Matt Fontaine
*/
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int chars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
int read() {
if (chars == -1)
throw new InputMismatchException();
if (curChar >= chars) {
curChar = 0;
try {
chars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (chars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
/*
3
5 2
BGGGG
5 3
RBRGR
5 5
BBBRR
outputCopy
1
0
3
*/ | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 2b7777808643bc04dd6090a4bba4124f | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Solution implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Solution(),"Main",1<<27).start();
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
public static long findGCD(long arr[], int n)
{
long result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}
static void sortbycolomn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
public void run()
{
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t=in.nextInt();
while(t--!=0){
int n=in.nextInt();
int k=in.nextInt();
char[] c=in.next().toCharArray();
int min=Integer.MAX_VALUE;
int temp=0,flag=0;
for(int i=0;i<=n-k;i++){
for(int j=i;j<i+k;j++){
if(flag==0 && c[j]!='R') temp++;
else if(flag==1 && c[j]!='G') temp++;
else if(flag==2 && c[j]!='B') temp++;
flag=(flag+1)%3;
}
min=Math.min(min,temp);
flag=0;
temp=0;
for(int j=i;j<i+k;j++){
if(flag==0 && c[j]!='G') temp++;
else if(flag==1 && c[j]!='B') temp++;
else if(flag==2 && c[j]!='R') temp++;
flag=(flag+1)%3;
}
min=Math.min(min,temp);
temp=0;
flag=0;
for(int j=i;j<i+k;j++){
if(flag==0 && c[j]!='B') temp++;
else if(flag==1 && c[j]!='R') temp++;
else if(flag==2 && c[j]!='G') temp++;
flag=(flag+1)%3;
}
min=Math.min(min,temp);
flag=0;
temp=0;
}
w.println(min);
}
w.flush();
w.close();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 31ebfe5f2a129254b6f92b3416ef8459 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class GFG {
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t-->0){
int n=sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
String a="",m="",q="";
char b='R';
for(int i=0;i<k;i++){
a=a+b;
if(b=='R'){
b='G';continue;}
if(b=='G'){
b='B';continue;}
if(b=='B'){
b='R';continue;}
}
b='G';
for(int i=0;i<k;i++){
m=m+b;
if(b=='R'){
b='G';continue;}
if(b=='G'){
b='B';continue;}
if(b=='B'){
b='R';continue;}
}
b='B';
for(int i=0;i<k;i++){
q=q+b;
if(b=='R'){
b='G';continue;}
if(b=='G'){
b='B';continue;}
if(b=='B'){
b='R';continue;}
}
int min=Integer.MAX_VALUE;
for(int i=0;i<n-k+1;i++)
{
String w=s.substring(i,i+k);
int count1=0,count2=0,count3=0;
if(w.equals(a)||w.equals(m)||w.equals(q)){
min=0;break;}
for(int j=0;j<k;j++){
if(a.charAt(j)!=w.charAt(j))
count1++;
if(m.charAt(j)!=w.charAt(j))
count2++;
if(q.charAt(j)!=w.charAt(j))
count3++;
}
min=(int)Math.min(min,(int)Math.min(count1,(int)Math.min(count2,count3)));
}
System.out.println(min);
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 9c7a0e3d545ec4e710e15df91cb64d78 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Solution{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
while(t>0){
int n = sc.nextInt(); int l=0; int q = sc.nextInt();
char ch2[] = new char[4002];
for(int i=0;l<=4000;i++) {
ch2[l] = 'R';l++;
ch2[l] = 'G';l++;
ch2[l] = 'B';l++;
}
String ab=sc.nextLine();
String bgr = sc.nextLine(); char ch1[] = bgr.toCharArray();
int count=0 , min = 20000;
int hh = 0;
for(int z =0;z<n;z++) {
for(int i=0;i<3;i++) {
count=0;
for(int j=0;j<q;j++) {
if(j+z<n ) {
if(ch1[j+z]==ch2[i+j]) {
continue;
}
else {
count++;
}
}
else {
hh=-1;
}
}
if(hh!=-1) {
if(min > count) {
min = count;
}
}
}
}
System.out.println(min);
t--; }
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 7c08297392329970d2acff40770c176b | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class codeforces{
// Input
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String s = null;
try {
s = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return s;
}
public String nextParagraph() {
String line = null;
String ans = "";
try {
while ((line = reader.readLine()) != null) {
ans += line;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return ans;
}
}
//Template
static int mod = 998244353;
static void printArray(int ar[]){ for(int x:ar) System.out.print(x+" ");}
static void printArray(ArrayList<Integer> ar){ for(int x:ar) System.out.print(x+" ");}
static int gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);}
static long power(long x, long y, int p) { long res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1;x = (x * x) % p; } return res;}
static void takeArrayInput(InputReader sc, int ar[]){ for(int i=0;i<ar.length;i++) ar[i]=sc.nextInt(); }
static void takeArrayInput(InputReader sc, long ar[]){ for(int i=0;i<ar.length;i++) ar[i]=sc.nextLong(); }
static void take2dArrayInput(InputReader sc, int ar[][]){ for(int i=0;i<ar.length;i++) for(int j=0;j<ar[i].length;j++) ar[i][j]=sc.nextInt(); }
static void take2dArrayInput(InputReader sc, long ar[][]){ for(int i=0;i<ar.length;i++) for(int j=0;j<ar[i].length;j++) ar[i][j]=sc.nextLong(); }
static ArrayList<ArrayList<Integer>> graph(InputReader sc, int n, int m){
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
for(int i=0;i<n;i++) list.add(new ArrayList<Integer>());
for(int i=0;i<m;i++){ int u = sc.nextInt(); int v = sc.nextInt(); list.get(u).add(v); list.get(v).add(u); }
return list;
}
// Write Code Here
static class Data {
int u;
int v;
public Data(int e, int val) {
this.u = e;
this.v = val;
}
}
static void sieveOfEratosthenes(int n, ArrayList<Integer> pr) {
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p
pr.add(p);
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
public static void main(String args[]) {
InputReader sc = new InputReader();
PrintWriter pw = new PrintWriter(System.out);
int i=0, j=0;
int q = sc.nextInt();
for(int z=0;z<q;z++) {
int n = sc.nextInt(), k = sc.nextInt();
String s = sc.nextLine();
String rgb = "RGB";
j = rgb.indexOf(s.charAt(0));
int total = 0, m = Integer.MAX_VALUE;
for (i = 0; i <= (n - k); i++) {
for(int a=0;a<=2;a++){
int start = a;
total = 0;
for (j = i; j <= (i + k - 1); j++) {
if (s.charAt(j) != rgb.charAt(start)) {
total++;
}
start = (start + 1) % 3;
}
m = Math.min(m, total);
}
}
pw.println(m);
}
pw.close();
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 84eb0169a18c9b4af0771fcdebfa168d | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.util.*;
public class cf1196d1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
for (int tc = 0; tc < q; tc++) {
int n = in.nextInt();
int k = in.nextInt();
if (k == 1) {
System.out.println(0);
in.next();
continue;
}
ArrayList<String> a = new ArrayList<String>();
// String tmp = "";
StringBuilder tmp = new StringBuilder();
int cnt = 0;
while (tmp.length() != k) {
if (cnt == 0) {
tmp.append('R');
cnt = 1;
} else if (cnt == 1) {
tmp.append('G');
cnt = 2;
} else if (cnt == 2) {
tmp.append('B');
cnt = 0;
}
}
a.add(tmp.toString());
while (true) {
tmp.deleteCharAt(0);
if (tmp.charAt(tmp.length() - 1) == 'R') {
tmp.append('G');
} else if (tmp.charAt(tmp.length() - 1) == 'G') {
tmp.append('B');
} else if (tmp.charAt(tmp.length() - 1) == 'B') {
tmp.append('R');
}
if (tmp.toString().equals(a.get(0))) {
break;
} else {
a.add(tmp.toString());
}
}
// for (String string : a) {
//
// System.out.println("----> " + string);
//
// }
int min = Integer.MAX_VALUE;
String minString = "";
String def = "";
String s = in.next();
if (n == k) {
for (String string : a) {
int diff = 0;
for (int ind = 0; ind < k; ind++) {
if (s.charAt(ind) != string.charAt(ind)) {
diff++;
}
}
min = Math.min(min, diff);
}
System.out.println(min);
} else {
for (int i = 0; i < (n - k)+1; i++) {
String f = s.substring(i, i + k);
for (int j = 0; j < a.size(); j++) {
String comp = a.get(j);
int diff = 0;
for (int ind = 0; ind < k; ind++) {
if (comp.charAt(ind) != f.charAt(ind)) {
diff++;
}
}
// min = Math.min(min, diff);
if (diff < min) {
minString = f;
min = diff;
def = comp;
}
}
}
// System.out.println(minString);
// System.out.println(def);
System.out.println(min);
}
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | cd224945b242d9404fa3a7ae60b8f6a9 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class RGB_Substring_hard_version
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine().trim());
while(t-->0)
{
String str[]=br.readLine().trim().split(" ");
int n=Integer.parseInt(str[0]);
int k=Integer.parseInt(str[1]);
char p[][]=new char[3][3];
p[0][0]='R';
p[0][1]='G';
p[0][2]='B';
p[1][0]='G';
p[1][1]='B';
p[1][2]='R';
p[2][0]='B';
p[2][1]='R';
p[2][2]='G';
char a[]=("#"+br.readLine()).trim().toCharArray();
n=a.length;
int r[][]=new int[3][n];
for(int i=1;i<n;i++)
{
r[0][i]=1;
r[1][i]=1;
r[2][i]=1;
r[check(p[(i-1)%3],a[i])][i]=0;
r[0][i]+=r[0][i-1];
r[1][i]+=r[1][i-1];
r[2][i]+=r[2][i-1];
}
/*for(int x:r[0])
System.out.print(x+" ");
System.out.println();
for(int x:r[1])
System.out.print(x+" ");
System.out.println();
for(int x:r[2])
System.out.print(x+" ");
System.out.println();*/
int ans=Integer.MAX_VALUE;
for(int i=0,j=k;j<n;j++,i++)
{
int x=r[0][j]-r[0][i];
ans=Math.min(ans,x);
x=r[1][j]-r[1][i];
ans=Math.min(ans,x);
x=r[2][j]-r[2][i];
ans=Math.min(ans,x);
}
pw.println(ans);
}
pw.flush();
}
public static int check(char[] a,char x)
{
for(int i=0;i<3;i++)
if(a[i]==x)
return i;
return 0;
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | d35ae0cdfff21c83ae1d265660175fb0 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import javax.print.attribute.standard.PrinterMessageFromOperator;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
new Main().run();}
// int[] h,ne,to,wt;
// int ct = 0;
// int n;
// void graph(int n,int m){
// h = new int[n];
// Arrays.fill(h,-1);
//// sccno = new int[n];
//// dfn = new int[n];
//// low = new int[n];
//// iscut = new boolean[n];
// ne = new int[2*m];
// to = new int[2*m];
// wt = new int[2*m];
// ct = 0;
// }
// void add(int u,int v,int w){
// to[ct] = v;
// ne[ct] = h[u];
// wt[ct] = w;
// h[u] = ct++;
// }
//
// int color[],dfn[],low[],stack[] = new int[1000000],cnt[];
// int sccno[];
// boolean iscut[];
// int time = 0,top = 0;
// int scc_cnt = 0;
//
// // 有向图的强连通分量
// void tarjan(int u) {
// low[u] = dfn[u]= ++time;
// stack[top++] = u;
// for(int i=h[u];i!=-1;i=ne[i]) {
// int v = to[i];
// if(dfn[v]==0) {
// tarjan(v);
// low[u]=Math.min(low[u],low[v]);
// } else if(sccno[v]==0) {
// // dfn>0 but sccno==0, means it's in current stack
// low[u]=Math.min(low[u],low[v]);
// }
// }
//
// if(dfn[u]==low[u]) {
// sccno[u] = ++scc_cnt;
// while(stack[top-1]!=u) {
// sccno[stack[top-1]] = scc_cnt;
// --top;
// }
// --top;
// }
// }
//
// //缩点, topology sort
// int[] h1,to1,ne1;
// int ct1 = 0;
// void point(){
// for(int i=0;i<n;i++) {
// if(dfn[i]==0) tarjan(i);//有可能图不连通,所以要循环判断。
// }
// // 入度
// int du[] = new int[scc_cnt+1];
// h1 = new int[scc_cnt+1];
// Arrays.fill(h1, -1);
// to1 = new int[scc_cnt*scc_cnt];
// ne1 = new int[scc_cnt*scc_cnt];
// // scc_cnt 个点
//
// for(int i=1;i<=n;i++) {
// for(int j=h[i]; j!=-1; j=ne[j]) {
// int y = to[j];
// if(sccno[i] != sccno[y]) {
// // add(sccno[i],sccno[y]); // 建新图
// to1[ct1] = sccno[y];
// ne1[ct1] = h[sccno[i]];
// h[sccno[i]] = ct1++;
// du[sccno[y]]++; //存入度
// }
// }
// }
//
// int q[] = new int[100000];
// int end = 0;
// int st = 0;
// for(int i=1;i<=scc_cnt;++i){
// if(du[i]==0){
// q[end++] = i;
// }
// }
//
// int dp[] = new int[scc_cnt+1];
// while(st<end){
// int cur = q[st++];
// for(int i=h1[cur];i!=-1;i=ne1[i]){
// int y = to[i];
// // dp[y] += dp[cur];
// if(--du[y]==0){
// q[end++] = y;
// }
// }
// }
// }
//
//
//
//
// int fa[];
// int faw[];
//
// int dep = -1;
// int pt = 0;
// void go(int rt,int f,int dd){
//
// int p = 0;
// stk[p] = rt;
// lk[p] = 0;
// fk[p] = f;p++;
// while(p>0) {
// int cur = stk[p - 1];
// int fp = fk[p - 1];
// int ll = lk[p - 1];
// p--;
//
//
// if (ll > dep) {
// dep = ll;
// pt = cur;
// }
// for (int i = h[cur]; i != -1; i = ne[i]) {
// int v = to[i];
// if (fp == v) continue;
//
// stk[p] = v;
// lk[p] = ll + wt[i];
// fk[p] = cur;
// p++;
// }
// }
// }
// int pt1 = -1;
// void go1(int rt,int f,int dd){
//
// int p = 0;
// stk[p] = rt;
// lk[p] = 0;
// fk[p] = f;p++;
// while(p>0) {
// int cur = stk[p - 1];
// int fp = fk[p - 1];
// int ll = lk[p - 1];
// p--;
//
//
// if (ll > dep) {
// dep = ll;
// pt1 = cur;
// }
//
// fa[cur] = fp;
// for (int i = h[cur]; i != -1; i = ne[i]) {
// int v = to[i];
// if (v == fp) continue;
// faw[v] = wt[i];
// stk[p] = v;
// lk[p] = ll + wt[i];
// fk[p] = cur;
// p++;
// }
// }
// }
//
// int r = 0;
// int stk[] = new int[301];
// int fk[] = new int[301];
// int lk[] = new int[301];
// void ddfs(int rt,int t1,int t2,int t3,int l){
//
//
// int p = 0;
// stk[p] = rt;
// lk[p] = 0;
// fk[p] = t3;p++;
// while(p>0){
// int cur = stk[p-1];
// int fp = fk[p-1];
// int ll = lk[p-1];
// p--;
// r = Math.max(r,ll);
// for(int i=h[cur];i!=-1;i=ne[i]){
// int v = to[i];
// if(v==t1||v==t2||v==fp) continue;
// stk[p] = v;
// lk[p] = ll+wt[i];
// fk[p] = cur;p++;
// }
// }
//
//
//
// }
static long mul(long a, long b, long p)
{
long res=0,base=a;
while(b>0)
{
if((b&1L)>0)
res=(res+base)%p;
base=(base+base)%p;
b>>=1;
}
return res;
}
static long mod_pow(long k,long n,long p){
long res = 1L;
long temp = k;
while(n!=0L){
if((n&1L)==1L){
res = (res*temp)%p;
}
temp = (temp*temp)%p;
n = n>>1L;
}
return res%p;
}
int ct = 0;
int f[] =new int[200001];
int b[] =new int[200001];
int str[] =new int[200001];
void go(int rt,List<Integer> g[]){
str[ct] = rt;
f[rt] = ct;
for(int cd:g[rt]){
ct++;
go(cd,g);
}
b[rt] = ct;
}
int add =0;
void sort(long a[]) {
Random rd = new Random();
for (int i = 1; i < a.length; ++i) {
int p = rd.nextInt(i); long x = a[p]; a[p] = a[i]; a[i] = x;
}
Arrays.sort(a);
}
void dfs(int from,int k){
}
void add(int u,int v){
to[ct] = u;
ne[ct] = h[v];
h[v] = ct++;
}
int r =0;
void dfs1(int c,int ff){
clr[c][aa[c]]++;
for(int j=h[c];j!=-1;j=ne[j]){
if(to[j]==ff) continue;
dfs1(to[j],c);
clr[c][1] += clr[to[j]][1];
clr[c][2] += clr[to[j]][2];
if(clr[to[j]][1]==s1&&clr[to[j]][2]==0||clr[to[j]][2]==s2&&clr[to[j]][1]==0){
r++;
}
}
}
int[] h,ne,to,fa1;
int clr[][];
int aa[];
int s1 = 0;
int s2 = 0;
boolean f(int n){
int c = 0;
while(n>0){
c += n%10;
n /=10;
}
return (c&3)==0;
}
int[][] next(String s){
int len = s.length();
int ne[][] = new int[len+1][26];
Arrays.fill(ne[len], -1);
for(int i=len-1;i>=0;--i){
ne[i] = ne[i+1].clone();
ne[i][s.charAt(i)-'a'] = i+1;
}
return ne;
}
void sort(int a[]){
Random rd =new Random();
for(int i=1;i<a.length;++i){
int id = rd.nextInt(i);
int t = a[id];
a[id] = a[i];
a[i] = t;
}
}
boolean same(String s){
return s.charAt(0)==s.charAt(1);
}
boolean next_perm(int[] a){
int len = a.length;
for(int i=len-2,j = 0;i>=0;--i){
if(a[i]<a[i+1]){
j = len-1;
for(;a[j]<=a[i];--j);
int p = a[j];
a[j] = a[i];
a[i] = p;
j = i+1;
for(int ed = len-1;j<ed;--ed) {
p = a[ed];
a[ed] = a[j];
a[j++] = p;
}
return true;
}
}
return false;
}
void print1(int c[],int n){
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;++i){
for(int j=0;j<3;++j) {
sb.appendCodePoint(c[j]+'a');
}
}
println(sb);
}
void print2(int c[],int n){
StringBuilder sb = new StringBuilder();
for(int j=0;j<3;++j) {
for (int i = 0; i < n; ++i) {
sb.appendCodePoint(c[j]+'a');
}
}
println(sb);
}
void solve() {
int q =ni();
int f[] = new int[200002];
int dp[][] = new int[200002][3];
for(int i=0;i<q;++i){
int n = ni();
int k = ni();
String s = ns();
for(int j=0;j<n;++j){
char c = s.charAt(j);
if(c=='R') {
f[j+1] = 0;
}else if(c=='G'){
f[j+1] = 1;
}else if(s.charAt(j)=='B'){
f[j+1] = 2;
}
}
int r = n;
for(int j=1;j<=n;++j){
for(int x= 0;x<=2;++x){
dp[j][x] = dp[j-1][(x+2)%3] + (f[j]==x?0:1);
if(j>=k) {
r = Math.min(dp[j][x] - dp[j - k][(3 + (x - k) % 3) % 3], r);
}
}
}
println(r);
}
//N , M , K , a , b , c , d . 其中N , M是矩阵的行列数;K 是上锁的房间数目,(a, b)是起始位置,(c, d)是出口位置
// int n = ni();
// int m = ni();
// int k = ni();
// int a = ni();
// int b = ni();
// int c = ni();
// int d = ni();
//
//
// char cc[][] = nm(n,m);
// char keys[][] = new char[n][m];
//
// char ky = 'a';
// for(int i=0;i<k;++i){
// int x = ni();
// int y = ni();
// keys[x][y] = ky;
// ky++;
// }
// int f1[] = {a,b,0};
//
// int dd[][] = {{0,1},{0,-1},{1,0},{-1,0}};
//
// Queue<int[]> q = new LinkedList<>();
// q.offer(f1);
// int ts = 1;
//
// boolean vis[][][] = new boolean[n][m][33];
//
// while(q.size()>0){
// int sz = q.size();
// while(sz-->0) {
// int cur[] = q.poll();
// vis[cur[0]][cur[1]][cur[2]] = true;
//
// int x = cur[0];
// int y = cur[1];
//
// for (int u[] : dd) {
// int lx = x + u[0];
// int ly = y + u[1];
// if (lx >= 0 && ly >= 0 && lx < n && ly < m && (cc[lx][ly] != '#')&&!vis[lx][ly][cur[2]]){
// char ck =cc[lx][ly];
// if(ck=='.'){
// if(lx==c&&ly==d){
// println(ts); return;
// }
// if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') {
// int cao = cur[2] | (1 << (keys[lx][ly] - 'a'));
// q.offer(new int[]{lx, ly, cao});
// vis[lx][ly][cao] = true;
// }else {
//
// q.offer(new int[]{lx, ly, cur[2]});
// }
//
// }else if(ck>='A'&&ck<='Z'){
// int g = 1<<(ck-'A');
// if((g&cur[2])>0){
// if(lx==c&&ly==d){
// println(ts); return;
// }
// if(keys[lx][ly]>='a'&&keys[lx][ly]<='z') {
//
// int cao = cur[2] | (1 << (keys[lx][ly] - 'a'));
// q.offer(new int[]{lx, ly, cao});
// vis[lx][ly][cao] = true;;
// }else {
//
// q.offer(new int[]{lx, ly, cur[2]});
// }
// }
// }
// }
// }
//
// }
// ts++;
// }
// println(-1);
// int n = ni();
//
// HashSet<String> st = new HashSet<>();
// HashMap<String,Integer> mp = new HashMap<>();
//
//
// for(int i=0;i<n;++i){
// String s = ns();
// int id= 1;
// if(mp.containsKey(s)){
// int u = mp.get(s);
// id = u;
//
// }
//
// if(st.contains(s)) {
//
// while (true) {
// String ts = s + id;
// if (!st.contains(ts)) {
// s = ts;
// break;
// }
// id++;
// }
// mp.put(s,id+1);
// }else{
// mp.put(s,1);
// }
// println(s);
// st.add(s);
//
// }
// int t = ni();
//
// for(int i=0;i<t;++i){
// int n = ni();
// long w[] = nal(n);
//
// Map<Long,Long> mp = new HashMap<>();
// PriorityQueue<long[]> q =new PriorityQueue<>((xx,xy)->{return Long.compare(xx[0],xy[0]);});
//
// for(int j=0;j<n;++j){
// q.offer(new long[]{w[j],0});
// mp.put(w[j],mp.getOrDefault(w[j],0L)+1L);
// }
//
// while(q.size()>=2){
// long f[] = q.poll();
// long y1 = f[1];
// if(y1==0){
// y1 = mp.get(f[0]);
// if(y1==1){
// mp.remove(f[0]);
// }else{
// mp.put(f[0],y1-1);
// }
// }
// long g[] = q.poll();
// long y2 = g[1];
// if(y2==0){
// y2 = mp.get(g[0]);
// if(y2==1){
// mp.remove(g[0]);
// }else{
// mp.put(g[0],y2-1);
// }
// }
// q.offer(new long[]{f[0]+g[0],2L*y1*y2});
//
// }
// long r[] = q.poll();
// println(r[1]);
//
//
//
//
// }
// int o= 9*8*7*6;
// println(o);
// int t = ni();
// for(int i=0;i<t;++i){
// long a = nl();
// int k = ni();
// if(k==1){
// println(a);
// continue;
// }
//
// int f = (int)(a%10L);
// int s = 1;
// int j = 0;
// for(;j<30;j+=2){
// int u = f-j;
// if(u<0){
// u = 10+u;
// }
// s = u*s;
// s = s%10;
// if(s==k){
// break;
// }
// }
//
// if(s==k) {
// println(a - j - 2);
// }else{
// println(-1);
// }
//
//
//
//
// }
// int m = ni();
// h = new int[n];
// to = new int[2*(n-1)];
// ne = new int[2*(n-1)];
// wt = new int[2*(n-1)];
//
// for(int i=0;i<n-1;++i){
// int u = ni()-1;
// int v = ni()-1;
//
// }
// long a[] = nal(n);
// int n = ni();
// int k = ni();
// t1 = new long[200002];
//
// int p[][] = new int[n][3];
//
// for(int i=0;i<n;++i){
// p[i][0] = ni();
// p[i][1] = ni();
// p[i][2] = i+1;
// }
// Arrays.sort(p, new Comparator<int[]>() {
// @Override
// public int compare(int[] x, int[] y) {
// if(x[1]!=y[1]){
// return Integer.compare(x[1],y[1]);
// }
// return Integer.compare(y[0], x[0]);
// }
// });
//
// for(int i=0;i<n;++i){
// int ck = p[i][0];
//
// }
}
// int []h,to,ne,wt;
long t1[];
// long t2[];
void update(long[] t,int i,long v){
for(;i<t.length;i+=(i&-i)){
t[i] += v;
}
}
long get(long[] t,int i){
long s = 0;
for(;i>0;i-=(i&-i)){
s += t[i];
}
return s;
}
int equal_bigger(long t[],long v){
int s=0,p=0;
for(int i=Integer.numberOfTrailingZeros(Integer.highestOneBit(t.length));i>=0;--i) {
if(p+(1<<i)< t.length && s + t[p+(1<<i)] < v){
v -= t[p+(1<<i)];
p |= 1<<i;
}
}
return p+1;
}
static class S{
int l = 0;
int r = 0 ;
long le = 0;
long ri = 0;
long tot = 0;
long all = 0;
public S(int l,int r) {
this.l = l;
this.r = r;
}
}
static S a[];
static int[] o;
static void init(int[] f){
o = f;
int len = o.length;
a = new S[len*4];
build(1,0,len-1);
}
static void build(int num,int l,int r){
S cur = new S(l,r);
if(l==r){
a[num] = cur;
return;
}else{
int m = (l+r)>>1;
int le = num<<1;
int ri = le|1;
build(le, l,m);
build(ri, m+1,r);
a[num] = cur;
pushup(num, le, ri);
}
}
// static int query(int num,int l,int r){
//
// if(a[num].l>=l&&a[num].r<=r){
// return a[num].tot;
// }else{
// int m = (a[num].l+a[num].r)>>1;
// int le = num<<1;
// int ri = le|1;
// pushdown(num, le, ri);
// int ma = 1;
// int mi = 100000001;
// if(l<=m) {
// int r1 = query(le, l, r);
// ma = ma*r1;
//
// }
// if(r>m){
// int r2 = query(ri, l, r);
// ma = ma*r2;
// }
// return ma;
// }
// }
static long dd = 10007;
static void update(int num,int l,long v){
if(a[num].l==a[num].r){
a[num].le = v%dd;
a[num].ri = v%dd;
a[num].all = v%dd;
a[num].tot = v%dd;
}else{
int m = (a[num].l+a[num].r)>>1;
int le = num<<1;
int ri = le|1;
pushdown(num, le, ri);
if(l<=m){
update(le,l,v);
}
if(l>m){
update(ri,l,v);
}
pushup(num,le,ri);
}
}
static void pushup(int num,int le,int ri){
a[num].all = (a[le].all*a[ri].all)%dd;
a[num].le = (a[le].le + a[le].all*a[ri].le)%dd;
a[num].ri = (a[ri].ri + a[ri].all*a[le].ri)%dd;
a[num].tot = (a[le].tot + a[ri].tot + a[le].ri*a[ri].le)%dd;
//a[num].res[1] = Math.min(a[le].res[1],a[ri].res[1]);
}
static void pushdown(int num,int le,int ri){
}
long gcd(long a,long b){ return b==0?a: gcd(b,a%b);}
int gcd(int a,int b){ return b==0?a: gcd(b,a%b);}
InputStream is;PrintWriter out;
void run() throws Exception {is = System.in;out = new PrintWriter(System.out);solve();out.flush();}
private byte[] inbuf = new byte[2];
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 char ncc() {int b;while((b = readByte()) != -1 && !(b >= 32 && b <= 126));return (char)b;}
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 String nline() {int b = skip();StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b);b = readByte(); }
return sb.toString();}
private char[][] nm(int n, int m) {char[][] a = new char[n][];for (int i = 0; i < n; i++) a[i] = ns(m);return a;}
private int[] na(int n) {int[] a = new int[n];for (int i = 0; i < n; i++) a[i] = ni();return a;}
private long[] nal(int n) { long[] a = new long[n];for (int i = 0; i < n; i++) a[i] = nl();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 << 3) + (num << 1) + (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();}}
void print(Object obj){out.print(obj);}
void println(Object obj){out.println(obj);}
void println(){out.println();}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | aa85d35e79a7d2e85b54aa045d106194 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main
{
public static void main(String[] args)
{
FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out);
int q =fr.nextInt() ,n ,k ,i ,j ,dum ,ans ,ptr[][] =new int[2][2] ; String s ,a ="RGB" ;
for (j =1 ; j<=17 ; ++j) a += a ;
while (q-- > 0) {
n =fr.nextInt() ; k =fr.nextInt() ; s =fr.next() ; ans =Integer.MAX_VALUE ;
ptr[0][0] =a.length()-k ; ptr[0][1] =a.length()-1 ; ptr[1][0] =s.length()-k ; ptr[1][1] =s.length()-1 ;
for (i =0 ; i<3 ; ++i) {
dum =0 ;
for (j =0 ; j<k ; j++) {
if (s.charAt(ptr[1][0]+j) != a.charAt(ptr[0][0]+j)) ++dum ;
}
ans =Math.min(ans , dum) ;
for (j =1 ; j-1<ptr[1][0] ; j++) {
if (s.charAt(ptr[1][0]-j) != a.charAt(ptr[0][0]-j)) ++dum ;
if (s.charAt(ptr[1][1]-j+1) != a.charAt(ptr[0][1]-j+1)) --dum ;
ans =Math.min(ans , dum) ;
}
ptr[0][0]-- ; ptr[0][1]-- ;
}
op.println(ans) ;
}op.flush(); op.close();
}
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();
}
String nextLine() {
String str ="";
try
{
str =br.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | a496e3cf5ca51dae8dc54a075051d9aa | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main
{
public static void main(String[] args)
{
FastReader fr =new FastReader();
PrintWriter op =new PrintWriter(System.out);
int q =fr.nextInt() ,i ,i_ ,n ,k ,j ,l ,dm ;
String[] a =new String[3] ; a[0] ="" ;a[1] ="" ;a[2] ="" ;
for (i =0 ; i<2001 ; i+=3) a[0] += "RGB" ;
for (i =0 ; i<2001 ; i+=3) a[1] += "GBR" ;
for (i =0 ; i<2001 ; i+=3) a[2] += "BRG" ;
while (q-- > 0) {
n =fr.nextInt() ; k =fr.nextInt() ; dm =Integer.MAX_VALUE ;
String s =fr.next() ;
for (i =0 ; i<=n-k ; i++) {
for (l =0 ; l<3 ; ++l) {
j =0 ;
for (i_ =0 ; i_<k ; i_++) {
if (s.charAt(i_+i)!=a[l].charAt(i_)) j++;
}
dm =Math.min(dm , j) ;
}
}
op.println(dm) ;
}
op.flush(); op.close();
}
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();
}
String nextLine() {
String str ="";
try
{
str =br.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 024ee705f6b41d2d3589cee9bcf1737f | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static Scanner sc = new Scanner(System.in);
/*public static void main(String[] args) throws IOException{
int n=sc.nextInt();
for (int i = 0; i < n; i++) {
Long[] bags= new Long[3];
for (int j = 0; j < bags.length; j++) {
bags[j]=sc.nextLong();
}
Arrays.sort(bags);
//System.out.println(Arrays.toString(bags));
long a=bags[0];
long b=bags[1];
long c=bags[2];
//System.out.println(a + " " + b + " " + c);
long extra=(b-a)/2;
//System.out.println("extra: " + extra);
if(c%2==0){
a+=c/2+extra;
b+=c/2-extra;
}
else
{
a+=c/2+1+extra;
b+=c/2-extra;
}
if(a!=b)
{
if(a>b)
{
a=b;
}
else
{
b=a;
}
}
System.out.println(a);
//System.out.println(b);
}
}*/
/*public static void main(String[] args) throws IOException{
int t=sc.nextInt();
for (int i = 0; i < t; i++) {
int n=sc.nextInt();
int k=sc.nextInt();
int[] a=new int[n];
for (int j = 0; j < a.length; j++) {
a[j]=sc.nextInt();
}
//System.out.println(Arrays.toString(a));
long sum=0;
TreeSet<Integer> tree= new TreeSet<Integer>();
for (int j = 0; j < a.length; j++) {
sum+=a[j];
if(sum%2==1)
{
if(tree.size()!=k-1)
{
sum=0;
tree.add(j+1);
}
}
}
if(sum%2==1)
{
tree.add(n);
}
if (tree.size()==k) {
System.out.println("YES");
for(int x:tree)
{
System.out.print(x + " ");
}
System.out.println();
}
else
{
System.out.println("NO");
}
}
}*/
/*public static void main(String[] args) throws IOException{
int q=sc.nextInt();
for (int i = 0; i < q; i++) {
int r=sc.nextInt();
int LX=-100000;
int UX=100000;
int LY=-100000;
int UY=100000;
for (int j = 0; j < r; j++) {
int x=sc.nextInt();
int y=sc.nextInt();
int f1=sc.nextInt();
int f2=sc.nextInt();
int f3=sc.nextInt();
int f4=sc.nextInt();
int lx; int ly; int ux; int uy;
if(f1==1)
{
lx=-100000;
}
else
{
lx=x;
}
if(f2==1)
{
uy=100000;
}
else
{
uy=y;
}
if(f3==1)
{
ux=100000;
}
else
{
ux=x;
}
if(f4==1)
{
ly=-100000;
}
else
{
ly=y;
}
if(lx>LX)
{
LX=lx;
}
if(ux<UX)
{
UX=ux;
}
if(ly>LY)
{
LY=ly;
}
if(uy<UY)
{
UY=uy;
}
}
if(UX<LX || UY<LY)
{
System.out.println(0);
}
else
{
System.out.println(1 + " " + LX + " " + LY);
}
}
}*/
/*public static void main(String[] args) throws IOException{
int q=sc.nextInt();
for (int i = 0; i < q; i++) {
int n=sc.nextInt();
int k=sc.nextInt();
String s= sc.next();
int curr=1;
int max=1;
int maxNow=0;
int f=0;
int l=k-1;
while(l<s.length())
{
for (int j = f; j < l; j++) {
if(s.charAt(j)=='R' && s.charAt(j+1)=='G')
{
curr++;
}
else if(s.charAt(j)=='G' && s.charAt(j+1)=='B')
{
curr++;
}
else if(s.charAt(j)=='B' && s.charAt(j+1)=='R')
{
curr++;
}
else
{
if(curr>1)
{
maxNow+=curr;
}
curr=1;
}
}
if(curr>1)
{
maxNow+=curr;
}
if(maxNow>max)
{
max=maxNow;
}
System.out.println(s);
System.out.println(f + " " + l);
System.out.println(s.substring(f, l+1));
System.out.println("curr: " + curr);
System.out.println("max: " + max);
System.out.println("max now: " + maxNow);
f++;
l++;
curr=1;
maxNow=0;
}
System.out.println(k-max);
}
}*/
public static void main(String[] args) throws IOException{
int q=sc.nextInt();
for (int i = 0; i < q; i++)
{
int n=sc.nextInt();
int k=sc.nextInt();
String s= sc.next();
int min=-1;
int f=0;
int l=k-1;
while(l<s.length())
{
int costR=0;
int count=0;
for (int j = f; j <= l; j++)
{
if(count%3==0 && s.charAt(j)!='R')
{
costR++;
}
if(count%3==1 && s.charAt(j)!='G')
{
costR++;
}
if(count%3==2 && s.charAt(j)!='B')
{
costR++;
}
count++;
}
int costG=0;
count=0;
for (int j = f; j <= l; j++)
{
if(count%3==0 && s.charAt(j)!='G')
{
costG++;
}
if(count%3==1 && s.charAt(j)!='B')
{
costG++;
}
if(count%3==2 && s.charAt(j)!='R')
{
costG++;
}
count++;
}
int costB=0;
count=0;
for (int j = f; j <= l; j++)
{
if(count%3==0 && s.charAt(j)!='B')
{
costB++;
}
if(count%3==1 && s.charAt(j)!='R')
{
costB++;
}
if(count%3==2 && s.charAt(j)!='G')
{
costB++;
}
count++;
}
int minCost=0;
if(costR<=costG && costR<=costB)
{
minCost=costR;
}
else if(costG<=costB && costG<costR)
{
minCost=costG;
}
else
{
minCost=costB;
}
if(min==-1 || min>minCost)
{
min=minCost;
}
f++;
l++;
}
System.out.println(min);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
int start = 0;
boolean dec = false, neg = false;
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\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 68040a9980d3afdf99e102d7f6ae3936 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | // package cp.codeforces.round575;
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int numQ = Integer.parseInt(br.readLine().trim());
for (int q = 0; q < numQ; q++) {
String[] line = br.readLine().trim().split(" ");
int k = Integer.parseInt(line[1]);
String str = br.readLine().trim();
bw.write(solve(str, k) + "\n");
}
bw.flush();
}
private static int solve(String str, int k) {
String[] candidates = generateCandidates(k);
int minUpdates = k;
for (int i = 0; i <= str.length() - k; i++) {
minUpdates = Math.min(minUpdates, getMinDistance(str.substring(i, i + k), candidates));
}
return minUpdates;
}
private static String[] generateCandidates(int k) {
StringBuilder sb0 = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
int len = 0;
while(len + 3 <= k) {
sb0.append("RGB");
sb1.append("GBR");
sb2.append("BRG");
len += 3;
}
int needed = k - len;
if(needed == 1) {
sb0.append("R");
sb1.append("G");
sb2.append("B");
}
if(needed == 2) {
sb0.append("RG");
sb1.append("GB");
sb2.append("BR");
}
String[] candidates = new String[3];
candidates[0] = sb0.toString();
candidates[1] = sb1.toString();
candidates[2] = sb2.toString();
return candidates;
}
private static int getMinDistance(String substring, String[] candidates) {
int[] distance = new int[candidates.length];
for (int i = 0; i < substring.length(); i++) {
if(substring.charAt(i) != candidates[0].charAt(i))
distance[0]++;
if(substring.charAt(i) != candidates[1].charAt(i))
distance[1]++;
if(substring.charAt(i) != candidates[2].charAt(i))
distance[2]++;
}
int minDistance = distance[0];
minDistance = Math.min(minDistance, distance[1]);
minDistance = Math.min(minDistance, distance[2]);
return minDistance;
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | fb2e87a2177a36845412d15bf1c66324 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
StringBuilder sb=new StringBuilder();
int q=sc.nextInt();
while(q-->0) {
int n = sc.nextInt(), k = sc.nextInt();
char[] c = sc.nextLine().toCharArray();
StringBuilder sb1=new StringBuilder();
StringBuilder sb2=new StringBuilder();
StringBuilder sb3=new StringBuilder();
sb1.append("R");sb2.append("G");sb3.append("B");
for(int i=1;i<k;i++){
if(i%3==1){
sb1.append("G");
sb2.append("B");
sb3.append("R");
}
else if(i%3==2){
sb1.append("B");
sb2.append("R");
sb3.append("G");
}
else{
sb1.append("R");
sb2.append("G");
sb3.append("B");
}
}
// System.out.println(sb1);
// System.out.println(sb2);
// System.out.println(sb3);
int max=0;
for(int i=0;i<=n-k;i++){
int count1=0,count2=0,count3=0;
for(int j=0;j<k;j++){
if(sb1.charAt(j)==c[i+j])count1++;
if(sb2.charAt(j)==c[i+j])count2++;
if(sb3.charAt(j)==c[i+j])count3++;
}
max=Math.max(max,Math.max(count1,Math.max(count2,count3)));
}
if(max>=k)sb.append(0+"\n");
else sb.append((k-max)+"\n");
}
System.out.println(sb);
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); }
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 66642e03972212e24b1d5d7c792441f7 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class Main {
private static Scanner sc;
private static Printer pr;
static boolean []visited;
static int []color;
static int []pow=new int[(int)3e5+1];
static int []count;
static boolean check=true;
static boolean checkBip=true;
static ArrayList<Integer>[]list;
private static long aLong=(long)(Math.pow(10,9)+7);
static final long div=998244353;
static int answer=0;
private static void solve() throws IOException {
int q=sc.nextInt();
String rgb="RGB";
for (int i=1;i<=q;i++){
int n=sc.nextInt(),k=sc.nextInt();
long min=(long)1e10;
String s=sc.next();
for (int j=0;j<=n-k;j++){
String str=s.substring(j,j+k);
for (int l=0;l<3;l++){
int curAns=0;
for (int m=0;m<k;m++){
if (s.charAt(j+m)!=rgb.charAt(((m+l)%3)))
curAns++;
}
min=Math.min(curAns,min);
//System.out.println("min:"+min);
}
}
//System.out.println("minchange:"+minChange);
//System.out.println("****************");
pr.println(min);
}
}
public static void bfsColor(int src){
Queue<Integer>queue = new ArrayDeque<>();
queue.add(src);
while (!queue.isEmpty()){
boolean b=false;
int vertex=-1,p=-1;
int poll=queue.remove();
for (int v:list[poll]){
if (color [v]==0){
vertex=v;
break;
}
}
for (int v:list[poll]){
if (color [v]!=0&&v!=vertex){
p=v;
break;
}
}
for (int v:list[p]){
if (color [v]!=0){
color[vertex]=color[v];
b=true;
break;
}
}
if (!b){
color[vertex]=color[poll]+1;
}
}
}
static int add(int a,int b ){
if (a+b>=div)
return (int)(a+b-div);
return (int)a+b;
}
public static int isBipartite(ArrayList<Integer>[]list,int src){
color[src]=0;
Queue<Integer>queue=new LinkedList<>();
int []ans={0,0};
queue.add(src);
while (!queue.isEmpty()){
ans[color[src=queue.poll()]]++;
for (int v:list[src]){
if (color[v]==-1){
queue.add(v);
color[v]=color[src]^1;
}else if (color[v]==color[src])
check=false;
}
}
return add(pow[ans[0]],pow[ans[1]]);
}
public static int powerMod(long b, long e){
long ans=1;
while (e-->0){
ans=ans*b%div;
}
return (int)ans;
}
public static int dfs(int s){
int ans=1;
visited[s]=true;
for (int k:list[s]){
if (!visited[k]){
ans+=dfs(k);
}
}
return ans;
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public static long []primeFactor(int n){
long []prime=new long[n+1];
prime[1]=1;
for (int i=2;i<=n;i++)
prime[i]=((i&1)==0)?2:i;
for (int i=3;i*i<=n;i++){
if (prime[i]==i){
for (int j=i*i;j<=n;j+=i){
if (prime[j]==j)
prime[j]=i;
}
}
}
return prime;
}
public static StringBuilder binaryradix(long number){
StringBuilder builder=new StringBuilder();
long remainder;
while (number!=0) {
remainder = number % 2;
number >>= 1;
builder.append(remainder);
}
builder.reverse();
return builder;
}
public static int binarySearch(long[] a, int index,long target) {
int l = index;
int h = a.length - 1;
while (l<=h) {
int med = l + (h-l)/2;
if(a[med] - target <= target) {
l = med + 1;
}
else h = med - 1;
}
return h;
}
public static int val(char c){
return c-'0';
}
public static long gcd(long a,long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
private static class Pair implements Comparable<Pair> {
long x;
long y;
Pair() {
this.x = 0;
this.y = 0;
}
Pair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) return false;
Pair other = (Pair) obj;
if (this.x == other.x && this.y == other.y) {
return true;
}
return false;
}
@Override
public int compareTo(Pair other) {
if (this.x != other.x) return Long.compare(this.x, other.x);
return Long.compare(this.y*other.x, this.x*other.y);
}
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
pr = new Printer(System.out);
solve();
pr.close();
// sc.close();
}
private static class Scanner {
BufferedReader br;
Scanner (InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
private boolean isPrintable(int ch) {
return ch >= '!' && ch <= '~';
}
private boolean isCRLF(int ch) {
return ch == '\n' || ch == '\r' || ch == -1;
}
private int nextPrintable() {
try {
int ch;
while (!isPrintable(ch = br.read())) {
if (ch == -1) {
throw new NoSuchElementException();
}
}
return ch;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
String next() {
try {
int ch = nextPrintable();
StringBuilder sb = new StringBuilder();
do {
sb.appendCodePoint(ch);
} while (isPrintable(ch = br.read()));
return sb.toString();
} catch (IOException e) {
throw new NoSuchElementException();
}
}
int nextInt() {
try {
// parseInt from Integer.parseInt()
boolean negative = false;
int res = 0;
int limit = -Integer.MAX_VALUE;
int radix = 10;
int fc = nextPrintable();
if (fc < '0') {
if (fc == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (fc != '+') {
throw new NumberFormatException();
}
fc = br.read();
}
int multmin = limit / radix;
int ch = fc;
do {
int digit = ch - '0';
if (digit < 0 || digit >= radix) {
throw new NumberFormatException();
}
if (res < multmin) {
throw new NumberFormatException();
}
res *= radix;
if (res < limit + digit) {
throw new NumberFormatException();
}
res -= digit;
} while (isPrintable(ch = br.read()));
return negative ? res : -res;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
long nextLong() {
try {
// parseLong from Long.parseLong()
boolean negative = false;
long res = 0;
long limit = -Long.MAX_VALUE;
int radix = 10;
int fc = nextPrintable();
if (fc < '0') {
if (fc == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (fc != '+') {
throw new NumberFormatException();
}
fc = br.read();
}
long multmin = limit / radix;
int ch = fc;
do {
int digit = ch - '0';
if (digit < 0 || digit >= radix) {
throw new NumberFormatException();
}
if (res < multmin) {
throw new NumberFormatException();
}
res *= radix;
if (res < limit + digit) {
throw new NumberFormatException();
}
res -= digit;
} while (isPrintable(ch = br.read()));
return negative ? res : -res;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
float nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
int ch;
while (isCRLF(ch = br.read())) {
if (ch == -1) {
throw new NoSuchElementException();
}
}
StringBuilder sb = new StringBuilder();
do {
sb.appendCodePoint(ch);
} while (!isCRLF(ch = br.read()));
return sb.toString();
} catch (IOException e) {
throw new NoSuchElementException();
}
}
void close() {
try {
br.close();
} catch (IOException e) {
// throw new NoSuchElementException();
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class List {
String Word;
int length;
List(String Word, int length) {
this.Word = Word;
this.length = length;
}
}
private static class Printer extends PrintWriter {
Printer(PrintStream out) {
super(out);
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 1e1f564af31faa70aaa8a136a55d5bfc | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String ag[])
{
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
int i,j,k;
while(T-- >0)
{
int N=sc.nextInt();
int K=sc.nextInt();
char A[]=sc.next().toCharArray();
int rgb=0;
int gbr=0;
int brg=0;
for(i=0;i<K;i++)
{
if(i%3==0)
{
if(A[i]!='R') rgb++;
if(A[i]!='G') gbr++;
if(A[i]!='B') brg++;
}
if(i%3==1)
{
if(A[i]!='G') rgb++;
if(A[i]!='B') gbr++;
if(A[i]!='R') brg++;
}
if(i%3==2)
{
if(A[i]!='B') rgb++;
if(A[i]!='R') gbr++;
if(A[i]!='G') brg++;
}
}
int ans=Math.min(rgb,Math.min(gbr,brg));
for(i=K,j=0;i<N;i++,j++)
{
if(j%3==0)
{
if(A[i-K]!='R') rgb--;
if(A[i-K]!='G') gbr--;
if(A[i-K]!='B') brg--;
}
if(j%3==1)
{
if(A[i-K]!='G') rgb--;
if(A[i-K]!='B') gbr--;
if(A[i-K]!='R') brg--;
}
if(j%3==2)
{
if(A[i-K]!='B') rgb--;
if(A[i-K]!='R') gbr--;
if(A[i-K]!='G') brg--;
}
if(i%3==0)
{
if(A[i]!='R') rgb++;
if(A[i]!='G') gbr++;
if(A[i]!='B') brg++;
}
if(i%3==1)
{
if(A[i]!='G') rgb++;
if(A[i]!='B') gbr++;
if(A[i]!='R') brg++;
}
if(i%3==2)
{
if(A[i]!='B') rgb++;
if(A[i]!='R') gbr++;
if(A[i]!='G') brg++;
}
ans=Math.min(ans,Math.min(rgb,Math.min(gbr,brg)));
}
System.out.println(ans);
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 3cf5f4c2315a04d5719f50ea8f6f4898 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.management.MemoryType;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
public class Main {
static final int INF = Integer.MAX_VALUE;
static int mergeSort(int[] a,int [] c, int begin, int end)
{
int inversion=0;
if(begin < end)
{
inversion=0;
int mid = (begin + end) >>1;
inversion+= mergeSort(a,c, begin, mid);
inversion+=mergeSort(a, c,mid + 1, end);
inversion+=merge(a,c, begin, mid, end);
}
return inversion;
}
static int merge(int[] a,int[]c, int b, int mid, int e)
{
int n1 = mid - b + 1;
int n2 = e - mid;
int[] L = new int[n1+1], R = new int[n2+1];
int[] L1 = new int[n1+1], R1 = new int[n2+1];
//inversion
int inversion=0;
for(int i = 0; i < n1; i++) {
L[i] = a[b + i];
L1[i] = c[b + i];
// L2[i] = w[b + i];
}
for(int i = 0; i < n2; i++) {
R[i] = a[mid + 1 + i];
R1[i] = c[mid + 1 + i];
//R2[i] = w[mid + 1 + i];
}
L[n1] = R[n2] = INF;
for(int k = b, i = 0, j = 0; k <= e; k++)
if(L[i] <= R[j]){
a[k] = L[i];
c[k] = L1[i];
++i;
// w[k]=L2[i++];
}
else
{
a[k] = R[j];
c[k] = R1[j];
//w[k] = R2[j++];
++j;
inversion=inversion+(n1-i);
}
return inversion;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static long a,b,c,k;
static int bs(Long []a,long e,int i){
int r=i,l=0,mid=0,ans=-1;
while (r>=l){
mid=(r+l)>>1;
if (a[mid]>e){
ans=mid;
r=mid-1;
}
else l=mid+1;
}
return ans;
}
static ArrayList<Integer>[]adj;
static boolean []visited;
static void dfs(int node){
visited[node]=true;
for(int child:adj[node]){
if (!visited[child])dfs(child);
}
}
public static void main (String[]args) throws IOException {
Scanner in = new Scanner(System.in);
try(PrintWriter or = new PrintWriter(System.out)) {
int t =in.nextInt();
while (t-->0){
int n = in.nextInt(),k=in.nextInt();
String s= in.next();
StringBuilder d=new StringBuilder("RGBRGB");
ArrayList<String>a= new ArrayList<>();
HashSet<String>set= new HashSet<>();
while (d.length()<=k){
d.append("R");
d.append("G");
d.append("B");
}
d.append(d.toString());
d.append(d.toString());
for (int i = 0; i < 3; i++) {
a.add(d.substring(i,i+k));
}
int ans=Integer.MAX_VALUE;
outer:
for (int i = 0; i < n; i++) {
if (i+k<=n){
String f= s.substring(i,i+k);
if (set.contains(f))continue;
set.add(f);
for (String item:a) {
int min=0;
for (int l = 0; l < item.length(); l++) {
if (f.charAt(l)!=item.charAt(l))++min;
}
ans=Math.min(ans,min);
if (ans==0)break outer;
}
}
else break;
}
or.println(ans);
}
}
}
static int getlen(int r,int l,int a){
return (r-l+1+1)/(a+1);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++) {
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec) {
f *= 10;
}
}
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return first - o.first;
}
}
class Tempo {
int num;
int index;
public Tempo(int num, int index) {
this.num = num;
this.index = index;
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 84faa2691bbe1b65395d94fad823b7bd | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Task575D solver = new Task575D();
solver.solve(1, in, out);
out.close();
}
static class Task575D {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int q = in.nextInt();
char a[] = {'R', 'G', 'B'};
while (q-- > 0) {
int n = in.nextInt();
int k = in.nextInt();
char arr[] = in.nextString().toCharArray();
int i, ans = Integer.MAX_VALUE, j;
for (i = 0; i <= n - k; i++) {
for (j = 0; j < 3; j++) {
int v = j;
int cur = 0;
for (int l = i; l < i + k; l++) {
if (arr[l] != a[v])
cur++;
v++;
v %= 3;
}
if (cur < ans)
ans = cur;
}
}
out.println(ans);
}
}
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 820b89bcabc9615bf4aaf136b7cd9884 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class D7 {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int q = in.nextInt();
char []c = new char[]{'R', 'G', 'B'};
StringBuilder res = new StringBuilder();
for(int i = 0; i < q; i++){
int n = in.nextInt();
int k = in.nextInt();
in.nextLine();
String s = in.nextLine();
int ans = Integer.MAX_VALUE;
for (int j = 0; j < n - k + 1; j++){
for (int offset = 0; offset < 3; offset++){
int changes = 0;
for(int pos = 0; pos < k; pos++){
if(s.charAt(j + pos) != c[(offset + pos)%3]){
changes++;
}
}
ans = Math.min(ans, changes);
}
}
res.append(ans +"\n");
}
System.out.println(res.toString());
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 893fb13708c8d2d0eb4125be6f471cca | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.regex.*;
public class vk18
{
public static void main(String[]stp) throws Exception
{
Scanner scan=new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer(br.readLine());
int q=Integer.parseInt(st.nextToken()),i;
String []na={"RGB","GBR","BRG"};
while(q-- > 0)
{
st=new StringTokenizer(br.readLine());
int n=Integer.parseInt(st.nextToken()),k=Integer.parseInt(st.nextToken()),j=0,p=0,count=0,l=0,min=Integer.MAX_VALUE;
st=new StringTokenizer(br.readLine());
String s=st.nextToken();
for(i=0;i<=n-k;i++)
{
for(l=0;l<3;l++)
{
p=0;count=0;
for(j=i;j<i+k;j++)
{
if(s.charAt(j)!=na[l].charAt((p++)%3)) count++;
}
min=Math.min(min,count);
}
}
pw.println(min);
}
pw.flush();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 69d40ac6acc83aa79fa7f3e96e7e7bd4 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.math.RoundingMode;
import java.util.Scanner;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Division3 {
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out);
static int n,k;
static String s;
public static int dp(int idx,char before,int length){
if(length==k)return 0;
if(idx==n){
return (int)1e9;
}
int a;
if(before=='R'){
a= s.charAt(idx)=='G'?dp(idx+1,'G',length+1):1+dp(idx+1,'G',length+1);
}else if(before=='G'){
a=s.charAt(idx)=='B'?dp(idx+1,'B',length+1):1+dp(idx+1,'B',length+1);
}else {
a=s.charAt(idx)=='R'?dp(idx+1,'R',length+1):1+dp(idx+1,'R',length+1);
}
return a;
}
public static void main(String[] args) throws IOException {
int tests=sc.nextInt();
for(int test=0;test<tests;test++){
n=sc.nextInt();k=sc.nextInt();
s=sc.next();
int min=Integer.MAX_VALUE;
for(int i=0;i<s.length();i++){
int a=s.charAt(i)=='R'?0:1;
min=Math.min(min,a+dp(i+1,'R',1));
a=s.charAt(i)=='B'?0:1;
min=Math.min(min,a+dp(i+1,'B',1));
a=s.charAt(i)=='G'?0:1;
min=Math.min(min,a+dp(i+1,'G',1));
}
System.out.println(min);
}
}
static class pair<E1, E2> implements Comparable<pair> {
E1 x;
E2 y;
pair(E1 x, E2 y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(pair o) {
return x.equals(o.x) ? (Integer) y - (Integer) o.y : (Integer) x - (Integer) o.x;
}
@Override
public String toString() {
return x + " " + y;
}
public double pointDis(pair p1) {
return Math.sqrt(((Integer) y - (Integer) p1.y) * ((Integer) y - (Integer) p1.y) + ((Integer) x - (Integer) p1.x) * ((Integer) x - (Integer) p1.x));
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static <E> void print2D(E[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
pw.println(arr[i][j]);
}
}
}
public static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static long pow(long a, long pow) {
return pow == 0 ? 1 : a * pow(a, pow - 1);
}
public static long sumNum(long a) {
return a * (a + 1) / 2;
}
public static int gcd(int n1, int n2) {
return n2 == 0 ? n1 : gcd(n2, n1 % n2);
}
public static long factorial(long a) {
return a == 0 || a == 1 ? 1 : a * factorial(a - 1);
}
public static Double[] solveQuadratic(double a, double b, double c) {
double result = (b * b) - 4.0 * a * c;
double r1;
if (result > 0.0) {
r1 = ((double) (-b) + Math.pow(result, 0.5)) / (2.0 * a);
double r2 = ((double) (-b) - Math.pow(result, 0.5)) / (2.0 * a);
return new Double[]{r1, r2};
} else if (result == 0.0) {
r1 = (double) (-b) / (2.0 * a);
return new Double[]{r1, r1};
} else {
return new Double[]{null, null};
}
}
public static BigDecimal[] solveQuadraticBigDicimal(double aa, double bb, double cc) {
BigDecimal a = BigDecimal.valueOf(aa), b = BigDecimal.valueOf(bb), c = BigDecimal.valueOf(cc);
BigDecimal result = (b.multiply(b)).multiply(BigDecimal.valueOf(4).multiply(a.multiply(c)));
BigDecimal r1;
if (result.compareTo(BigDecimal.ZERO) > 0) {
r1 = (b.negate().add(bigSqrt(result)).divide(a.multiply(BigDecimal.valueOf(2))));
BigDecimal r2 = (b.negate().subtract(bigSqrt(result)).divide(a.multiply(BigDecimal.valueOf(2))));
return new BigDecimal[]{r1, r2};
} else if (result.compareTo(BigDecimal.ZERO) == 0) {
r1 = b.negate().divide(a.multiply(BigDecimal.valueOf(2)));
return new BigDecimal[]{r1, r1};
} else {
return new BigDecimal[]{null, null};
}
}
private static BigDecimal sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision) {
BigDecimal fx = xn.pow(2).add(c.negate());
BigDecimal fpx = xn.multiply(new BigDecimal(2));
BigDecimal xn1 = fx.divide(fpx, 2 * BigDecimal.valueOf(16).intValue(), RoundingMode.HALF_DOWN);
xn1 = xn.add(xn1.negate());
BigDecimal currentSquare = xn1.pow(2);
BigDecimal currentPrecision = currentSquare.subtract(c);
currentPrecision = currentPrecision.abs();
if (currentPrecision.compareTo(precision) <= -1) {
return xn1;
}
return sqrtNewtonRaphson(c, xn1, precision);
}
public static BigDecimal bigSqrt(BigDecimal c) {
return sqrtNewtonRaphson(c, new BigDecimal(1), new BigDecimal(1).divide(BigDecimal.valueOf(10).pow(16)));
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 06cd4685eb77896c658a5b74528a6793 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br;
static PrintWriter pr;
static int cin() throws Exception
{
return Integer.valueOf(br.readLine());
}
static int[] split() throws Exception
{
String[] cmd=br.readLine().split(" ");
int[] ans=new int[cmd.length];
for(int i=0;i<cmd.length;i++)
{
ans[i]=Integer.valueOf(cmd[i]);
}
return ans;
}
static long[] splitL() throws IOException
{
String[] cmd=br.readLine().split(" ");
long[] ans=new long[cmd.length];
for(int i=0;i<cmd.length;i++)
{
ans[i]=Long.valueOf(cmd[i]);
}
return ans;
}
static int sum(long n)
{
int ans=0;
while(n!=0)
{
ans=ans+(int)(n%10);
n=n/10;
}
return ans;
}
static long gcd(long x,long y)
{
if(x==0)
return y;
if(y==0)
return x;
if(x>y)
return gcd(x%y,y);
else
return gcd(x,y%x);
}
static int calc(char[]s,char[]pos,int st,int i,int k)
{
int cnt=0;
for(int j=i;j<(i+k);j++)
{
if(s[j]!=pos[(st+j-i)%3])
cnt++;
}
return cnt;
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
br=new BufferedReader(new InputStreamReader(System.in));
pr=new PrintWriter(new OutputStreamWriter(System.out));
int cases=cin();
while(cases!=0)
{
cases--;
int[]ar=split();
int n=ar[0];
int k=ar[1];
char[] s=br.readLine().toCharArray();
int ans=1000000000;
char[] pos=new char[] {'R','G','B'};
for(int i=0;i<=n-k;i++)
{
int x=calc(s,pos,0,i,k);
int y=calc(s,pos,1,i,k);
int z=calc(s,pos,2,i,k);
ans=Math.min(ans,Math.min(x,Math.min(y, z)));
}
System.out.println(ans);
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | d9fd65da6ab50db4eae25ad0e119240f | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class RGBSubstring {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class TaskA {
long mod = (long)(1000000007);
public void solve(int testNumber, InputReader in, PrintWriter out) {
while(testNumber-->0){
int n = in.nextInt();
int k = in.nextInt();
String s = in.next();
// String b[] = new String[3];
// b[0] = "";
// b[1] = "";
// b[2] = "";
// int x = n/3;
// int y = n%3;
// b[0] += "RGB";
// b[1] += "GBR";
// b[2] += "BRG";
// if(y!=0){
// b[0] += "RGB".substring(0 , y);
// b[1] += "GBR".substring(0 , y);
// b[2] += "BRG".substring(0 , y);
// }
int a[][] = new int[3][n+1];
for(int i=0;i<n;i++){
int j = i%3;
String b = "";
if(j == 0)
b = "RGB";
else if(j==1)
b = "GBR";
else
b = "BRG";
if(s.charAt(i) == b.charAt(0)){
a[0][i+1] = 1;
continue;
}
else if(s.charAt(i) == b.charAt(1)){
a[1][i+1] = 1;
continue;
}
else
a[2][i+1] = 1;
}
for(int i=1;i<=n;i++)
for(int j=0;j<3;j++)
a[j][i] += a[j][i-1];
int max = Integer.MIN_VALUE;
for(int i=0;i<3;i++){
for(int j=k;j<=n;j++)
max = Math.max(max , a[i][j] - a[i][j-k]);
}
out.println(k - max);
}
}
class Combine{
int value;
int delete;
Combine(int val , int delete){
this.value = val;
this.delete = delete;
}
}
class Sort2 implements Comparator<Combine>{
public int compare(Combine a , Combine b){
if(a.value > b.value)
return 1;
else if(a.value == b.value && a.delete>b.delete)
return 1;
else if(a.value == b.value && a.delete == b.delete)
return 0;
return -1;
}
}
public int lowerBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>=x)
return -1;
if(a.get(r)<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid-1)<x)
return mid-1;
else if(a.get(mid)>=x)
r = mid-1;
else if(a.get(mid)<x && a.get(mid+1)>=x)
return mid;
else if(a.get(mid)<x && a.get(mid+1)<x)
l = mid+1;
}
return mid;
}
public int upperBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>x)
return l;
if(a.get(r)<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid+1)>x)
return mid+1;
else if(a.get(mid)<=x)
l = mid+1;
else if(a.get(mid)>x && a.get(mid-1)<=x)
return mid;
else if(a.get(mid)>x && a.get(mid-1)>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.floor((Math.log(number) / Math.log(base)));
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
if(a%b==0)
return b;
return gcd(b , a%b);
}
public void print2d(int a[][] , PrintWriter out){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
out.print(a[i][j] + " ");
out.println();
}
out.println();
}
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
out.println();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 94e41a29a1da289f00becafa752349b6 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main1 {
static FastReader input = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int memo[][][];
static boolean v[][][];
static char c[] = { 'R', 'G', 'B' };
static char s[];
static int n, k;
static int solve(int i, int f, int next) {
if (f == k)
return 0;
if (i >= n || f > k)
return con.IINF;
if (v[i][f][next])
return memo[i][f][next];
v[i][f][next] = true;
int x = con.IINF;
int y = con.IINF;
y = solve(i + 1, f + 1, (next + 1) % 3);
if (s[i] != c[next])
y++;
if (f == 0)
x = solve(i + 1, f, next);
return memo[i][f][next] = Math.min(x, y);
}
public static void main(String[] args) throws IOException {
int t = input.nextInt();
while (t-- > 0) {
n = input.nextInt();
k = input.nextInt();
s = input.nextLine().toCharArray();
memo = new int[n + 5][k + 5][4];
v = new boolean[n + 5][k + 5][4];
out.println(Math.min(Math.min(solve(0, 0, 0), solve(0, 0, 1)), solve(0, 0, 2)));
}
out.flush();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
String str = "";
str = br.readLine();
return str;
}
}
static class con {
static int IINF = (int) 1e9;
static int _IINF = (int) -1e9;
static long LINF = (long) 1e15;
static long _LINF = (long) -1e15;
static double EPS = 1e-9;
}
static class Triple implements Comparable<Triple> {
int x;
int y;
int z;
Triple(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public int compareTo(Triple o) {
if (x == o.x && y == o.y)
return z - o.z;
if (x == o.x)
return y - o.y;
return x - o.x;
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (x == o.x)
return y - o.y;
return x - o.x;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
static void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
int r = i + (int) (Math.random() * (a.length - i));
int tmp = a[r];
a[r] = a[i];
a[i] = tmp;
}
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 91392a5623bfb6b30ac17ceb1e1308c8 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | /* Rajkin Hossain */
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class D{
FastInput k = new FastInput(System.in);
//FastInput k = new FastInput("C:/Users/rajkin.h/Desktop/input.txt");
FastOutput z = new FastOutput();
int n, K;
char [] y;
void startAlgo() {
int ans = Integer.MAX_VALUE;
for(int counter = 0; counter < 3; counter++) {
int count = 0;
char [] target;
if(counter == 0) {
target = "RGB".toCharArray();
}
else if(counter == 1) {
target = "GBR".toCharArray();
}
else {
target = "BRG".toCharArray();
}
for(int i = 0; i<K; i++) {
if(y[i] != target[i%3]) {
count++;
}
}
ans = Math.min(ans, count);
int start = 0;
for(int i = K; i<n; i++) {
if(y[i] != target[i%3]) {
count++;
}
if(y[start] != target[start%3]) {
count--;
}
ans = Math.min(ans, count);
start++;
}
}
z.println(ans);
}
void startProgram() {
int q = k.nextInt();
while(q-->0) {
n = k.nextInt();
K = k.nextInt();
y = k.next().toCharArray();
startAlgo();
}
z.flush();
System.exit(0);
}
public static void main(String [] args) throws IOException {
new Thread(null, new Runnable(){
public void run(){
try{
new D().startProgram();
}
catch(Exception e){
e.printStackTrace();
}
}
},"Main",1<<28).start();
}
/* MARK: FastInput and FastOutput */
class FastInput {
BufferedReader reader;
StringTokenizer tokenizer;
FastInput(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
}
FastInput(String path){
try {
reader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokenizer = null;
}
String next() {
return nextToken();
}
String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
boolean hasNext(){
try {
return reader.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.valueOf(nextToken());
}
double nextDouble() {
return Double.valueOf(nextToken());
}
}
class FastOutput extends PrintWriter {
FastOutput() {
super(new BufferedOutputStream(System.out));
}
public void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | bf6b5a8d59e8a51fbb959dcc0c4f5428 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | //package test;
import java.util.Arrays;
import java.util.Scanner;
public class starter
{
public static void main ( String args[] )
throws Exception
{
Scanner conio = new Scanner ( System.in ) ;
int ans ;
String god = "RGB" ;
int current ;
int x = conio.nextInt() ;
while ( x-- > 0 )
{
int n = conio.nextInt() ;
int k = conio.nextInt() ;
String line = conio.next() ;
ans = Integer.MAX_VALUE ;
for ( int i = 0 ; i < n - k + 1 ; ++i )
{
// generate offset
for ( int off = 0 ; off < 3 ; ++off )
{
current = 0 ;
for ( int j = 0 ; j < k ; ++j )
{
if ( line.charAt(i+j) != god.charAt((j+off)%3) )
++current ;
}
ans = Math.min( current , ans ) ;
}
}
System.out.println(ans) ;
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | e440a700fe393380ccff16161aa6acb3 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class ProblemD {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
InputReader scan = new InputReader(in);
int query = scan.nextInt();
for(int q=0;q<query;q++) {
int n = scan.nextInt();
int k = scan.nextInt();
String str = scan.next();
String ptrn = "RGB";
int ans = Integer.MAX_VALUE;
for(int offset=0;offset<3;offset++) {
int[] res = new int[n];
int curr = 0;
for(int i=0;i<n;i++) {
if(str.charAt(i)!=ptrn.charAt((i+offset)%3)) {
res[i]=1;
}
curr+=res[i];
if(i>=k) {
curr-=res[i-k];
}
if(i>=k-1) {
ans = Math.min(ans, curr);
}
}
}
System.out.println(ans);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | b3fbde648f5ecc1930f6651c2a187140 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prem_cse
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
D1RGBSubstringEasyVersion solver = new D1RGBSubstringEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class D1RGBSubstringEasyVersion {
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int q = sc.nextInt();
while (q-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
StringBuffer str = new StringBuffer(sc.next());
char[] c = {'R', 'G', 'B'};
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
StringBuffer sb3 = new StringBuffer();
for (int i = 0; i < k; ++i) {
sb1.append(c[i % 3]);
sb2.append(c[(i + 1) % 3]);
sb3.append(c[(i + 2) % 3]);
}
//System.out.println(sb1.length());
int min = Integer.MAX_VALUE;
min = Math.min(min, getMin(sb1, str));
min = Math.min(min, getMin(sb2, str));
min = Math.min(min, getMin(sb3, str));
out.println(min);
}
}
private int getMin(StringBuffer sb, StringBuffer str) {
int ans = Integer.MAX_VALUE;
for (int i = 0; i < str.length() - sb.length() + 1; i++) {
int min = 0;
for (int j = 0; j < sb.length(); j++) {
if (sb.charAt(j) != str.charAt(i + j)) ++min;
}
ans = Math.min(min, ans);
}
return ans;
}
}
static class FastReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 8ea798b9312f8fea160e40805c2afad2 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prem_cse
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
D1RGBSubstringEasyVersion solver = new D1RGBSubstringEasyVersion();
solver.solve(1, in, out);
out.close();
}
static class D1RGBSubstringEasyVersion {
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int q = sc.nextInt();
while (q-- > 0) {
int n = sc.nextInt();
int k = sc.nextInt();
char[] s = sc.next().toCharArray();
char[] c = {'R', 'G', 'B'};
int min = k;
for (int i = 0; i < 3; ++i) {
int mismatch = 0;
// prepare window
for (int j = 0; j < k; ++j) {
if (s[j] != c[(i + j) % 3])
++mismatch;
}
min = Math.min(mismatch, min);
// slideeeeeeee
for (int j = k; j < s.length; ++j) {
if (s[j] != c[(i + j) % 3]) ++mismatch;
if (s[j - k] != c[(i + j - k) % 3]) --mismatch;
min = Math.min(min, mismatch);
}
}
out.println(min);
}
}
}
static class FastReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 49a500c22f7d86b5f4ef609b0129a4df | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
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);
Task1196D1 solver = new Task1196D1();
solver.solve(1, in, out);
out.close();
}
static class Task1196D1 {
private static final int INF = (int) 2e9 + 7;
private InputReader in;
private OutputWriter out;
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.in = in;
this.out = out;
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int k = in.nextInt();
char[] a = in.nextCharArray(n, 1);
int[] sum = new int[n + 1];
int ans = INF;
char[] sample1 = {'B', 'R', 'G'};
char[] sample2 = {'R', 'G', 'B'};
char[] sample3 = {'G', 'B', 'R'};
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1];
if (a[i] != sample1[i % 3]) sum[i]++;
}
for (int i = k; i <= n; i++) {
ans = MaxMin.Min(ans, sum[i] - sum[i - k]);
}
sum = new int[n + 1];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1];
if (a[i] != sample2[i % 3]) sum[i]++;
}
for (int i = k; i <= n; i++) {
ans = MaxMin.Min(ans, sum[i] - sum[i - k]);
}
sum = new int[n + 1];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1];
if (a[i] != sample3[i % 3]) sum[i]++;
}
for (int i = k; i <= n; i++) {
ans = MaxMin.Min(ans, sum[i] - sum[i - k]);
}
out.println(ans);
}
}
}
static class OutputWriter {
private final PrintWriter out;
public OutputWriter(OutputStream outputStream) {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.out = new PrintWriter(writer);
}
public void close() {
out.close();
}
public void println(int i) {
out.println(i);
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
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() {
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 char[] nextCharArray(int length, int stIndex) {
char[] arr = new char[length + stIndex];
for (int i = stIndex; i < stIndex + length; i++)
arr[i] = nextCharacter();
return arr;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
}
static class MaxMin {
public static <T extends Comparable<T>> T Min(T x, T y) {
T min = x;
if (y.compareTo(min) < 0) min = y;
return min;
}
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 9f74b2399fc260b85f121c2c0ed90190 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.System.*;
import static java.lang.Math.*;
public class MainClass{
/*static boolean match(int a,int b)
{
if(b-a==1)
return true;
else if(b==1&&a==3)
return true;
return false;
}*/
public static void task(InputReader in){
//---------------------------------Solve here---------------------------------------------------------------------------------
int q=in.nextInt();
while(q-->0)
{
int n=in.nextInt();
int k=in.nextInt();
char c[]=in.nextString().toCharArray();
/*int a[]=new int[n];
int curr=1,max=1;
for(int i=0;i<n;i++)
{
if(c[i]=='R')
a[i]=1;
else if(c[i]=='G')
a[i]=2;
else
a[i]=3;
}
for(int i=1;i<n;i++)
{
if(match(a[i-1],a[i]))
{
curr++;
if(curr>max)
max=curr;
}
else
curr=1;
}
if(max>k)
out.println("0");
else
out.println(k-max);*/
String s[]=new String[3];
s[0]="RGB";
s[1]="GBR";
s[2]="BRG";
int max=0;
for(int j=0;j<3;j++)
{
int curr=0;
char x=s[j].charAt(0);
char y=s[j].charAt(1);
char z=s[j].charAt(2);
for(int p=0;p<=n-k;p++)
{
curr=0;
for(int i=p;i<p+k;i+=3)
{
if(c[i]==x)
curr++;
if(i+1<n&&i+1<p+k&&c[i+1]==y)
curr++;
if(i+2<n&&i+2<p+k&&c[i+2]==z)
curr++;
//out.println(j+" "+p+" "+i+" "+x+" "+y+" "+z+" "+c[i]+" "+"c[i+1]"+" "+"c[i+2]"+" "+curr);
}
if(curr>=max)
max=curr;
}
}
out.println(k-max);
//out.println("-------------------");
}
//----------------------------------------------------------------------------------------------------------------------------
}
public static void main(String[] args)throws IOException {
try{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
task(in);
out.close();
}
catch(NumberFormatException e){
System.out.println(e);
}
}
public static class InputReader {
/*
String-nextString()
int -nextInt()
double-nextDouble()
long -nextLong()
char -nextChar()
line -nextLine()
*/
private InputStream stream;
private byte[] buf = new byte[8192];
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 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 {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public char nextChar(){
return nextString().charAt(0);
}
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 nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | 7b4ac5fc9d3ba25bd9c5ad71389f8763 | train_004.jsonl | 1563978900 | The only difference between easy and hard versions is the size of the input.You are given a string $$$s$$$ consisting of $$$n$$$ characters, each character is 'R', 'G' or 'B'.You are also given an integer $$$k$$$. Your task is to change the minimum number of characters in the initial string $$$s$$$ so that after the changes there will be a string of length $$$k$$$ that is a substring of $$$s$$$, and is also a substring of the infinite string "RGBRGBRGB ...".A string $$$a$$$ is a substring of string $$$b$$$ if there exists a positive integer $$$i$$$ such that $$$a_1 = b_i$$$, $$$a_2 = b_{i + 1}$$$, $$$a_3 = b_{i + 2}$$$, ..., $$$a_{|a|} = b_{i + |a| - 1}$$$. For example, strings "GBRG", "B", "BR" are substrings of the infinite string "RGBRGBRGB ..." while "GR", "RGR" and "GGG" are not.You have to answer $$$q$$$ independent queries. | 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);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(),"Main",1<<26).start();
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int q=sc.nextInt();
char c[]={'R','G','B'};
while(q-->0)
{
int n=sc.nextInt();
int k=sc.nextInt();
String s=sc.next();
int count1=0,count2=1;
int max=Integer.MAX_VALUE;
boolean flag=true;
for(int i=0;i<=n-k;i++)
{
for(int l=0;l<3;l++){
count1=0;
count2=0;
while(count2<k)
{
if(((i+count2)<n) && (s.charAt(i+count2)!=c[(count2+l)%3]))
{
count1++;
}
count2++;
}
if(max>count1)
{
max=count1;
if(max==0)
{
flag=false;
break;
}
}
}
if(!flag)
{
break;
}
}
w.println(max);
}
w.close();
}
}
| Java | ["3\n5 2\nBGGGG\n5 3\nRBRGR\n5 5\nBBBRR"] | 2 seconds | ["1\n0\n3"] | NoteIn the first example, you can change the first character to 'R' and obtain the substring "RG", or change the second character to 'R' and obtain "BR", or change the third, fourth or fifth character to 'B' and obtain "GB".In the second example, the substring is "BRG". | Java 8 | standard input | [
"implementation"
] | 1aa8f887eb3b09decb223c71b40bb25b | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the length of the string $$$s$$$ and the length of the substring. The second line of the query contains a string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B'. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 1,500 | For each query print one integer — the minimum number of characters you need to change in the initial string $$$s$$$ so that after changing there will be a substring of length $$$k$$$ in $$$s$$$ that is also a substring of the infinite string "RGBRGBRGB ...". | standard output | |
PASSED | f5cc9ce714a8d537ab4e94976f62d0dd | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws IOException {
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(f.readLine());
int[] a=new int[n];
StringTokenizer tk=new StringTokenizer(f.readLine());
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(tk.nextToken());
}
int[] ps=new int[n+1];
ps[0]=0;
//System.out.println(0);
for(int i=1;i<n+1;i++){
ps[i]=ps[i-1]^a[i-1];
//System.out.println(ps[i]);
}
HashMap<Integer, Integer> hm=new HashMap<Integer, Integer>();
for(int i=0;i<n+1;i++){
int input=ps[i]+1;
if(i%2==0){
input*=-1;
}
if(hm.containsKey(input)){
hm.put(input,hm.get(input)+1);
}
else{
hm.put(input, 1);
}
}
long sum=0;
for(int x:hm.keySet()){
int num=hm.get(x);
sum+=(((long)num)*((long)(num-1)))/2;
}
System.out.println(sum);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 39f3e303278edb559ab2c0182b6c4989 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
public final class CFG {
public 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 static void main(String[] args) {
FastScanner sc = new FastScanner();
int n=sc.nextInt();
int i,j,l;
long k;
l=0;
k=0;
int[][] arr=new int[2][1<<20+2];
arr[1][0]=1;
int[] list=new int[n];
for(i=0;i<n;i++)
{
list[i]=sc.nextInt();
l^=list[i];
k+=arr[i%2][l];
arr[i%2][l]++;
}
System.out.println(k);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 9e5d2c808abfe5542f43245e156f1b4b | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[][] cnt = new int[2][(1 << 20) + 1];
cnt[1][0] = 1;
long ans = 0;
int cur = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
cur ^= Integer.parseInt(st.nextToken());
ans += cnt[i&1][cur]++;
}
System.out.println(ans);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 7ff8a52bb65b33628ae6ba5e4470687a | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.*;
import java.util.*;
public class C implements Runnable {
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
int[] arr = scn.nextIntArray(n);
int[] xor = new int[n + 1];
HashMap<Integer, Integer> odd = new HashMap<>();
HashMap<Integer, Integer> even = new HashMap<>();
odd.put(0, 1);
long ans = 0;
for(int i = 0; i < n; i++) {
xor[i + 1] = xor[i] ^ arr[i];
if(i % 2 == 0) {
ans += even.getOrDefault(xor[i + 1], 0);
even.merge(xor[i + 1], 1, Integer::sum);
} else {
ans += odd.getOrDefault(xor[i + 1], 0);
odd.merge(xor[i + 1], 1, Integer::sum);
}
}
out.println(ans);
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new C(), "Main", 1 << 26).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
int[] uniq(int[] arr) {
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | b6f775ef380ef242d653f1b808bb2e41 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
public class Solution{
static InputReader sc;
static PrintWriter wc;
public static void main(String[] args) {
sc=new InputReader(System.in);
wc=new PrintWriter(System.out);
int n=sc.nextInt();
int arr[]=new int[n];
int i;
HashMap<Integer,Integer> odd=new HashMap<>(),even=new HashMap<>();
for(i=0;i<n;i++){
arr[i]=sc.nextInt();
}
even.put(arr[0],1);
for(i=1;i<n;i++){
arr[i]=arr[i]^arr[i-1];
if(i%2==0){
if(even.containsKey(arr[i])) even.put(arr[i],even.get(arr[i])+1);
else even.put(arr[i],1);
}
else{
if(odd.containsKey(arr[i])) odd.put(arr[i],odd.get(arr[i])+1);
else odd.put(arr[i],1);
}
}
long res=0,temp;
for(Integer a:odd.keySet()){
//System.out.println(a+" "+odd.get(a));
temp=odd.get(a);
res+=(temp*(temp-1))/2;
}
for(Integer a:even.keySet()){
//System.out.println(a+" "+even.get(a));
temp=even.get(a);
res+=(temp*(temp-1))/2;
}
if(odd.containsKey(0)){
res+=odd.get(0);
}
wc.println(res);
wc.close();
}
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 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()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 4f78d3eefda04e87faca171533be4089 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long prefix[];
public static void main(String[] args)
{
OutputStream outputStream = System.out;
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(outputStream);
int n = sc.nextInt();
long a[] = new long[n+1];
prefix = new long[n+1];
prefix[0] = 0;
for(int i = 1; i <= n; i++)
{
a[i] = sc.nextLong();
prefix[i] = prefix[i-1]^a[i];
}
HashMap<Long,Long> even = new HashMap<>();
HashMap<Long,Long> odd = new HashMap<>();
long count = 0;
for(int i = 0; i <= n; i++)
{
if(i%2 == 0)
{
if(!even.containsKey(prefix[i]))
{
even.put(prefix[i],1L);
}
else
{
count += even.get(prefix[i]);
even.put(prefix[i],even.get(prefix[i])+1);
}
}
else
{
if(!odd.containsKey(prefix[i]))
{
odd.put(prefix[i],1L);
}
else
{
count += odd.get(prefix[i]);
odd.put(prefix[i],odd.get(prefix[i])+1);
}
}
}
out.println(count);
out.close();
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | cd1ece7c58cae90bab9c6a75dc364a2e | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long prefix[];
public static void main(String[] args)
{
OutputStream outputStream = System.out;
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(outputStream);
int n = sc.nextInt();
prefix = new long[n+1];
prefix[0] = 0;
for(int i = 1; i <= n; i++)
{
prefix[i] = prefix[i-1]^sc.nextLong();
}
HashMap<Long,Long> even = new HashMap<>();
HashMap<Long,Long> odd = new HashMap<>();
long count = 0;
for(int i = 0; i <= n; i++)
{
if(i%2 == 0)
{
if(!even.containsKey(prefix[i]))
{
even.put(prefix[i],1L);
}
else
{
count += even.get(prefix[i]);
even.put(prefix[i],even.get(prefix[i])+1);
}
}
else
{
if(!odd.containsKey(prefix[i]))
{
odd.put(prefix[i],1L);
}
else
{
count += odd.get(prefix[i]);
odd.put(prefix[i],odd.get(prefix[i])+1);
}
}
}
out.println(count);
out.close();
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 1013c48abf30dd6ed6b6fb3de86d3f76 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
final int M = (int)(1 << 22);
int[] a = new int[n + 5];
int[] pre = new int[n + 5];
int[][] mp = new int[M][2];
long ans = 0;
for(int i = 1; i <= n; ++i){
a[i] = in.nextInt();
pre[i] ^= a[i] ^ pre[i - 1];
}
for(int i = 0; i <= n; ++i){
if(i % 2 == 1) {
ans += mp[pre[i]][1];
mp[pre[i]][1]++;
}
else{
ans += mp[pre[i]][0];
mp[pre[i]][0]++;
}
}
System.out.println(ans);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 6479d18b4c4480f220c041396b1b8587 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = reader.nextInt();
}
int[][] cnt = new int[(1 << 20) + 1][2];
int x = 0;
long ans = 0;
cnt[0][1] = 1;
for(int i = 0; i < n; i++){
x = x ^ a[i];
ans += cnt[x][i % 2];
cnt[x][i % 2]++;
}
System.out.println(ans);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 959cd4a1ae910ce60db8e0396200831c | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Set;
import java.util.HashMap;
import java.util.TreeSet;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author MJ
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
long[] nums = new long[n+1];
long[] xors = new long[n+1];
xors[0] = 0;
HashMap<Long, Set<Integer>>[] map = new HashMap[2];
map[0] = new HashMap<>();
map[1] = new HashMap<>();
map[0].computeIfAbsent(xors[0], k -> new TreeSet<Integer>()).add(0);
for(int i = 1; i <= n; i++) {
nums[i] = in.nextLong();
xors[i] = nums[i] ^ xors[i - 1];
map[i % 2].computeIfAbsent(xors[i], k -> new TreeSet<Integer>()).add(i);
}
long ans = 0;
for(Long nn : map[0].keySet()) {
Set<Integer> set = map[0].get(nn);
ans += f(set.size());
}
for(Long nn : map[1].keySet()) {
Set<Integer> set = map[1].get(nn);
ans += f(set.size());
}
out.println(ans);
}
}
private static long f(long n){
return n*(n-1)/2;
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | ac43b34e18a9faae6956c6319b9d2a47 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
init();
int n = nextInt();
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
if (i > 0) a[i] ^= a[i - 1];
}
// System.out.println(Arrays.toString(a));
Map<Integer, Integer> odds = new HashMap<>();
Map<Integer, Integer> evens = new HashMap<>();
odds.put(0, 1);
for (int i = 0; i < a.length; i++) {
if (i % 2 == 1) {
if (odds.containsKey(a[i])) odds.put(a[i], odds.get(a[i]) + 1);
else odds.put(a[i], 1);
} else {
if (evens.containsKey(a[i])) evens.put(a[i], evens.get(a[i]) + 1);
else evens.put(a[i], 1);
}
}
long funnies = 0;
for (int num: odds.keySet()) funnies += ((long)odds.get(num)*(odds.get(num) - 1))/2;
for (int num: evens.keySet()) funnies += ((long)evens.get(num)*(evens.get(num) - 1))/2;
System.out.println(funnies);
}
//Input Reader
private static BufferedReader reader;
private static StringTokenizer tokenizer;
private static void init() {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
}
private static String next() throws IOException {
String read;
while (!tokenizer.hasMoreTokens()) {
read = reader.readLine();
if (read == null || read.equals(""))
return "-1";
tokenizer = new StringTokenizer(read);
}
return tokenizer.nextToken();
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
// private static long nextLong() throws IOException {
// return Long.parseLong(next());
// }
//
// // Get a whole line.
// private static String line() throws IOException {
// return reader.readLine();
// }
//
// private static double nextDouble() throws IOException {
// return Double.parseDouble(next());
// }
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | ff816b6f558d9154b42afd4fec7347e5 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
/* abhi2601 */
public class Q1 implements Runnable{
final static long mod = (long)1e9 + 7;
class pair{
int p,q;
pair(int p,int q){
this.p=p;
this.q=q;
}
}
int gcd(int a, int b){
if(b==0) return a;
return gcd(b,a%b);
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
long n=sc.nextLong(),sum=0L,c=0L;
HashMap<Long,Long>odd=new HashMap<>();
HashMap<Long,Long>even=new HashMap<>();
HashMap<Long,Long>iodd=new HashMap<>();
HashMap<Long,Long>ieven=new HashMap<>();
iodd.put(0L,-1L);
odd.put(0L,1L);
for(int i=0;i<n;i++){
sum=sum^sc.nextInt();
//w.println(sum);
if(iodd.containsKey(sum)){
if((i-iodd.get(sum))%2L==0){
if(odd.containsKey(sum)){
c+=odd.get(sum);
odd.put(sum,odd.get(sum)+1);
}
else odd.put(sum,1L);
}
else{
if(ieven.containsKey(sum)){
if(even.containsKey(sum)){
c+=even.get(sum);
even.put(sum,even.get(sum)+1);
}
else even.put(sum,1L);
}
else{
ieven.put(sum,(long)i);
even.put(sum,1L);
}
}
}
else{
iodd.put(sum,(long)i);
odd.put(sum,1L);
}
}
w.println(c);
w.close();
}
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 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()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Q1(),"q1",1<<26).start();
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 5a37f1123adc8e1d7d1933ac11395e6d | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes |
/*
USER: caoash3
LANG: JAVA
TASK:
*/
import java.io.*;
import java.util.*;
public class relax {
public static void main(String[] args) throws IOException {
FastScanner br = new FastScanner();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
//BufferedReader br = new BufferedReader(new FileReader("X.in"));
//PrintWriter pw = new PrintWriter(new FileWriter("X.out"));
X solver = new X();
solver.solve(br, pw);
}
static class X {
public void solve(FastScanner br, PrintWriter pw) throws IOException {
int N = br.nextInt();
int[] in = new int[N];
for(int i = 0; i < N; i++) {
in[i] = br.nextInt();
}
int[] pre = new int[N+1];
pre[1] = in[0];
for(int i = 2; i < pre.length; i++) {
pre[i] = pre[i-1] ^ in[i-1];
}
//
// for(int i = 0; i < pre.length; i++) {
// pw.print(pre[i] + " ");
//
// }
// pw.println();
long[][] num = new long[1 << 20][2];
for(int i = 0; i < pre.length; i++) {
if(i % 2 == 0) {
num[pre[i]][0]++;
}
else {
num[pre[i]][1]++;
}
}
long ans = 0;
for(int i = 0; i < num.length; i++) {
long M = num[i][0];
long T = num[i][1];
if(M == 2) {
ans++;
}
else if(M > 2) {
ans += ((M-1) * (M)) / 2;
}
if(T == 2) {
ans++;
}
else if(T > 2) {
ans += ((T-1) * (T)) / 2;
}
}
pw.println(ans);
pw.close();
}
}
//fastscanner class
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | fb374fb7efc2974eb1702dae88d35d30 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++){
a[i] = reader.nextInt();
}
int[][] cnt = new int[(1 << 20) + 1][2];
int x = 0;
long ans = 0;
cnt[0][1] = 1;
for(int i = 0; i < n; i++){
x = x ^ a[i];
ans += cnt[x][i % 2];
cnt[x][i % 2]++;
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 95b2640c45862795b36e67605e4c609d | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.geom.*;
import java.math.*;
import java.text.*;
import java.math.BigInteger.*;
import java.util.Arrays;
public class IMBACK
{
BufferedReader in;
StringTokenizer as;
int nums[],nums2[][];
int nums1[];
ArrayList < Integer > [] ar;
Map<Integer,Integer > map = new HashMap<Integer, Integer>();
public static void main (String[] args)
{
new IMBACK ();
}
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
public IMBACK ()
{
try
{
in = new BufferedReader (new InputStreamReader (System.in));
int a = nextInt();
nums = new int [a];
nums2 = new int[(int)Math.pow(2,20)][2];
nums[0] = nextInt();
nums2[nums[0]][0]++;
for(int x = 1;x<a;x++)
{
nums[x] = nextInt() ^ nums[x-1];
nums2[nums[x]][x%2]++;
}
long total = 0;
int far = 0;
for(int x = 0;x<a;x++)
{
if( x == 0)
total += (long)(nums2[0][(x+1)%2]);
else
total += (long)(nums2[nums[x-1]][(x+1)%2]);
nums2[nums[x]][x%2]--;
/// System.out.println(x + " " + total + " " + far);
}
System.out.println(total);
}
catch(IOException e)
{
}
}
String next () throws IOException
{
while (as == null || !as.hasMoreTokens ())
{
as = new StringTokenizer (in.readLine ().trim ());
}
return as.nextToken ();
}
long nextLong () throws IOException
{
return Long.parseLong (next ());
}
int nextInt () throws IOException
{
return Integer.parseInt (next ());
}
double nextDouble () throws IOException
{
return Double.parseDouble (next ());
}
String nextLine () throws IOException
{
return in.readLine ().trim ();
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 2fb2d955010fa7617739285ccfa217b2 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.*;
import java.util.*;
public class SahsaAndABitRelax {
public static void main (String [] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
int a [] = new int [n];
StringTokenizer st = new StringTokenizer(in.readLine());
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
int cnt [][] = new int [2][(int) Math.pow(2, 21)];
cnt[1][0]++;
int pref = 0;
long ans = 0;
for (int i = 0; i < n; i++) {
pref ^= a[i];
ans += cnt[i % 2][pref];
cnt[i % 2][pref]++;
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 6824af8068f73849b3cfbefa1ffb7f94 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes |
import java.util.*;
public class ACM {
public static void main(String[] args) {
ArrayList<Integer> sum = new ArrayList<>();
Map<Integer, Long> mp0 = new HashMap<>();
Map<Integer, Long> mp1 = new HashMap<>();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long ans = 0;
int x = sc.nextInt();
sum.add(x);
for (int i = 1; i < n; ++i) {
x = sc.nextInt();
sum.add(sum.get(i - 1) ^ x);
}
mp0.put(0,(long)1);
boolean f = true;
for (Integer integer : sum) {
// System.out.print(integer + " ");
if(f) {
if (mp1.containsKey(integer)) {
long preCnt = mp1.get(integer);
ans += preCnt;
mp1.put(integer, preCnt + 1);
} else {
mp1.put(integer, (long) 1);
}
} else {
if (mp0.containsKey(integer)) {
long preCnt = mp0.get(integer);
ans += preCnt;
mp0.put(integer, preCnt + 1);
} else {
mp0.put(integer, (long) 1);
}
}
f = !f;
}
System.out.print(ans);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 38cd70e89a731533a9c2efccc9564c53 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
static int cnt[][] = new int[2][(int) 1e7];
public static void solve(InputReader in) {
int n = in.readInt();
int a[] = new int[n];
for(int i = 0; i<n; i++)
a[i] = in.readInt();
cnt[1][0] = 1;
int x = 0;
long res = 0;
for(int i = 0; i<n; i++) {
x ^= a[i];
res += cnt[i%2][x];
cnt[i%2][x]++;
}
System.out.println(res);
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int t = 1;
while (t-- > 0)
solve(in);
}
}
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 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 long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 8bd43728917e656f5871016f643cd831 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes |
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class solution
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader in=new FastReader();
int i,j,sum=0,f=0,max=0;
long cnt=0;
int n=in.nextInt();
//String s= in.next();
int a[]=new int[n];
int cnte[]=new int[(int)Math.pow(2,20)];
int cnto[]=new int[(int)Math.pow(2,20)];
for(i=0;i<n;++i)
{
a[i]=in.nextInt();
}
cnte[0]=1;
int x=0;
for(i=1;i<=n;++i)
{
x=a[i-1]^x;
if(i%2==0)
{
cnt+=cnte[x];
cnte[x]++;
}
else
{
cnt+=cnto[x];
cnto[x]++;
}
}
System.out.println(cnt);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | c2999a88729098ceda2fbd366ef4de01 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 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.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Wolfgang Beyer
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int sum = 0;
Map<Integer, List<Integer>> map = new HashMap<>();
List<Integer> li = new ArrayList<>();
li.add(0);
map.put(0, li);
for (int i = 0; i < n; i++) {
sum ^= a[i];
if (map.containsKey(sum)) {
map.get(sum).add(i + 1);
} else {
List<Integer> list = new ArrayList<>();
list.add(i + 1);
map.put(sum, list);
}
}
long result = 0;
for (int k : map.keySet()) {
List<Integer> list = map.get(k);
long even = 0;
long odd = 0;
for (int i : list) {
if (i % 2 == 0) {
even++;
} else {
odd++;
}
}
if (even > 1) result += ((even - 1) * even) / 2;
if (odd > 1) result += ((odd - 1) * odd) / 2;
// result += even * odd;
}
out.println(result);
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
return ar;
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
//tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 2d0f6f6230b3d142cecd40508c331703 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.awt.List;
import java.io.*;
import java.lang.*;
public class c1 {
public static long mod = (long) Math.pow(10, 9) + 7;
public static InputReader in = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static int cnt = 0;
public static void main(String[] args) {
// Code starts..
int n = in.nextInt();
long[] a = new long[n];
for(int i=0; i<n; i++)
a[i] = in.nextLong();
long[] dp = new long[n+1];
HashMap<Long, Integer> ev = new HashMap<Long, Integer>();
HashMap<Long, Integer> od = new HashMap<Long, Integer>();
//ev.put(0L, 1);
for(int i=1; i<=n; i++)
{
dp[i] = dp[i-1] ^ a[i-1];
if(i%2==1)
{
if(od.get(dp[i])==null)
od.put(dp[i], 1);
else
od.put(dp[i], od.get(dp[i])+1);
}
else
{
if(ev.get(dp[i])==null)
ev.put(dp[i], 1);
else
ev.put(dp[i], ev.get(dp[i])+1);
}
}
long ans = 0;
for(int i=1; i<=n; i++)
{
if(i%2==1)
{
//od[dp[i]]--;
if(od.get(dp[i])!=null && od.get(dp[i])>1)
od.put(dp[i], od.get(dp[i])-1);
else
od.remove(dp[i]);
if(ev.get(dp[i-1])!=null)
ans += ev.get(dp[i-1]);
}
else
{
//od[dp[i]]--;
if(ev.get(dp[i])!=null && ev.get(dp[i])>1)
ev.put(dp[i], ev.get(dp[i])-1);
else
ev.remove(dp[i]);
if(od.get(dp[i-1])!=null)
ans += od.get(dp[i-1]);
}
/*
* pw.print(od); pw.print(ev); pw.println(ans);
*/
}
pw.print(ans);
// code ends...
pw.flush();
pw.close();
}
public static boolean flag = false;
public static long bs(boolean flag) {
long ll = 0;
long rl = (long) Math.pow(10, 9)+1;
long mid = 0;
long ans = -1;
while (rl - ll > 0) {
mid = (rl + ll) / 2;
cnt++;
System.out.println("> " + mid);
int ret = in.nextInt();
if (flag) {
if (ret == 1) {
ll = mid + 1;
} else {
rl = mid;
ans = mid;
}
}
}
return ans;
}
public static Comparator<Integer> cmp = new Comparator<Integer>() {
@Override
public int compare(Integer t1, Integer t2) {
return t2 - t1;
}
};
public static int lcs(char[] X, char[] Y, int m, int n) {
int L[][] = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
if (L[i][j] >= 100)
return 100;
}
}
return L[m][n];
}
public static void factSieve(int[] fact, long n) {
for (int i = 2; i <= n; i += 2)
fact[i] = 2;
for (int i = 3; i <= n; i += 2) {
if (fact[i] == 0) {
fact[i] = i;
for (int j = i; (long) j * i <= n; j++) {
fact[(int) ((long) i * j)] = i;
}
}
}
/*
* int k = 1000; while(k!=1) { System.out.print(a[k]+" "); k /= a[k];
*
* }
*/
}
public static int gcd(int p2, int p22) {
if (p2 == 0)
return (int) p22;
return gcd(p22 % p2, p2);
}
public static void nextGreater(long[] a, int[] ans) {
Stack<Integer> stk = new Stack<>();
stk.push(0);
for (int i = 1; i < a.length; i++) {
if (!stk.isEmpty()) {
int s = stk.pop();
while (a[s] < a[i]) {
ans[s] = i;
if (!stk.isEmpty())
s = stk.pop();
else
break;
}
if (a[s] >= a[i])
stk.push(s);
}
stk.push(i);
}
return;
}
public static void nextGreaterRev(long[] a, int[] ans) {
int n = a.length;
int[] pans = new int[n];
Arrays.fill(pans, -1);
long[] arev = new long[n];
for (int i = 0; i < n; i++)
arev[i] = a[n - 1 - i];
Stack<Integer> stk = new Stack<>();
stk.push(0);
for (int i = 1; i < n; i++) {
if (!stk.isEmpty()) {
int s = stk.pop();
while (arev[s] < arev[i]) {
pans[s] = n - i - 1;
if (!stk.isEmpty())
s = stk.pop();
else
break;
}
if (arev[s] >= arev[i])
stk.push(s);
}
stk.push(i);
}
// for(int i=0; i<n; i++)
// System.out.print(pans[i]+" ");
for (int i = 0; i < n; i++)
ans[i] = pans[n - i - 1];
return;
}
public static void nextSmaller(long[] a, int[] ans) {
Stack<Integer> stk = new Stack<>();
stk.push(0);
for (int i = 1; i < a.length; i++) {
if (!stk.isEmpty()) {
int s = stk.pop();
while (a[s] > a[i]) {
ans[s] = i;
if (!stk.isEmpty())
s = stk.pop();
else
break;
}
if (a[s] <= a[i])
stk.push(s);
}
stk.push(i);
}
return;
}
public static long lcm(int[] numbers) {
long lcm = 1;
int divisor = 2;
while (true) {
int cnt = 0;
boolean divisible = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 0) {
return 0;
} else if (numbers[i] < 0) {
numbers[i] = numbers[i] * (-1);
}
if (numbers[i] == 1) {
cnt++;
}
if (numbers[i] % divisor == 0) {
divisible = true;
numbers[i] = numbers[i] / divisor;
}
}
if (divisible) {
lcm = lcm * divisor;
} else {
divisor++;
}
if (cnt == numbers.length) {
return lcm;
}
}
}
public static long fact(long n) {
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}
public static long choose(long total, long choose) {
if (total < choose)
return 0;
if (choose == 0 || choose == total)
return 1;
return (choose(total - 1, choose - 1) + choose(total - 1, choose)) % mod;
}
public static int[] suffle(int[] a, Random gen) {
int n = a.length;
for (int i = 0; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static int[] sufflesort(int[] a) {
int n = a.length;
Random gen = new Random();
for (int i = 0; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
Arrays.sort(a);
return a;
}
public static int floorSearch(int arr[], int low, int high, int x) {
if (low > high)
return -1;
if (x > arr[high])
return high;
int mid = (low + high) / 2;
if (mid > 0 && arr[mid - 1] < x && x < arr[mid])
return mid - 1;
if (x < arr[mid])
return floorSearch(arr, low, mid - 1, x);
return floorSearch(arr, mid + 1, high, x);
}
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
public static ArrayList<Integer> primeFactorization(int n) {
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i = 2; i * i <= n; i++) {
while (n % i == 0) {
a.add(i);
n /= i;
}
}
if (n != 1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime, int n) {
for (int i = 1; i < n; i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i * i < n; i++) {
if (isPrime[i] == true) {
for (int j = (2 * i); j < n; j += i)
isPrime[j] = false;
}
}
}
public static int lowerbound(ArrayList<Long> net, long c2) {
int i = Collections.binarySearch(net, c2);
if (i < 0)
i = -(i + 2);
return i;
}
public static int lowerboundArray(int[] dis, int c2) {
int i = Arrays.binarySearch(dis, c2);
if (i < 0)
i = -(i + 2);
return i;
}
public static int uperbound(ArrayList<Integer> list, int c2) {
int i = Collections.binarySearch(list, c2);
if (i < 0)
i = -(i + 1);
return i;
}
public static int uperboundArray(int[] dis, int c2) {
int i = Arrays.binarySearch(dis, c2);
if (i < 0)
i = -(i + 1);
return i;
}
public static int GCD(int a, int b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
public static long GCD(long a, long b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
public static int d1;
public static int p1;
public static int q1;
public static void extendedEuclid(int A, int B) {
if (B == 0) {
d1 = A;
p1 = 1;
q1 = 0;
} else {
extendedEuclid(B, A % B);
int temp = p1;
p1 = q1;
q1 = temp - (A / B) * q1;
}
}
public static long LCM(long a, long b) {
return (a * b) / GCD(a, b);
}
public static int LCM(int a, int b) {
return (a * b) / GCD(a, b);
}
public static int binaryExponentiation(int x, int n) {
int result = 1;
while (n > 0) {
if (n % 2 == 1)
result = result * x;
x = x * x;
n = n / 2;
}
return result;
}
public static int[] countDer(int n) {
int der[] = new int[n + 1];
der[0] = 1;
der[1] = 0;
der[2] = 1;
for (int i = 3; i <= n; ++i)
der[i] = (i - 1) * (der[i - 1] + der[i - 2]);
// Return result for n
return der;
}
static long binomialCoeff(int n, int k) {
long C[][] = new long[n + 1][k + 1];
int i, j;
// Calculate value of Binomial Coefficient in bottom up manner
for (i = 0; i <= n; i++) {
for (j = 0; j <= Math.min(i, k); j++) {
// Base Cases
if (j == 0 || j == i)
C[i][j] = 1;
// Calculate value using previosly stored values
else
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
return C[n][k];
}
public static long binaryExponentiation(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1)
result = result * x;
x = (x % mod * x % mod) % mod;
n = n / 2;
}
return result;
}
public static int modularExponentiation(int x, int n, int M) {
int result = 1;
while (n > 0) {
if (n % 2 == 1)
result = (result * x) % M;
x = (x * x) % M;
n = n / 2;
}
return result;
}
public static long modularExponentiation(long x, long n, long M) {
long result = 1;
while (n > 0) {
if (n % 2 == 1)
result = (result * x) % M;
x = (x * x) % M;
n = n / 2;
}
return result;
}
public static long pow(long x, long n, long M) {
long result = 1;
while (n > 0) {
if (n % 2 == 1)
result = (result * x) % M;
x = (x * x) % M;
n = n / 2;
}
return result;
}
public static long modInverse(long q, long mod2) {
return modularExponentiation(q, mod2 - 2, mod2);
}
public static long sie(long A, long M) {
return modularExponentiation(A, M - 2, M);
}
public static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
static class pair implements Comparable<pair>
{
Long x, y;
pair(long bi, long wi) {
this.x = bi;
this.y = wi;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if (result == 0)
result = y.compareTo(o.y);
return result;
}
public String toString() {
return x + " " + y;
}
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 Long(x).hashCode() * 31 + new Long(y).hashCode();
}
}
static class tripletD implements Comparable<tripletD>
{
Double x, y, z;
tripletD(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(tripletD o) {
int result = x.compareTo(o.x);
if (result == 0) {
double x1 = o.x + o.y;
result = ((Double) x1).compareTo((double) (x + y));
}
return result;
}
public String toString() {
return x + " " + y + " " + z;
}
public boolean equals(Object o) {
if (o instanceof tripletD) {
tripletD p = (tripletD) o;
return p.x == x && p.y == y && p.z == z;
}
return false;
}
public int hashCode() {
return new Double(x).hashCode() * 31 + new Double(y).hashCode();
}
}
static class triplet implements Comparable<triplet> {
Integer x, y, z;
triplet(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(triplet o) {
int result = x.compareTo(o.x);
if (result == 0)
result = y.compareTo(o.y);
if (result == 0)
result = z.compareTo(o.z);
return result;
}
public boolean equlas(Object o) {
if (o instanceof triplet) {
triplet p = (triplet) o;
return x == p.x && y == p.y && z == p.z;
}
return false;
}
public String toString() {
return x + " " + y + " " + z;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode();
}
}
/*
* static class node implements Comparable<node>
*
* { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; }
*
* public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0)
* result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return
* result; }
*
* @Override public int compareTo(node o) { // TODO Auto-generated method stub
* return 0; } }
*/
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 166ac0e4202f6a3656c8aa7ac27d8d63 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.io.*;
/*
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Integer.parseInt(st.nextToken());
Long.parseLong(st.nextToken());
Scanner sc = new Scanner(System.in);
*/
public class Waw{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int[] a = new int[n];
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
a[i] = Integer.parseInt(st.nextToken());
}
long[] nb = new long[1048576];
int sum = 0;
int fin = 0;
for(int i=1;i<n;i+=2){
sum ^= a[i]^a[i-1];
nb[sum]++;
fin = i;
}
long rep = nb[0];
int rec = 0;
for(int i=1;i<n;i+=2){
if(i==fin) break;
rec ^= a[i]^a[i-1];
nb[rec]--;
rep += nb[rec];
}
Arrays.fill(nb,0);
sum = 0;
fin = 0;
for(int i=2;i<n;i+=2){
sum ^= a[i]^a[i-1];
nb[sum]++;
fin = i;
}
rep += nb[0];
rec = 0;
for(int i=2;i<n;i+=2){
if(i==fin) break;
rec ^= a[i]^a[i-1];
nb[rec]--;
rep += nb[rec];
}
System.out.println(rep);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | e410cccb3a55b727baad8fc6aa55bdb3 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static int n;
static int[] arr;
static long out;
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = p(br.readLine());
arr = new int[n];
String[] line = br.readLine().split(" ");
for(int i = 0; i < n; ++i) arr[i] = p(line[i]);
out = 0;
int[] pre = new int[n + 1];
pre[0] = 0;
for(int i = 1; i <= n; ++i){
pre[i] = arr[i - 1] ^ pre[i - 1];
}
HashMap<Integer, Long> mapEven = new HashMap<>(), mapOdd = new HashMap<>();
for(int i = 0; i <= n; ++i){
int curr = pre[i];
if(i % 2 == 0){
long add = mapEven.getOrDefault(curr, 0L);
out += add;
mapEven.put(curr, add + 1);
}
else{
long add = mapOdd.getOrDefault(curr, 0L);
out += add;
mapOdd.put(curr, add + 1);
}
}
System.out.println(out);
}
static int p(String in){
return Integer.parseInt(in);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 4acd12914892d85c7baae1bde330b17f | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
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;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CSashaAndABitOfRelax solver = new CSashaAndABitOfRelax();
solver.solve(1, in, out);
out.close();
}
static class CSashaAndABitOfRelax {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
long cur = 0;
HashMap<Long, Integer>[] map = new HashMap[2];
map[0] = new HashMap<>();
map[1] = new HashMap<>();
map[1].put(0L, 1);
long ans = 0;
for (int i = 0; i < n; ++i) {
cur ^= a[i];
if (i % 2 == 0) {
Integer count = map[0].get(cur);
if (count == null) count = 0;
ans += count;
++count;
map[0].put(cur, count);
} else {
Integer count = map[1].get(cur);
if (count == null) count = 0;
ans += count;
++count;
map[1].put(cur, count);
}
}
out.println(ans);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 6bc6c0bc5e0d4aed88bc4fa977adcb9d | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.*;
public class sdfafa {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[] a=new int[n], pref=new int[n+1];
/*
if a[l]^a[l+1]^...^a[m]=a[m+1]^a[m+2]^...a[r]
then it follows that a[l]^a[l+1]^...^a[r-1]^a[r]=0
and a[l]^a[l+1]^...^a[r-1]^a[r]=pref[r]^pref[l-1] because it all cancels out
so maintain count of how many times pref[i]=a particular value
for both odd and even indices so you can keep track of the size of the interval
since r-l+1 must be even
*/
for(int i=0;i<n;i++) {
a[i]=scan.nextInt();
pref[i+1]=pref[i]^a[i];
}
HashMap<Integer,Long> even=new HashMap<>();
HashMap<Integer,Long> odd=new HashMap<>();
long res=0L;
for(int i=0;i<=n;i++) {
int p=pref[i];
if(i%2==0) {
res+=even.getOrDefault(p,0L);
even.put(p,even.getOrDefault(p,0L)+1);
}
else {
res+=odd.getOrDefault(p,0L);
odd.put(p,odd.getOrDefault(p,0L)+1);
}
}
System.out.println(res);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 502f8f53085e108ca59dee74e71838a9 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static int k;
public static void main(String[] args) {
OutputStream outputStream = System.out;
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
int[] pre=new int[n+1];
for(int i=1;i<=n;i++) {
pre[i]=pre[i-1]^in.nextInt();
}
int[][] arr=new int[1<<20+1][2];
arr[0][0]=1;
long ans=0;
for(int i=1;i<=n;i++) {
ans+=arr[pre[i]][i%2];
arr[pre[i]][i%2]++;
}
out.println(ans);
}
}
static class InputReader
{
BufferedReader br;
StringTokenizer st;
public InputReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort(a, low, mid);
sort(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 08ed65e586f0458a641a8ca08797ce18 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 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.Map;
public class SashaAndABitOfRelax {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] a = Arrays.stream(br.readLine().split(" "))
.mapToInt(x -> Integer.parseInt(x)).toArray();
int[] aXor = new int[n];
Map<Integer, Integer> xorCountEven = new HashMap<>();
Map<Integer, Integer> xorCountOdd = new HashMap<>();
aXor[0] = a[0];
for (int i = 1; i < a.length; i++) {
aXor[i] = aXor[i - 1] ^ a[i];
}
xorCountOdd.put(0, 1);
for (int i = 0; i < aXor.length; i++) {
if (i % 2 == 0) {
xorCountEven.put(aXor[i], xorCountEven.getOrDefault(aXor[i], 0) + 1);
} else {
xorCountOdd.put(aXor[i], xorCountOdd.getOrDefault(aXor[i], 0) + 1);
}
}
long ans = 0;
for (Map.Entry<Integer, Integer> e : xorCountEven.entrySet()) {
ans += (long) (e.getValue()) * (e.getValue() - 1L);
}
for (Map.Entry<Integer, Integer> e : xorCountOdd.entrySet()) {
ans += (long) (e.getValue()) * (e.getValue() - 1L);
}
System.out.println(ans/2);
br.close();
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 1e8b78429f2bac203e87281909c56346 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* @Created by sbhowmik on 17/02/19
*/
public class SashaAndABitOfRelax {
static public long totalFunnyPairs(int a[], int n) {
int preC[] = new int[n];
preC[0] = a[0];
for(int i = 1; i < n; i++) {
preC[i] = preC[i-1] ^ a[i];
}
long count = 0;
int[] even = new int[(int)Math.ceil(Math.pow(2, 20))];
int[] odd = new int[(int)Math.ceil(Math.pow(2, 20))];
odd[0] = 1;
for(int i = 0; i < n; i++) {
if(i % 2 == 0) {
count += even[preC[i]];
even[preC[i]]++;
}
else {
count += odd[preC[i]];
odd[preC[i]]++;
}
}
return count;
}
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int i = 0;
int arr[] = new int[n];
while ( i < n) {
arr[i++] = scanner.nextInt();
}
System.out.println(totalFunnyPairs(arr, n));
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 13359884a22898a29548975c62851c58 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
/*
* 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 Qwert
*/
public class SashaAndBit {
static class FastScanner {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner() {
this(System.in);
}
public FastScanner(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] args) {
FastScanner f=new FastScanner();
int n=f.nextInt();
int a[]=new int[n];
int pre=0;
int ct[][]=new int[1048576][2];
long res=0;
ct[0][1]=1;
for(int i=0;i<n;i++)
a[i]=f.nextInt();
for(int i=0;i<n;i++){
pre^=a[i];
res+=ct[pre][i%2];
++ct[pre][i%2];
}
System.out.println(res);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 0643b99bc6f512d9fd47c3b5ea5f99e1 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.InputMismatchException;
public class C {
public static void main(String args[]) throws Exception {
int n = scn.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = scn.nextInt();
}
HashMap<Integer, ArrayList<Integer>> evenMap = new HashMap<>(), oddMap = new HashMap<>();
ArrayList<Integer> l =new ArrayList<>();
l.add(0);
evenMap.put(0,l);
int xor = 0;
long ans = 0;
for(int i=1; i<=n; i++){
xor ^= arr[i-1];
if(i%2 == 0 && evenMap.containsKey(xor)){
ans += evenMap.get(xor).size();
}else if(i%2 != 0 && oddMap.containsKey(xor)){
ans += oddMap.get(xor).size();
}
if(i%2 == 0){
if(!evenMap.containsKey(xor)){
ArrayList<Integer> list = new ArrayList<>();
list.add(i);
evenMap.put(xor,list);
}else{
ArrayList<Integer> list = evenMap.get(xor);
list.add(i);
evenMap.put(xor,list);
}
}else{
if(!oddMap.containsKey(xor)){
ArrayList<Integer> list = new ArrayList<>();
list.add(i);
oddMap.put(xor,list);
}else{
ArrayList<Integer> list = oddMap.get(xor);
list.add(i);
oddMap.put(xor,list);
}
}
}
out.println(ans);
out.close();
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return this.x + " [" + this.y + "]";
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Pair) {
Pair o = (Pair) obj;
return this.y == o.y;
}
return false;
}
}
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 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() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static InputReader scn = new InputReader(System.in);
public static PrintWriter out = new PrintWriter(System.out);
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 22ea2a59dc968088696d78c5c54b53de | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | //package baobab;
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
void solve() {
int n = io.nextInt();
int[] a = new int[n+1];
for (int i=1; i<=n; i++) {
a[i] = io.nextInt();
}
int max = (int)pow(2,20);
List<Integer>[][] xors = new ArrayList[max][2];
for (int i=0; i<max; i++) {
xors[i][0] = new ArrayList<>();
xors[i][1] = new ArrayList<>();
}
int xor = 0;
for (int i=0; i<=n; i++) {
xor ^= a[i];
int p = (i%2);
xors[xor][p].add(i);
}
long ans = 0;
for (xor=0; xor<max; xor++) {
ans += biCo(xors[xor][0].size(), 2);
ans += biCo(xors[xor][1].size(), 2);
}
io.println(ans);
}
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000001;
}
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
void draw(long[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/* Provides log(n) operations for:
* - Range query (sum, min or max)
* - Range update ("+8 to all values between indexes 4 and 94")
*/
int N;
long[] lazy;
long[] sum;
long[] min;
long[] max;
boolean supportSum;
boolean supportMin;
boolean supportMax;
public SegmentTree(int n) {
this(n, true, true, true);
}
public SegmentTree(int n, boolean supportSum, boolean supportMin, boolean supportMax) {
for (N=2; N<n;) N*=2;
this.lazy = new long[2*N];
this.supportSum = supportSum;
this.supportMin = supportMin;
this.supportMax = supportMax;
if (this.supportSum) this.sum = new long[2*N];
if (this.supportMin) this.min = new long[2*N];
if (this.supportMax) this.max = new long[2*N];
}
void modifyRange(long x, int a, int b) {
modifyRec(a, b, 1, 0, N-1, x);
}
void setRange() {
//TODO
}
long getSum(int a, int b) {
return querySum(a, b, 1, 0, N-1);
}
long getMin(int a, int b) {
return queryMin(a, b, 1, 0, N-1);
}
long getMax(int a, int b) {
return queryMax(a, b, 1, 0, N-1);
}
private long querySum(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return 0;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
int count = wantedRight - wantedLeft + 1;
return sum[i] + count * lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = querySum(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = querySum(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return left + right;
}
private long queryMin(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return Long.MAX_VALUE;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
return min[i] + lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = queryMin(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = queryMin(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return min(left, right);
}
private long queryMax(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return Long.MIN_VALUE;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
return max[i] + lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = queryMax(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = queryMax(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return max(left, right);
}
private void modifyRec(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight, long value) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
lazy[i] += value;
return;
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
modifyRec(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1, value);
modifyRec(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight, value);
if (supportSum) sum[i] += value * (min(actualRight, wantedRight) - max(actualLeft, wantedLeft) + 1);
if (supportMin) min[i] = min(min[2*i] + lazy[2*i], min[2*i+1] + lazy[2*i+1]);
if (supportMax) max[i] = max(max[2*i] + lazy[2*i], max[2*i+1] + lazy[2*i+1]);
}
private void propagate(int i, int actualLeft, int actualRight) {
lazy[2*i] += lazy[i];
lazy[2*i+1] += lazy[i];
if (supportSum) sum[i] += lazy[i] * (actualRight - actualLeft + 1);
if (supportMin) min[i] += lazy[i];
if (supportMax) max[i] += lazy[i];
lazy[i] = 0;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
/* Trees only. */
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
int n;
List<Integer>[] edges;
public Graph(int n) {
this.n = n;
edges = new ArrayList[n+1];
for (int i=1; i<=n; i++) edges[i] = new ArrayList<>();
}
void addBiEdge(int a, int b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(int from, int to) {
edges[from].add(to);
}
/*********** Strongly Connected Components (Kosaraju) ****************/
ArrayList<Integer>[] bacw;
public int getCount() {
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
bacw[i] = new ArrayList<Integer>();
}
for (int a=1; a<=n; a++) {
for (int b : edges[a]) {
bacw[b].add(a);
}
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : edges[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
/************************* Topological Order **********************/
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
int[] vis;
List<Integer> topoAns;
// Returns nodes in topological order or null if cycle was found
public List<Integer> topoSort() {
topoAns = new ArrayList<>();
vis = new int[n+1];
for (int i=1; i<=n; i++) {
if (!topoDFS(i)) return null;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(int curr) {
Integer status = vis[curr];
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis[curr] = INPROGRESS;
for (int next : edges[curr]) {
if (!topoDFS(next)) return false;
}
vis[curr] = FINISHED;
topoAns.add(curr);
return true;
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r, boolean countBorderAsInside) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return countBorderAsInside;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long pow(long base, int exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
if (exp % 2 != 0) ans *= base;
return ans;
}
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
int invertNumber(int a, int k) {
// Inverts the binary representation of a, using only k last bits e.g. 01101 -> 10010
int inv32k = ~a;
int mask = 1;
for (int i = 1; i < k; ++i) mask |= mask << 1;
return inv32k & mask;
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
int editDistance(String a, String b) {
a = "#"+a;
b = "#"+b;
int n = a.length();
int m = b.length();
int[][] dp = new int[n+1][m+1];
for (int y=0; y<=n; y++) {
for (int x=0; x<=m; x++) {
if (y == 0) dp[y][x] = x;
else if (x == 0) dp[y][x] = y;
else {
int e1 = dp[y-1][x] + 1;
int e2 = dp[y][x-1] + 1;
int e3 = dp[y-1][x-1] + (a.charAt(y-1) != b.charAt(x-1) ? 1 : 0);
dp[y][x] = min(e1, e2, e3);
}
}
}
return dp[n][m];
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 5592cee85473b407fdaa5b51506657f4 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | //package baobab;
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
void solve() {
long ans = 0;
int n = io.nextInt();
int[] a = new int[n+1];
for (int i=1; i<=n; i++) {
a[i] = io.nextInt();
}
int max = (int)pow(2,20);
int[][] xors = new int[max][2];
int xor = 0;
for (int i=0; i<=n; i++) {
xor ^= a[i];
ans += xors[xor][i%2]++;
}
io.println(ans);
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000001;
}
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
void draw(long[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/* Provides log(n) operations for:
* - Range query (sum, min or max)
* - Range update ("+8 to all values between indexes 4 and 94")
*/
int N;
long[] lazy;
long[] sum;
long[] min;
long[] max;
boolean supportSum;
boolean supportMin;
boolean supportMax;
public SegmentTree(int n) {
this(n, true, true, true);
}
public SegmentTree(int n, boolean supportSum, boolean supportMin, boolean supportMax) {
for (N=2; N<n;) N*=2;
this.lazy = new long[2*N];
this.supportSum = supportSum;
this.supportMin = supportMin;
this.supportMax = supportMax;
if (this.supportSum) this.sum = new long[2*N];
if (this.supportMin) this.min = new long[2*N];
if (this.supportMax) this.max = new long[2*N];
}
void modifyRange(long x, int a, int b) {
modifyRec(a, b, 1, 0, N-1, x);
}
void setRange() {
//TODO
}
long getSum(int a, int b) {
return querySum(a, b, 1, 0, N-1);
}
long getMin(int a, int b) {
return queryMin(a, b, 1, 0, N-1);
}
long getMax(int a, int b) {
return queryMax(a, b, 1, 0, N-1);
}
private long querySum(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return 0;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
int count = wantedRight - wantedLeft + 1;
return sum[i] + count * lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = querySum(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = querySum(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return left + right;
}
private long queryMin(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return Long.MAX_VALUE;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
return min[i] + lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = queryMin(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = queryMin(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return min(left, right);
}
private long queryMax(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return Long.MIN_VALUE;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
return max[i] + lazy[i];
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
long left = queryMax(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1);
long right = queryMax(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight);
return max(left, right);
}
private void modifyRec(int wantedLeft, int wantedRight, int i, int actualLeft, int actualRight, long value) {
if (wantedLeft > actualRight || wantedRight < actualLeft) {
return;
}
if (wantedLeft == actualLeft && wantedRight == actualRight) {
lazy[i] += value;
return;
}
if (lazy[i] != 0) propagate(i, actualLeft, actualRight);
int d = (actualRight - actualLeft + 1) / 2;
modifyRec(wantedLeft, min(actualLeft+d-1, wantedRight), 2*i, actualLeft, actualLeft+d-1, value);
modifyRec(max(actualLeft+d, wantedLeft), wantedRight, 2*i+1, actualLeft+d, actualRight, value);
if (supportSum) sum[i] += value * (min(actualRight, wantedRight) - max(actualLeft, wantedLeft) + 1);
if (supportMin) min[i] = min(min[2*i] + lazy[2*i], min[2*i+1] + lazy[2*i+1]);
if (supportMax) max[i] = max(max[2*i] + lazy[2*i], max[2*i+1] + lazy[2*i+1]);
}
private void propagate(int i, int actualLeft, int actualRight) {
lazy[2*i] += lazy[i];
lazy[2*i+1] += lazy[i];
if (supportSum) sum[i] += lazy[i] * (actualRight - actualLeft + 1);
if (supportMin) min[i] += lazy[i];
if (supportMax) max[i] += lazy[i];
lazy[i] = 0;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
/* Trees only. */
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
int n;
List<Integer>[] edges;
public Graph(int n) {
this.n = n;
edges = new ArrayList[n+1];
for (int i=1; i<=n; i++) edges[i] = new ArrayList<>();
}
void addBiEdge(int a, int b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(int from, int to) {
edges[from].add(to);
}
/*********** Strongly Connected Components (Kosaraju) ****************/
ArrayList<Integer>[] bacw;
public int getCount() {
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
bacw[i] = new ArrayList<Integer>();
}
for (int a=1; a<=n; a++) {
for (int b : edges[a]) {
bacw[b].add(a);
}
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : edges[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
/************************* Topological Order **********************/
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
int[] vis;
List<Integer> topoAns;
// Returns nodes in topological order or null if cycle was found
public List<Integer> topoSort() {
topoAns = new ArrayList<>();
vis = new int[n+1];
for (int i=1; i<=n; i++) {
if (!topoDFS(i)) return null;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(int curr) {
Integer status = vis[curr];
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis[curr] = INPROGRESS;
for (int next : edges[curr]) {
if (!topoDFS(next)) return false;
}
vis[curr] = FINISHED;
topoAns.add(curr);
return true;
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r, boolean countBorderAsInside) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return countBorderAsInside;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long pow(long base, int exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
if (exp % 2 != 0) ans *= base;
return ans;
}
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
int invertNumber(int a, int k) {
// Inverts the binary representation of a, using only k last bits e.g. 01101 -> 10010
int inv32k = ~a;
int mask = 1;
for (int i = 1; i < k; ++i) mask |= mask << 1;
return inv32k & mask;
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
int editDistance(String a, String b) {
a = "#"+a;
b = "#"+b;
int n = a.length();
int m = b.length();
int[][] dp = new int[n+1][m+1];
for (int y=0; y<=n; y++) {
for (int x=0; x<=m; x++) {
if (y == 0) dp[y][x] = x;
else if (x == 0) dp[y][x] = y;
else {
int e1 = dp[y-1][x] + 1;
int e2 = dp[y][x-1] + 1;
int e3 = dp[y-1][x-1] + (a.charAt(y-1) != b.charAt(x-1) ? 1 : 0);
dp[y][x] = min(e1, e2, e3);
}
}
}
return dp[n][m];
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 7640a3168b5d5f6fb3e356e02e055d36 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.*;
import java.util.*;
public class tr2 {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int []a=new int[n];
int []pre=new int[n+1];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
pre[i+1]=a[i]^pre[i];
}
HashMap<Integer,Integer> even=new HashMap();
HashMap<Integer,Integer> odd=new HashMap();
long ans=0;
for(int i=0;i<pre.length;i++) {
if(i%2==0) {
if(even.containsKey(pre[i])) {
ans+=even.get(pre[i]);
even.put(pre[i], even.get(pre[i])+1);
}
else {
even.put(pre[i],1);
}
}
else if(i%2==1) {
if(odd.containsKey(pre[i])) {
ans+=odd.get(pre[i]);
odd.put(pre[i], odd.get(pre[i])+1);
}
else {
odd.put(pre[i],1);
}
}
}
out.println(ans);
out.flush();
}
static int gcd(int a,int b) {
if(b==0) {
return a;
}
return gcd(b,a%b);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 47ae4afd42ef2b0a21cbfb3139445a78 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Soln1 {
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
Soln1 solution = new Soln1();
solution.solve();
solution.close();
}
void solve() {
int n=readInt();
int[]a=readIntArr();
Map<Integer,Integer>prevO=new HashMap<>();
Map<Integer,Integer>prevE=new HashMap<>();
prevO.put(0,1);
int xrc=a[0];
prevE.put(a[0],1);
long num=0;
for(int i=1;i<n;i++) {
xrc^=a[i];
if(i%2==1) {
if(prevO.containsKey(xrc)) {
int np=prevO.get(xrc);
num+=np;
prevO.put(xrc, np+1);
}
else prevO.put(xrc, 1);
}else {
if(prevE.containsKey(xrc)) {
int np=prevE.get(xrc);
num+=np;
prevE.put(xrc, np+1);
}
else prevE.put(xrc, 1);
}
}
pw.println(num);
}
void close() {
pw.close();
}
String readLine() {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
String readString() {
return readLine();
}
public long readlong() {
return Long.parseLong(readLine());
}
public int readInt() {
return Integer.parseInt(readLine());
}
String[] stringArray() {
StringTokenizer st = new StringTokenizer(readLine());
int n = st.countTokens();
String ret[] = new String[n];
for (int i = 0; i < n; i++) {
ret[i] = st.nextToken();
}
return ret;
}
public int[] readIntArr() {
String[] str = stringArray();
int arr[] = new int[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Integer.parseInt(str[i]);
return arr;
}
public double[] readDoubleArr() {
String[] str = stringArray();
double arr[] = new double[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Double.parseDouble(str[i]);
return arr;
}
public long[] readLongArr() {
String[] str = stringArray();
long arr[] = new long[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Long.parseLong(str[i]);
return arr;
}
public double readDouble() {
return Double.parseDouble(readLine());
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 25aa55fd5642e70b8515ff045037d931 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 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.
*/
import java.util.*;
/**
*
* @author arvin
*/
public class Sasha_relax {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
int a1[]=new int[3000000];
int a2[]=new int[3000000];
String abc[]=sc.nextLine().split(" ");
int b[]=new int[n];
for(int i=0;i<n;i++)
b[i]=Integer.parseInt(abc[i]);
int x=0;
a1[0]++;
for(int i=0;i<n;i++)
{
x=x^b[i];
if((i&1)==1)
a1[x]++;
else
a2[x]++;
//System.out.println(x+" "+a1[x]+" "+a2[x]);
}
long ans=0l;
for(int i=0;i<3000000;i++)
{
long mn=((long)a1[i]*(a1[i]-1));
if(a1[i]>1)
ans+=(mn/2);
mn=(long)a2[i]*(a2[i]-1);
if(a2[i]>1)
ans+=(mn/2);
/*if(a1[i]>0 && a2[i]>0)
{
ans+=(a1[i]*a2[i]);
System.out.println(x+" "+a1[i]+" "+a2[i]);
}*/
}
System.out.println(ans);
sc.close();
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 0103a36c52940cc2694da60b01bbe112 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class C_Round_539_Div2 {
public static long MOD = 998244353;
static long[][][]dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[]data = new int[n];
for(int i = 0; i < n; i++){
data[i] = in.nextInt();
}
int[][]map = new int[1<<20][2];
map[0][1]++;
int last = 0;
long result = 0;
for(int i = 0; i < n; i++){
last ^= data[i];
result += map[last][(i % 2)];
//System.out.println(last + " " + map[last]);
map[last][i % 2]++;
}
out.println(result);
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 86f8c561a5cefe268e31dc60f1971917 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | /* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++)
a[i]=s.nextInt();
int x=0;
int[][] c=new int[2][1<<20+3];
c[1][0]=1;
// c[0][0]=1;
long res=0;
for(int i=0;i<n;i++){
x^=a[i];
res+=c[i%2][x];
++c[i%2][x];
}
System.out.println(res);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | dd752d07dba0c0c8051a7ddb5179e640 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.awt.*;
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for (int i=0;i<n;i++)a[i]=sc.nextInt();
int xor[][]=new int[2][(1<<20)+1];int x=0;xor[1][0]=1;
long res=0;
for (int i=0;i<n;i++){
x^=a[i];
res+=xor[i%2][x];
xor[i%2][x]++;
}
System.out.println(res);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 5406546106d22f044ebf69a05b5fcad0 | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class quec {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
int[] pref = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
}
pref[0] = arr[0];
HashMap<Integer, Integer> odd = new HashMap<>();
HashMap<Integer, Integer> even = new HashMap<>();
even.put(arr[0], 1);
odd.put(0, 1);
long ans=0;
for (int i = 1; i < n; i++) {
pref[i] = pref[i - 1] ^ arr[i];
if (i % 2 == 0) {
if(even.containsKey(pref[i])){
ans+=even.get(pref[i]);
}
even.put(pref[i],even.getOrDefault(pref[i],0)+1);
}
else {
if(odd.containsKey(pref[i])){
ans+=odd.get(pref[i]);
}
odd.put(pref[i],odd.getOrDefault(pref[i],0)+1);
}
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | d0efc386d9b83ef96485bacd0ad22d9e | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.StringTokenizer;
/**
* Created by timur on 28.03.15.
*/
public class TaskC {
boolean eof;
BufferedReader br;
StringTokenizer st;
PrintWriter out;
public static void main(String[] args) throws IOException {
new TaskC().run();
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return "-1";
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
return br.readLine();
}
void run() throws IOException {
InputStream input = System.in;
PrintStream output = System.out;
try {
File f = new File("a.in");
if (f.exists() && f.canRead()) {
input = new FileInputStream(f);
output = new PrintStream("a.out");
}
} catch (Throwable e) {
}
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(output);
solve();
br.close();
out.close();
}
class Pair implements Comparable<Pair> {
int l, r, ind;
public Pair(int l, int r, int ind) {
this.l = l;
this.r = r;
this.ind = ind;
}
@Override
public int compareTo(Pair o) {
int r = l - o.l;
if (r == 0)
r = o.r - this.r;
return r;
}
}
long factPow(long n, long k) {
long res = 0;
while (n > 0) {
n /= k;
res += n;
}
return res;
}
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
void solve() {
int n = nextInt();
int[] a = new int[n];
int[] x = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
x[0] = a[0];
for (int i = 1; i < n; i++) {
x[i] = x[i - 1] ^ a[i];
}
int u = x[ n - 1];
HashMap<Integer, Long> sufC = new HashMap<>();
HashMap<Integer, Long> sufN = new HashMap<>();
sufC.put(0, 1L);
long ans = 0;
HashMap<Integer, Long> cur, ne;
int curSuf = 0;
for (int prlen = n - 3; prlen >= 0; prlen--) {
if ((prlen + 1) % 2 == n % 2) {
cur = sufC;
ne = sufN;
} else {
cur = sufN;
ne = sufC;
}
ans += cur.getOrDefault(x[prlen] ^ u, 0L);
curSuf = curSuf ^ a[prlen + 2];
if (ne.containsKey(curSuf)) {
ne.put(curSuf, ne.get(curSuf) + 1);
} else {
ne.put(curSuf, 1L);
}
}
if (n % 2 == 0) {
ans += sufC.getOrDefault(u, 0L);
} else {
ans += sufN.getOrDefault(u, 0L);
}
out.print(ans);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | 357549298f2b4c343c9ce347e69bea6a | train_004.jsonl | 1550334900 | Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task. | 256 megabytes |
import java.util.*;
import java.io.*;
public class SashaandaBitofRelax {
// https://codeforces.com/contest/1113/problem/C
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("SashaandaBitofRelax"));
int n = Integer.parseInt(in.readLine());
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(in.readLine());
for (int i=0; i<n; i++) arr[i] = Integer.parseInt(st.nextToken());
HashMap<Integer, Long> even = new HashMap<>();
HashMap<Integer, Long> odd = new HashMap<>();
odd.put(0, 1l);
int curxor = 0;
long ans=0;
for (int i=0; i<n; i++) {
curxor ^= arr[i];
if (i%2==1 && odd.containsKey(curxor)) {
ans+=odd.get(curxor);
}
if (i%2==0 && even.containsKey(curxor)) {
ans+=even.get(curxor);
}
if (i%2==0) {
even.put(curxor, even.getOrDefault(curxor, 0l)+1);
}
else {
odd.put(curxor, odd.getOrDefault(curxor, 0l)+1);
}
}
System.out.println(ans);
}
} | Java | ["5\n1 2 3 4 5", "6\n3 2 2 3 7 6", "3\n42 4 2"] | 1 second | ["1", "3", "0"] | NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs. | Java 8 | standard input | [] | e9cf26e61ebff8ad8d3b857c429d3aa9 | The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself. | 1,600 | Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number. | standard output | |
PASSED | a7776cdfa805d16322e3a6b7c7091d74 | train_004.jsonl | 1350370800 | There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum. | 256 megabytes | import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
private int n;
private int[] a;
private int m;
private int[] b;
int[] c;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
a = Utils.readIntArray(in, n);
m = in.nextInt();
b = Utils.readIntArray(in, m);
int min;
if (a[0] != b[0]) {
int turns = solve(a[0]);
int turns2 = solve(b[0]);
if (turns < turns2) {
solve(a[0]);
}
min = Math.min(turns, turns2);
} else {
min = solve(a[0]);
}
for (int i = 0; i < n + m; ++i) {
out.print(list[i] + 1);
out.print(" ");
}
out.println();
out.println(min);
getTurns();
for (int i = 0; i < min; ++i) {
out.print(opers.get(i) + " ");
}
out.println();
}
int solve(int begin) {
int ptr1 = 0, ptr2 = 0;
list = new int[n + m];
c = new int[n + m];
int ptr = 0;
int cur = begin;
while (ptr1 < n || ptr2 < m) {
while (ptr1 < n && a[ptr1] == cur) {
c[ptr] = a[ptr1];
list[ptr++] = ptr1;
++ptr1;
}
while (ptr2 < m && b[ptr2] == cur) {
c[ptr] = b[ptr2];
list[ptr++] = ptr2 + n;
++ptr2;
}
cur = 1 - cur;
}
int switches = 0;
for (int i = 1; i < n + m; ++i) {
if (c[i] != c[i-1]) {
++switches;
}
}
if (c[n + m - 1] == 1) {
++switches;
}
return switches;
}
int[] list;
List<Integer> opers;
public void getTurns() {
opers = new ArrayList<Integer>();
for (int i = 1; i < n + m; ++i) {
if (c[i] != c[i-1]) {
opers.add(i);
}
}
if (c[n + m - 1] == 1) {
opers.add(n + m);
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
class Utils {
public static int[] readIntArray(InputReader in, int n) {
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
return a;
}
}
| Java | ["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"] | 2 seconds | ["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"] | null | Java 8 | input.txt | [
"constructive algorithms",
"greedy"
] | f1a312a21d600cf9cfff4afeca9097dc | The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost. | 2,000 | In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105. | output.txt | |
PASSED | 11e7a25acc42d4ad256116a61881505b | train_004.jsonl | 1350370800 | There are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class P234H {
public void run() throws Exception {
int n = nextInt();
int [] a = new int [n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
int m = nextInt();
int [] b = new int [m];
for (int i = 0; i < m; i++) {
b[i] = nextInt();
}
int [] ab = new int [n + m];
StringBuffer resA = new StringBuffer();
StringBuffer resB = new StringBuffer();
int sc = a[0];
int ia = 0;
int ib = 0;
while (ia < n || ib < m) {
while (ia < n && a[ia] == sc) {
ab[ia + ib] = a[ia];
ia++;
resA = resA.append(ia).append(' ');
}
while (ib < m && b[ib] == sc) {
ab[ia + ib] = b[ib];
ib++;
resA = resA.append(ib + n).append(' ');
}
sc = 1 - sc;
}
resA= resA.append("\n");
StringBuffer tRes = new StringBuffer();
sc = ab[0];
int cntA = 0;
for (int i = 0; i < ab.length; i++) {
if (ab[i] != sc) {
tRes = tRes.append(i).append(' ');
sc = 1 - sc;
cntA++;
}
}
if (ab[ab.length - 1] == 1) {
cntA++;
tRes = tRes.append(ab.length);
}
resA = resA.append(cntA).append("\n").append(tRes);
//-------------------------------------------------------
sc = b[0];
ia = 0;
ib = 0;
while (ia < n || ib < m) {
while (ib < m && b[ib] == sc) {
ab[ia + ib] = b[ib];
ib++;
resB = resB.append(n + ib).append(' ');
}
while (ia < n && a[ia] == sc) {
ab[ia + ib] = a[ia];
ia++;
resB = resB.append(ia).append(' ');
}
sc = 1 - sc;
}
resB= resB.append("\n");
tRes = new StringBuffer();
sc = ab[0];
int cntB = 0;
for (int i = 0; i < ab.length; i++) {
if (ab[i] != sc) {
tRes = tRes.append(i).append(' ');
sc = 1 - sc;
cntB++;
}
}
if (ab[ab.length - 1] == 1) {
cntB++;
tRes = tRes.append(ab.length);
}
resB = resB.append(cntB).append("\n").append(tRes);
if (cntA <= cntB) {
println(resA);
} else {
println(resB);
}
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream("output.txt")));
new P234H().run();
br.close();
pw.close();
}
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(StringBuffer sb) {
print("" + sb);
}
void print(String s) {
pw.print(s);
}
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(StringBuffer sb) {
println("" + sb);
}
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 br.readLine();
}
} | Java | ["3\n1 0 1\n4\n1 1 1 1", "5\n1 1 1 1 1\n5\n0 1 0 1 0"] | 2 seconds | ["1 4 5 6 7 2 3\n3\n5 6 7", "6 1 2 3 4 5 7 8 9 10\n4\n1 7 8 9"] | null | Java 6 | input.txt | [
"constructive algorithms",
"greedy"
] | f1a312a21d600cf9cfff4afeca9097dc | The first input line contains a single integer n — the number of cards in the first deck (1 ≤ n ≤ 105). The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≤ ai ≤ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one. The third input line contains integer m — the number of cards in the second deck (1 ≤ m ≤ 105). The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≤ bi ≤ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost. | 2,000 | In the first line print n + m space-separated integers — the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom. In the second line print a single integer x — the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≤ ci ≤ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6·105. | output.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.