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 | ab84dece90029fb12dc1c750adb5a979 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.HashMap;
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 greperror
*/
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 k = in.nextInt();
int n = in.nextInt();
long[] arr = new long[k];
HashMap<Long, Boolean> map = new HashMap<>();
HashMap<Long, Boolean> ansMap = new HashMap<>();
for (int i = 0; i < k; i++) {
arr[i] = Long.parseLong(in.next());
}
map.put(arr[0], true);
for (int i = 1; i < k; i++) {
arr[i] = arr[i - 1] + arr[i];
map.put(arr[i], true);
}
int ans = 0;
int[] num = new int[n];
for (int i = 0; i < n; i++) {
num[i] = in.nextInt();
}
for (int i = 0; i < k; i++) {
long startNum = num[0] - arr[i];
boolean flag = true;
for (int j = 1; j < n; j++) {
long reqNum = num[j] - startNum;
if (!map.containsKey(reqNum)) {
flag = false;
break;
}
}
if (flag) {
if (!ansMap.containsKey(startNum)) {
ans++;
ansMap.put(startNum, true);
}
}
}
out.println(ans);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 48e77ef3b966b8bf2a036c667a52ddf4 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.HashMap;
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 vikas.k
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n + 1];
a[0] = 0;
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1] + in.nextInt();
}
Arrays.sort(a, 1, n + 1);
int b[] = new int[k + 1];
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 1; i <= k; i++) {
b[i] = in.nextInt();
hashMap.put(b[i], i);
}
Arrays.sort(b, 1, k + 1);
HashMap<Integer, Boolean> done = new HashMap<>();
int u = b[1];
int ans = 0;
for (int i = 1; i <= n; i++) {
int x = u - a[i];
if (done.containsKey(x)) continue;
boolean[] mrk = new boolean[k + 1];
int cnt = 0;
for (int j = 1; j <= n; j++) {
int y = x + a[j];
if (hashMap.containsKey(y)) {
int v = hashMap.get(y);
if (!mrk[v]) {
mrk[v] = true;
cnt++;
}
}
}
if (cnt == k) {
//out.print(x+" ");
ans++;
}
done.put(x, true);
}
out.print(ans);
}
}
static class FastScanner {
private BufferedReader bufferedReader;
private StringTokenizer stringTokenizer;
public FastScanner(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
if (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
try {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | bd5dba8372d41c05d56166bd70abfe69 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), k = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (i > 0) a[i] += a[i - 1];
}
int[] b = new int[k];
for (int i = 0; i < k; i++) b[i] = sc.nextInt();
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(b[0] - a[i]);
}
int possible[] = new int[set.size()];
boolean[] ok = new boolean[set.size()];
int idx = 0;
for (int num : set) {
ok[idx] = true;
possible[idx++] = num;
}
for (int j = 1; j < k; j++) {
set = new HashSet<>();
for (int i = 0; i < n; i++)
set.add(b[j] - a[i]);
for (int i = 0; i < possible.length; i++)
if (!set.contains(possible[i]))
ok[i] = false;
}
int cnt = 0;
for (int i = 0; i < possible.length; i++)
cnt += ok[i] ? 1 : 0;
out.println(cnt);
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 9d22a7a25afa560b1b631f303c8df7e9 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
public static void main(String[] args) {
int k = input.nextInt();
int n = input.nextInt();
Set<Integer> a = new HashSet<>();
Set<Integer> b = new HashSet<>();
int sum = 0;
for (int i = 0; i < k; i++) {
sum += input.nextInt();
a.add(sum);
}
for (int i = 0; i < n; i++) {
b.add(input.nextInt());
}
Set<Integer> AllPos = new HashSet<>();
boolean firstIter = true;
for (int curNum : b) {
Set<Integer> pos = new HashSet<>();
for (int curSum : a) {
pos.add(curNum - curSum);
}
if (firstIter) {
AllPos = pos;
firstIter = false;
} else {
AllPos.retainAll(pos);
}
}
System.out.println(AllPos.size());
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 4ce5d891cd58e9f80282049f7a84d80f | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by aps36017 on 14/7/17.
*/
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int k = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
int array[] = new int[k];
st = new StringTokenizer(br.readLine());
for(int i = 0;i < k;i++)
array[i] = Integer.parseInt(st.nextToken());
for(int i = 1;i < k;i++)
array[i] += array[i - 1];
Arrays.sort(array);
int b[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0;i < n;i++)
b[i] = Integer.parseInt(st.nextToken());
Arrays.sort(b);
HashSet<Integer>ans = new HashSet<>();
HashSet<Integer>set;
for(int i = 0;i < k;i++){
int start = b[0] - array[i];
set = new HashSet<>();
for(int j = i;j < k;j++)
set.add(start + array[j]);
boolean flag = true;
for(int j = 0;j < n;j++)
if(!set.contains(b[j]))
flag = false;
if(flag)ans.add(start);
}
System.out.println(ans.size());
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 30239f4df0c96f7e34054415081d2c1e | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by aps36017 on 14/7/17.
*/
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int k = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
int array[] = new int[k];
st = new StringTokenizer(br.readLine());
for(int i = 0;i < k;i++)
array[i] = Integer.parseInt(st.nextToken());
for(int i = 1;i < k;i++)
array[i] += array[i - 1];
Arrays.sort(array);
int b[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0;i < n;i++)
b[i] = Integer.parseInt(st.nextToken());
Arrays.sort(b);
HashSet<Integer>ans = new HashSet<>();
HashSet<Integer>set;
for(int i = 0;i < k;i++){
int start = b[0] - array[i];
set = new HashSet<>();
for(int j = 0;j < k;j++)
set.add(start + array[j]);
boolean flag = true;
for(int j = 0;j < n;j++)
if(!set.contains(b[j]))
flag = false;
if(flag)ans.add(start);
}
System.out.println(ans.size());
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 9ed068a8f8296d81a49bd720ce8c04d6 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class JuryMarks {
public static void main(String[] args) {
try(Scanner sc = new Scanner(System.in)) {
int k = sc.nextInt();
int n = sc.nextInt();
int[] ka = new int[k];
int[] sums = new int[k];
int[] na = new int[n];
for (int i = 0; i < k; i++) {
ka[i] = sc.nextInt();
sums[i] = i == 0 ? ka[i] : sums[i-1] + ka[i];
}
for (int i = 0; i < n; i++) {
na[i] = sc.nextInt();
}
int ans = 0;
Set<Integer> potentials = new HashSet<>();
int b = na[0];
for (int i = 0; i < k; i++) {
potentials.add(b - sums[i]);
}
for (Integer e : potentials) {
Set<Integer> points = new HashSet<>();
for (int i = 0; i < k; i++) {
points.add(e + sums[i]);
}
boolean contains = true;
for (int i = 0; i < na.length; i++) {
if(!points.contains(na[i])) {
contains = false; break;
};
}
if(contains) ans++;
}
System.out.println(ans);
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 01a7da4d4095acbf7067661568b81836 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class C_424
{
public static final long[] POWER2 = generatePOWER2();
public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator());
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer stringTokenizer = null;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
interface BiFunctionResult<Type0, Type1, TypeResult>
{
TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
}
static class Array<Type> implements Iterable<Type>
{
private Object[] array;
public Array(int size)
{
this.array = new Object[size];
}
public Array(int size, Type element)
{
this(size);
Arrays.fill(this.array, element);
}
public Array(Array<Type> array, Type element)
{
this(array.size() + 1);
for (int index = 0; index < array.size(); index++)
{
set(index, array.get(index));
}
set(size() - 1, element);
}
public Array(List<Type> list)
{
this(list.size());
int index = 0;
for (Type element : list)
{
set(index, element);
index += 1;
}
}
public Type get(int index)
{
return (Type) this.array[index];
}
public Array set(int index, Type value)
{
this.array[index] = value;
return this;
}
public int size()
{
return this.array.length;
}
public List<Type> toList()
{
List<Type> result = new ArrayList<>();
for (Type element : this)
{
result.add(element);
}
return result;
}
@Override
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < size();
}
@Override
public Type next()
{
Type result = Array.this.get(index);
index += 1;
return result;
}
};
}
@Override
public String toString()
{
return "[" + C_424.toString(this, ", ") + "]";
}
}
static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
{
public final TypeVertex vertex0;
public final TypeVertex vertex1;
public final boolean bidirectional;
public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
this.vertex0 = vertex0;
this.vertex1 = vertex1;
this.bidirectional = bidirectional;
this.vertex0.edges.add(getThis());
if (this.bidirectional)
{
this.vertex1.edges.add(getThis());
}
}
public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
{
TypeVertex result;
if (vertex0 == vertex)
{
result = vertex1;
}
else
{
result = vertex0;
}
return result;
}
public abstract TypeEdge getThis();
public void remove()
{
this.vertex0.edges.remove(getThis());
if (this.bidirectional)
{
this.vertex1.edges.remove(getThis());
}
}
@Override
public String toString()
{
return this.vertex0 + "->" + this.vertex1;
}
}
public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
{
public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefault<TypeVertex> getThis()
{
return this;
}
}
public static class Vertex<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
{
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> void depthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
BiConsumer<TypeVertex, TypeEdge> functionPreVisit,
BiConsumer<TypeVertex, TypeEdge> functionInVisit,
BiConsumer<TypeVertex, TypeEdge> functionPostVisit
)
{
TypeVertex vertexTo;
TypeEdge edgeTo;
boolean[] isOnStack = new boolean[vertices.size()];
Stack<Operation> stackOperations = new Stack<>();
Stack<TypeVertex> stackVertices = new Stack<>();
Stack<TypeEdge> stackEdges = new Stack<>();
TypeVertex vertexStart = vertices.get(indexVertexStart);
stackOperations.push(Operation.EXPAND);
stackVertices.push(vertexStart);
stackEdges.push(null);
isOnStack[vertexStart.index] = true;
while (!stackOperations.isEmpty())
{
Operation operation = stackOperations.pop();
TypeVertex vertex = stackVertices.pop();
TypeEdge edge = stackEdges.pop();
switch (operation)
{
case INVISIT:
functionInVisit.accept(vertex, edge);
break;
case POSTVISIT:
functionPostVisit.accept(vertex, edge);
break;
case EXPAND:
stackOperations.push(Operation.POSTVISIT);
stackVertices.push(vertex);
stackEdges.push(edge);
Integer indexTo = null;
for (int index = 0; indexTo == null && index < vertex.edges.size(); index++)
{
edgeTo = vertex.edges.get(index);
vertexTo = edgeTo.other(vertex);
if (!isOnStack[vertexTo.index])
{
indexTo = index;
}
}
if (indexTo != null)
{
edgeTo = vertex.edges.get(indexTo);
vertexTo = edgeTo.other(vertex);
stackOperations.push(Operation.EXPAND);
stackVertices.push(vertexTo);
stackEdges.push(edgeTo);
isOnStack[vertexTo.index] = true;
for (int index = indexTo + 1; index < vertex.edges.size(); index++)
{
edgeTo = vertex.edges.get(index);
vertexTo = edgeTo.other(vertex);
if (!isOnStack[vertexTo.index])
{
stackOperations.push(Operation.INVISIT);
stackVertices.push(vertex);
stackEdges.push(edge);
stackOperations.push(Operation.EXPAND);
stackVertices.push(vertexTo);
stackEdges.push(edgeTo);
isOnStack[vertexTo.index] = true;
}
}
}
functionPreVisit.accept(vertex, edge);
break;
}
}
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> void depthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
Consumer<TypeVertex> functionPreVisit,
Consumer<TypeVertex> functionInVisit,
Consumer<TypeVertex> functionPostVisit
)
{
depthFirstSearch(
vertices,
indexVertexStart,
(vertex, edge) -> functionPreVisit.accept(vertex),
(vertex, edge) -> functionInVisit.accept(vertex),
(vertex, edge) -> functionPostVisit.accept(vertex)
);
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
TypeVertex vertex,
TypeEdge edge,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
Array<Boolean> visited,
FIFO<TypeVertex> verticesNext,
FIFO<TypeEdge> edgesNext,
TypeResult result
)
{
if (!visited.get(vertex.index))
{
visited.set(vertex.index, true);
result = function.apply(vertex, edge, result);
for (TypeEdge edgeNext : vertex.edges)
{
TypeVertex vertexNext = edgeNext.other(vertex);
if (!visited.get(vertexNext.index))
{
verticesNext.push(vertexNext);
edgesNext.push(edgeNext);
}
}
}
return result;
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
TypeResult result
)
{
Array<Boolean> visited = new Array<>(vertices.size(), false);
FIFO<TypeVertex> verticesNext = new FIFO<>();
verticesNext.push(vertices.get(indexVertexStart));
FIFO<TypeEdge> edgesNext = new FIFO<>();
edgesNext.push(null);
while (!verticesNext.isEmpty())
{
result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
}
return result;
}
public final int index;
public final List<TypeEdge> edges;
public Vertex(int index)
{
this.index = index;
this.edges = new ArrayList<>();
}
@Override
public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
{
return Integer.compare(this.index, that.index);
}
@Override
public String toString()
{
return "" + this.index;
}
enum Operation
{
INVISIT, POSTVISIT, EXPAND
}
}
public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
{
public VertexDefault(int index)
{
super(index);
}
}
public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
{
public static Array<VertexDefaultDefault> vertices(int n)
{
Array<VertexDefaultDefault> result = new Array<>(n);
for (int index = 0; index < n; index++)
{
result.set(index, new VertexDefaultDefault(index));
}
return result;
}
public VertexDefaultDefault(int index)
{
super(index);
}
}
public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
{
public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefaultDefault getThis()
{
return this;
}
}
public static class Tuple2<Type0, Type1>
{
public final Type0 v0;
public final Type1 v1;
public Tuple2(Type0 v0, Type1 v1)
{
this.v0 = v0;
this.v1 = v1;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ")";
}
}
static class Wrapper<Type>
{
public Type value;
public Wrapper(Type value)
{
this.value = value;
}
public Type get()
{
return this.value;
}
public void set(Type value)
{
this.value = value;
}
@Override
public String toString()
{
return this.value.toString();
}
}
public static class Tuple3<Type0, Type1, Type2>
{
public final Type0 v0;
public final Type1 v1;
public final Type2 v2;
public Tuple3(Type0 v0, Type1 v1, Type2 v2)
{
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
}
}
public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
{
public Tuple2Comparable(Type0 v0, Type1 v1)
{
super(v0, v1);
}
@Override
public int compareTo(Tuple2Comparable<Type0, Type1> that)
{
int result = this.v0.compareTo(that.v0);
if (result == 0)
{
result = this.v1.compareTo(that.v1);
}
return result;
}
}
public static class SingleLinkedList<Type>
{
public final Type element;
public SingleLinkedList<Type> next;
public SingleLinkedList(Type element, SingleLinkedList<Type> next)
{
this.element = element;
this.next = next;
}
public void toCollection(Collection<Type> collection)
{
if (this.next != null)
{
this.next.toCollection(collection);
}
collection.add(this.element);
}
}
public static class Node<Type>
{
public static <Type> Node<Type> balance(Node<Type> result)
{
while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
{
if (height(result.left) < height(result.right))
{
Node<Type> right = result.right;
if (height(right.right) < height(right.left))
{
result = new Node<>(result.value, result.left, right.rotateRight());
}
result = result.rotateLeft();
}
else
{
Node<Type> left = result.left;
if (height(left.left) < height(left.right))
{
result = new Node<>(result.value, left.rotateLeft(), result.right);
}
result = result.rotateRight();
}
}
return result;
}
public static <Type> Node<Type> clone(Node<Type> result)
{
if (result != null)
{
result = new Node<>(result.value, clone(result.left), clone(result.right));
}
return result;
}
public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
if (node.left == null)
{
result = node.right;
}
else
{
if (node.right == null)
{
result = node.left;
}
else
{
Node<Type> first = first(node.right);
result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator));
}
}
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, delete(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, delete(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> first(Node<Type> result)
{
while (result.left != null)
{
result = result.left;
}
return result;
}
public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node;
}
else
{
if (compare < 0)
{
result = get(node.left, value, comparator);
}
else
{
result = get(node.right, value, comparator);
}
}
}
return result;
}
public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node.left;
}
else
{
if (compare < 0)
{
result = head(node.left, value, comparator);
}
else
{
result = new Node<>(node.value, node.left, head(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static int height(Node node)
{
return node == null ? 0 : node.height;
}
public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = new Node<>(value, null, null);
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(value, node.left, node.right);
;
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, insert(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, insert(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> last(Node<Type> result)
{
while (result.right != null)
{
result = result.right;
}
return result;
}
public static int size(Node node)
{
return node == null ? 0 : node.size;
}
public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(node.value, null, node.right);
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, tail(node.left, value, comparator), node.right);
}
else
{
result = tail(node.right, value, comparator);
}
}
result = balance(result);
}
return result;
}
public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
{
if (node != null)
{
traverseOrderIn(node.left, consumer);
consumer.accept(node.value);
traverseOrderIn(node.right, consumer);
}
}
public final Type value;
public final Node<Type> left;
public final Node<Type> right;
public final int size;
private final int height;
public Node(Type value, Node<Type> left, Node<Type> right)
{
this.value = value;
this.left = left;
this.right = right;
this.size = 1 + size(left) + size(right);
this.height = 1 + Math.max(height(left), height(right));
}
public Node<Type> rotateLeft()
{
Node<Type> left = new Node<>(this.value, this.left, this.right.left);
return new Node<>(this.right.value, left, this.right.right);
}
public Node<Type> rotateRight()
{
Node<Type> right = new Node<>(this.value, this.left.right, this.right);
return new Node<>(this.left.value, this.left.left, right);
}
}
public static class SortedSetAVL<Type> implements SortedSet<Type>
{
public Comparator<? super Type> comparator;
public Node<Type> root;
private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
{
this.comparator = comparator;
this.root = root;
}
public SortedSetAVL(Comparator<? super Type> comparator)
{
this(comparator, null);
}
public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
{
this(comparator, null);
this.addAll(collection);
}
public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL)
{
this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
}
@Override
public void clear()
{
this.root = null;
}
@Override
public Comparator<? super Type> comparator()
{
return this.comparator;
}
public Type get(Type value)
{
Node<Type> node = Node.get(this.root, value, this.comparator);
return node == null ? null : node.value;
}
@Override
public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
{
return tailSet(valueStart).headSet(valueEnd);
}
@Override
public SortedSetAVL<Type> headSet(Type valueEnd)
{
return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
}
@Override
public SortedSetAVL<Type> tailSet(Type valueStart)
{
return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
}
@Override
public Type first()
{
return Node.first(this.root).value;
}
@Override
public Type last()
{
return Node.last(this.root).value;
}
@Override
public int size()
{
return this.root == null ? 0 : this.root.size;
}
@Override
public boolean isEmpty()
{
return this.root == null;
}
@Override
public boolean contains(Object value)
{
return Node.get(this.root, (Type) value, this.comparator) != null;
}
@Override
public Iterator<Type> iterator()
{
Stack<Node<Type>> path = new Stack<>();
return new Iterator<Type>()
{
{
push(SortedSetAVL.this.root);
}
public void push(Node<Type> node)
{
while (node != null)
{
path.push(node);
node = node.left;
}
}
@Override
public boolean hasNext()
{
return !path.isEmpty();
}
@Override
public Type next()
{
if (path.isEmpty())
{
throw new NoSuchElementException();
}
else
{
Node<Type> node = path.peek();
Type result = node.value;
if (node.right != null)
{
push(node.right);
}
else
{
do
{
node = path.pop();
}
while (!path.isEmpty() && path.peek().right == node);
}
return result;
}
}
};
}
@Override
public Object[] toArray()
{
List<Object> list = new ArrayList<>();
Node.traverseOrderIn(this.root, list::add);
return list.toArray();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(Type value)
{
int sizeBefore = size();
this.root = Node.insert(this.root, value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean remove(Object value)
{
int sizeBefore = size();
this.root = Node.delete(this.root, (Type) value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean containsAll(Collection<?> collection)
{
return collection.stream()
.allMatch(this::contains);
}
@Override
public boolean addAll(Collection<? extends Type> collection)
{
return collection.stream()
.map(this::add)
.reduce(true, (x, y) -> x | y);
}
@Override
public boolean retainAll(Collection<?> collection)
{
SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
collection.stream()
.map(element -> (Type) element)
.filter(this::contains)
.forEach(set::add);
boolean result = size() != set.size();
this.root = set.root;
return result;
}
@Override
public boolean removeAll(Collection<?> collection)
{
return collection.stream()
.map(this::remove)
.reduce(true, (x, y) -> x | y);
}
@Override
public String toString()
{
return "{" + C_424.toString(this, ", ") + "}";
}
}
public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
{
public final Comparator<? super TypeKey> comparator;
public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;
public SortedMapAVL(Comparator<? super TypeKey> comparator)
{
this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
}
private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
{
this.comparator = comparator;
this.entrySet = entrySet;
}
@Override
public Comparator<? super TypeKey> comparator()
{
return this.comparator;
}
@Override
public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
}
public Entry<TypeKey, TypeValue> firstEntry()
{
return this.entrySet.first();
}
@Override
public TypeKey firstKey()
{
return firstEntry().getKey();
}
public Entry<TypeKey, TypeValue> lastEntry()
{
return this.entrySet.last();
}
@Override
public TypeKey lastKey()
{
return lastEntry().getKey();
}
@Override
public int size()
{
return this.entrySet().size();
}
@Override
public boolean isEmpty()
{
return this.entrySet.isEmpty();
}
@Override
public boolean containsKey(Object key)
{
return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null));
}
@Override
public boolean containsValue(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public TypeValue get(Object key)
{
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
entry = this.entrySet.get(entry);
return entry == null ? null : entry.getValue();
}
@Override
public TypeValue put(TypeKey key, TypeValue value)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
this.entrySet().add(entry);
return result;
}
@Override
public TypeValue remove(Object key)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
this.entrySet.remove(entry);
return result;
}
@Override
public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
{
map.entrySet()
.forEach(entry -> put(entry.getKey(), entry.getValue()));
}
@Override
public void clear()
{
this.entrySet.clear();
}
@Override
public Set<TypeKey> keySet()
{
throw new UnsupportedOperationException();
}
@Override
public Collection<TypeValue> values()
{
return new Collection<TypeValue>()
{
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public boolean isEmpty()
{
return SortedMapAVL.this.entrySet.isEmpty();
}
@Override
public boolean contains(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
@Override
public boolean hasNext()
{
return this.iterator.hasNext();
}
@Override
public TypeValue next()
{
return this.iterator.next().getValue();
}
};
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(TypeValue typeValue)
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeValue> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
{
return this.entrySet;
}
@Override
public String toString()
{
return this.entrySet().toString();
}
}
public static class FIFO<Type>
{
public SingleLinkedList<Type> start;
public SingleLinkedList<Type> end;
public FIFO()
{
this.start = null;
this.end = null;
}
public boolean isEmpty()
{
return this.start == null;
}
public Type peek()
{
return this.start.element;
}
public Type pop()
{
Type result = this.start.element;
this.start = this.start.next;
return result;
}
public void push(Type element)
{
SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
if (this.start == null)
{
this.start = list;
this.end = list;
}
else
{
this.end.next = list;
this.end = list;
}
}
}
public static class MapCount<Type> extends SortedMapAVL<Type, Long>
{
private int count;
public MapCount(Comparator<? super Type> comparator)
{
super(comparator);
this.count = 0;
}
public long add(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key);
if (value == null)
{
value = delta;
}
else
{
value += delta;
}
put(key, value);
result = delta;
}
else
{
result = 0;
}
this.count += result;
return result;
}
public int count()
{
return this.count;
}
public List<Type> flatten()
{
List<Type> result = new ArrayList<>();
for (Entry<Type, Long> entry : entrySet())
{
for (long index = 0; index < entry.getValue(); index++)
{
result.add(entry.getKey());
}
}
return result;
}
@Override
public void putAll(Map<? extends Type, ? extends Long> map)
{
throw new UnsupportedOperationException();
}
@Override
public Long remove(Object key)
{
Long result = super.remove(key);
this.count -= result;
return result;
}
public long remove(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key) - delta;
if (value <= 0)
{
result = delta + value;
remove(key);
}
else
{
result = delta;
put(key, value);
}
}
else
{
result = 0;
}
this.count -= result;
return result;
}
@Override
public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> headMap(Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> tailMap(Type keyStart)
{
throw new UnsupportedOperationException();
}
}
public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
{
private Comparator<? super TypeValue> comparatorValue;
public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey);
this.comparatorValue = comparatorValue;
}
public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey, entrySet);
this.comparatorValue = comparatorValue;
}
public TypeValue firstValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
if (firstEntry == null)
{
result = null;
}
else
{
result = firstEntry.getValue().first();
}
return result;
}
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
Iterator<TypeValue> iteratorValue = null;
@Override
public boolean hasNext()
{
return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
}
@Override
public TypeValue next()
{
if (iteratorValue == null || !iteratorValue.hasNext())
{
iteratorValue = iteratorValues.next().iterator();
}
return iteratorValue.next();
}
};
}
public TypeValue lastValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
if (lastEntry == null)
{
result = null;
}
else
{
result = lastEntry.getValue().last();
}
return result;
}
public boolean add(TypeKey key, TypeValue value)
{
SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue));
return set.add(value);
}
public boolean removeSet(TypeKey key, TypeValue value)
{
boolean result;
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
result = false;
}
else
{
result = set.remove(value);
if (set.size() == 0)
{
remove(key);
}
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
}
@Override
public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
}
}
static class IteratorBuffer<Type>
{
private Iterator<Type> iterator;
private List<Type> list;
public IteratorBuffer(Iterator<Type> iterator)
{
this.iterator = iterator;
this.list = new ArrayList<Type>();
}
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < list.size() || iterator().hasNext();
}
@Override
public Type next()
{
if (list.size() <= this.index)
{
list.add(iterator.next());
}
Type result = list.get(index);
index += 1;
return result;
}
};
}
}
public static <Type> List<List<Type>> permutations(List<Type> list)
{
List<List<Type>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (Type element : list)
{
List<List<Type>> permutations = result;
result = new ArrayList<>();
for (List<Type> permutation : permutations)
{
for (int index = 0; index <= permutation.size(); index++)
{
List<Type> permutationNew = new ArrayList<>(permutation);
permutationNew.add(index, element);
result.add(permutationNew);
}
}
}
return result;
}
public static List<List<Integer>> combinations(int n, int k)
{
List<List<Integer>> result = new ArrayList<>();
if (k == 0)
{
}
else
{
if (k == 1)
{
List<Integer> combination = new ArrayList<>();
combination.add(n);
result.add(combination);
}
else
{
for (int index = 0; index <= n; index++)
{
for (List<Integer> combination : combinations(n - index, k - 1))
{
combination.add(index);
result.add(combination);
}
}
}
}
return result;
}
public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
{
int result = 0;
while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
{
result = comparator.compare(iterator0.next(), iterator1.next());
}
if (result == 0)
{
if (iterator1.hasNext())
{
result = -1;
}
else
{
if (iterator0.hasNext())
{
result = 1;
}
}
}
return result;
}
public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
{
return compare(iterable0.iterator(), iterable1.iterator(), comparator);
}
private static String nextString() throws IOException
{
while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
{
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
private static String[] nextStrings(int n) throws IOException
{
String[] result = new String[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextString();
}
}
return result;
}
public static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public static int[] nextInts(int n) throws IOException
{
int[] result = new int[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextInt();
}
}
return result;
}
public static double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
public static long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public static long[] nextLongs(int n) throws IOException
{
long[] result = new long[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextLong();
}
}
return result;
}
public static String nextLine() throws IOException
{
return bufferedReader.readLine();
}
public static void close()
{
out.close();
}
public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
{
int result;
if (start == end)
{
result = end;
}
else
{
int middle = start + (end - start) / 2;
if (filter.apply(middle))
{
result = binarySearchMinimum(filter, start, middle);
}
else
{
result = binarySearchMinimum(filter, middle + 1, end);
}
}
return result;
}
public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
{
return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
}
public static long divideCeil(long x, long y)
{
return (x + y - 1) / y;
}
public static Set<Long> divisors(long n)
{
SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
result.add(1L);
for (Long factor : factors(n))
{
SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
for (Long divisor : result)
{
divisors.add(divisor * factor);
}
result = divisors;
}
return result;
}
public static long faculty(int n)
{
long result = 1;
for (int index = 2; index <= n; index++)
{
result *= index;
}
return result;
}
public static LinkedList<Long> factors(long n)
{
LinkedList<Long> result = new LinkedList<>();
Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while (n > 1 && (prime = primes.next()) * prime <= n)
{
while (n % prime == 0)
{
result.add(prime);
n /= prime;
}
}
if (n > 1)
{
result.add(n);
}
return result;
}
public static long gcd(long a, long b)
{
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
public static long[] generatePOWER2()
{
long[] result = new long[63];
for (int x = 0; x < result.length; x++)
{
result[x] = 1L << x;
}
return result;
}
public static boolean isPrime(long x)
{
boolean result = x > 1;
Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while ((prime = iterator.next()) * prime <= x)
{
result &= x % prime > 0;
}
return result;
}
public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
{
long[] valuesMaximum = new long[weightMaximum + 1];
for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
{
long itemValue = itemValueWeightCount.v0;
int itemWeight = itemValueWeightCount.v1;
int itemCount = itemValueWeightCount.v2;
for (int weight = weightMaximum; 0 <= weight; weight--)
{
for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
{
valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
}
}
}
long result = 0;
for (long valueMaximum : valuesMaximum)
{
result = Math.max(result, valueMaximum);
}
return result;
}
public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
{
boolean[] weightPossible = new boolean[weightMaximum + 1];
weightPossible[0] = true;
int weightLargest = 0;
for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
{
int itemWeight = itemWeightCount.v0;
int itemCount = itemWeightCount.v1;
for (int weightStart = 0; weightStart < itemWeight; weightStart++)
{
int count = 0;
for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
{
if (weightPossible[weight])
{
count = itemCount;
}
else
{
if (0 < count)
{
weightPossible[weight] = true;
weightLargest = weight;
count -= 1;
}
}
}
}
}
return weightPossible[weightMaximum];
}
public static long lcm(int a, int b)
{
return a * b / gcd(a, b);
}
public static <T> List<T> permutation(long p, List<T> x)
{
List<T> copy = new ArrayList<>();
for (int index = 0; index < x.size(); index++)
{
copy.add(x.get(index));
}
List<T> result = new ArrayList<>();
for (int indexTo = 0; indexTo < x.size(); indexTo++)
{
int indexFrom = (int) p % copy.size();
p = p / copy.size();
result.add(copy.remove(indexFrom));
}
return result;
}
public static <Type> String toString(Iterator<Type> iterator, String separator)
{
StringBuilder stringBuilder = new StringBuilder();
if (iterator.hasNext())
{
stringBuilder.append(iterator.next());
}
while (iterator.hasNext())
{
stringBuilder.append(separator);
stringBuilder.append(iterator.next());
}
return stringBuilder.toString();
}
public static <Type> String toString(Iterator<Type> iterator)
{
return toString(iterator, " ");
}
public static <Type> String toString(Iterable<Type> iterable, String separator)
{
return toString(iterable.iterator(), separator);
}
public static <Type> String toString(Iterable<Type> iterable)
{
return toString(iterable, " ");
}
public static Stream<BigInteger> streamFibonacci()
{
return Stream.generate(new Supplier<BigInteger>()
{
private BigInteger n0 = BigInteger.ZERO;
private BigInteger n1 = BigInteger.ONE;
@Override
public BigInteger get()
{
BigInteger result = n0;
n0 = n1;
n1 = result.add(n0);
return result;
}
});
}
public static Stream<Long> streamPrime(int sieveSize)
{
return Stream.generate(new Supplier<Long>()
{
private boolean[] isPrime = new boolean[sieveSize];
private long sieveOffset = 2;
private List<Long> primes = new ArrayList<>();
private int index = 0;
public void filter(long prime, boolean[] result)
{
if (prime * prime < this.sieveOffset + sieveSize)
{
long remainingStart = this.sieveOffset % prime;
long start = remainingStart == 0 ? 0 : prime - remainingStart;
for (long index = start; index < sieveSize; index += prime)
{
result[(int) index] = false;
}
}
}
public void generatePrimes()
{
Arrays.fill(this.isPrime, true);
this.primes.forEach(prime -> filter(prime, isPrime));
for (int index = 0; index < sieveSize; index++)
{
if (isPrime[index])
{
this.primes.add(this.sieveOffset + index);
filter(this.sieveOffset + index, isPrime);
}
}
this.sieveOffset += sieveSize;
}
@Override
public Long get()
{
while (this.primes.size() <= this.index)
{
generatePrimes();
}
Long result = this.primes.get(this.index);
this.index += 1;
return result;
}
});
}
public static long totient(long n)
{
Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
long result = n;
for (long p : factors)
{
result -= result / p;
}
return result;
}
public static void main(String[] args)
{
try
{
solve();
} catch (IOException exception)
{
exception.printStackTrace();
}
close();
}
public static boolean match(int[] score, int[] b, boolean[] score2b)
{
for (int index = 0; index < b.length; index++)
{
score2b[b[index] + 4000000] = true;
}
int count = 0;
for (int index = 0; index < score.length; index++)
{
if (-4000000 <= score[index] && score[index] <= 4000000 && score2b[score[index] + 4000000])
{
count += 1;
score2b[score[index] + 4000000] = false;
}
}
return count == b.length;
}
public static void solve() throws IOException
{
int k = nextInt();
int n = nextInt();
int[] a = nextInts(k);
int[] b = nextInts(n);
boolean[] score2b = new boolean[4000000 * 2 + 1];
SortedSetAVL<Integer> scores = new SortedSetAVL<>(Comparator.naturalOrder());
int[] score = new int[k];
for (int start = 0; start < k; start++)
{
score[start] = b[0];
for (int index = start - 1; index >= 0; index--)
{
score[index] = score[index + 1] - a[index + 1];
}
for (int index = start + 1; index < k; index++)
{
score[index] = score[index - 1] + a[index];
}
if (match(score, b, score2b))
{
scores.add(score[0] - a[0]);
}
}
out.println(scores.size());
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 5866e1bf5b756958bb0f554931c3c5a6 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.*;
import java.util.InputMismatchException;
import java.util.List;
/**
* http://codeforces.com/contest/831/problem/C
*/
public class JuryMarks {
InputStream is;
PrintWriter out;
String INPUT = "";
long mod = 1000000007;
class Node {
String s;
int[] ar;
}
void solve() {
int k = ni();
int n = ni();
int[] marks = na(k);
int[] score = na(n);
int score0 = score[0];
for (int i = 0; i < n; i++) {
score[i] = score[i] - score0;
}
Arrays.sort(score);
List<Integer> list = new ArrayList();
list.add(marks[0]);
for (int i = 1; i < k; i++) {
list.add(marks[i] + list.get(i - 1));
}
Collections.sort(list);
List<Integer> delta1 = new ArrayList();
Set<Integer> saw = new HashSet();
for (int i = 0; i < k; i++) {
int diff = i > 0 ? list.get(i) - list.get(i - 1) : list.get(0);
if (diff != 0) {
delta1.add(diff);
saw.add(diff);
}
}
List<Integer> delta2 = new ArrayList();
for (int i = 1; i < n; i++) {
int diff = i > 0 ? score[i] - score[i - 1] : score[0];
delta2.add(diff);
}
int result = 0;
int startingPoint = 1;
if(delta2.size() == 0) {
startingPoint = 0;
}
while (true) {
if (startingPoint > delta1.size() - 1 - delta2.size() + 1 ||
startingPoint > delta1.size() - 1) {
break;
}
int accumulated = 0;
int delta1I = startingPoint;
int delta2I = 0;
while (true) {
if (delta2I == delta2.size()) {
result += 1;
break;
}
if (delta1I == delta1.size()) {
break;
}
accumulated += delta1.get(delta1I++);
if (delta2.get(delta2I) == accumulated) {
accumulated = 0;
delta2I++;
} else if (delta2.get(delta2I) < accumulated) {
break;
}
}
startingPoint++;
}
if (delta1.size() == 0 && delta2.size() == 0) {
result = 1;
}
out.println(result);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new JuryMarks().run();
}
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | f7a0b0cb4c6ec129fcde43f2753807b1 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 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.Arrays;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
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 k = in.nextInt();
int n = in.nextInt();
int[] judge = in.readIntArray(k);
int[] tempScores = in.readIntArray(n);
int[] scoreSums = new int[k];
scoreSums[0] = judge[0];
for (int i = 1; i < k; i++) {
scoreSums[i] = scoreSums[i - 1] + judge[i];
}
Arrays.sort(scoreSums);
Arrays.sort(tempScores);
Set<Integer> iniScores = new HashSet<>();
for (int offset = 0; offset < k - n + 1; offset++) {
int prevJudge = offset;
int currentJudge = offset + 1;
boolean isPossible = true;
for (int i = 1; i < n; i++) {
int diff = tempScores[i] - tempScores[i - 1];
while ((currentJudge < k - 1) && (scoreSums[currentJudge] - scoreSums[prevJudge] < diff)) {
currentJudge++;
}
if (scoreSums[currentJudge] - scoreSums[prevJudge] != diff) {
isPossible = false;
break;
}
prevJudge = currentJudge;
currentJudge++;
}
if (isPossible) {
iniScores.add(tempScores[0] - scoreSums[offset]);
}
}
out.println(iniScores.size());
}
}
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 | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 98aa7924b63f580ae51bc155dcbef077 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
public class C831 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int k = sc.nextInt(), n = sc.nextInt();
HashSet<Integer> acc = new HashSet<>();
int sum = 0;
for(int i = 0;i<k;i++)
acc.add(sum += sc.nextInt());
int[] scores = new int[n];
for(int i = 0;i<n;i++)
scores[i] = sc.nextInt();
int ans= 0;
Iterator<Integer> e1 = acc.iterator();
int[] map = new int[((int)1e6)*16+1];
while(e1.hasNext())
{
int cur = e1.next();
for(int i = 0;i<n;i++)
{
int needed = scores[i]-cur;
map[needed+(int)1e6*8]++;
}
}
for(int needed:map)
if(needed==scores.length)
ans++;
System.out.println(ans);
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | cc972c83cf1dda79eb320cdb66c9016f | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | //package cf.n424;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import static java.lang.System.out;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int n = in.nextInt();
int[] addition = new int[k];
Set<Integer> xs = new HashSet<>();
int sum = 0;
for (int i = 0; i < k; ++i) {
int a = in.nextInt();
sum += a;
addition[i] = sum;
}
for (int j = 0; j < n; ++j) {
int b = in.nextInt();
Set<Integer> xsCur = new HashSet<>();
for (int i = 0; i < k; ++i) {
int x = b - addition[i];
xsCur.add(x);
}
xs = j == 0 ? xsCur : intersect(xsCur, xs);
}
out.println(xs.size());
}
private static Set<Integer> intersect(Set<Integer> a, Set<Integer> b) {
Set<Integer> result = new HashSet<>();
for (Integer e : a)
if (b.contains(e))
result.add(e);
return result;
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 0e0dd7512a0edc610cdfc0c3e832e962 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | //package cf.n424;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import static java.lang.System.out;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int n = in.nextInt();
int[] addition = new int[k];
Set<Integer> xs = new HashSet<>();
int sum = 0;
for (int i = 0; i < k; ++i) {
int a = in.nextInt();
sum += a;
addition[i] = sum;
}
for (int j = 0; j < n; ++j) {
int b = in.nextInt();
Set<Integer> xsCur = new HashSet<>();
for (int i = 0; i < k; ++i) {
int x = b - addition[i];
xsCur.add(x);
}
xs = j == 0 ? xsCur : intersect(xs, xsCur);
}
out.println(xs.size());
}
private static Set<Integer> intersect(Set<Integer> a, Set<Integer> b) {
Set<Integer> result = new HashSet<>();
for (Integer e : a)
if (b.contains(e))
result.add(e);
return result;
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 8c40b80b6bdc0f13533e2c6e0ed70dc2 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | //package cf.n424;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import static java.lang.System.out;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int n = in.nextInt();
int[] s = new int[k];
Set<Integer> xs = new HashSet<>();
int sum = 0;
for (int i = 0; i < k; ++i) {
int a = in.nextInt();
sum += a;
s[i] = sum;
}
for (int j = 0; j < n; ++j) {
int b = in.nextInt();
Set<Integer> x0 = new HashSet<>();
for (int i = 0; i < k; ++i) {
int x = b - s[i];
x0.add(x);
}
if (j == 0)
xs = x0;
else
xs = intersect(x0, xs);
}
out.println(xs.size());
}
private static Set<Integer> intersect(Set<Integer> a, Set<Integer> b) {
Set<Integer> result = new HashSet<>();
if (a.isEmpty() || b.isEmpty())
return result;
for (Integer e : a)
if (b.contains(e))
result.add(e);
return result;
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | bce141f41231068167e3abd1766bca13 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
long[] a = new long[n];
long[] val = new long[n];
HashMap<Long, Integer> sval = new HashMap<>();
for(int i=0; i<n; i++)
a[i] = in.nextInt();
for(int i=0; i<m; i++)
{
val[i] = in.nextInt();
sval.put(val[i], i);
}
long[] dp = new long[n];
dp[0] = a[0];
for(int i=1; i<n; i++)
dp[i] = dp[i-1] + a[i];
HashSet<Long> ans = new HashSet<>();
for(int i=0; i<n; i++)
{
// for(int j=0; j<m; j++)
ans.add(val[0] - dp[i]);
}
//pw.print(ans);
int ans2 = 0;
for(long p: ans)
{
int count = 0;
// pw.print(p+":");
boolean[] vis = new boolean[m];
for(int i=0; i<n; i++)
{
// pw.print(p+dp[i]+" ");
if(sval.get(p+dp[i])!=null)
if(!vis[sval.get(p+dp[i])])
{
count++;
vis[sval.get(p+dp[i])] = true;
}
}
// pw.print(count);
if(count==m)
ans2++;
// pw.println();
}
pw.print(ans2);
pw.flush();
pw.close();
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | d7f98c8bccb3b373c0f675212c723afd | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class CF_424_D2_C {
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());
}
}
private static boolean check(int possibleStart, int[] a, int[] b) {
int total = 0;
Map<Long, Boolean> bel = new HashMap<>();
for (int i = 0; i < b.length; ++i) {
bel.put((long) b[i], false);
}
long positionStart = possibleStart;
for (int i = 0; i < a.length; ++i) {
long new_result = positionStart + a[i];
positionStart = new_result;
if (bel.containsKey(new_result)) {
bel.put(new_result, true);
}
}
for (int i = 0; i < b.length; ++i) {
if (!bel.get((long) b[i])) {
return false;
}
}
return true;
}
public static void main(String[] args) {
FastScanner fs = new FastScanner();
int k = fs.nextInt();
int n = fs.nextInt();
int[] a = new int[k];
int[] prefix_sums = new int[k];
for (int i = 0; i < k; ++i) {
a[i] = fs.nextInt();
prefix_sums[i] = (i == 0)? a[0]: prefix_sums[i - 1] + a[i];
}
int[] b = new int[n];
for (int i = 0; i < n; ++i) {
b[i] = fs.nextInt();
}
Map<Integer, Boolean> solutions = new HashMap<>();
int result = 0;
for (int i = 0; i < k; ++i) {
int possibleStart = b[0] - prefix_sums[i];
if (check(possibleStart, a, b)) {
if (!solutions.containsKey(possibleStart)) {
result++;
solutions.put(possibleStart, true);
}
}
}
System.out.println(result);
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 61b2ffc9dabcdda9d52b48c5d2ba0671 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), k = sc.nextInt();
int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = sc.nextInt();
int[] sum = new int[n]; sum[0] = a[0];
for(int i = 1; i < n; i++) sum[i] = sum[i - 1] + a[i];
int[] b = new int[k]; for(int i = 0; i < k; i++) b[i] = sc.nextInt();
HashSet<Integer> ans = new HashSet<>(), taken = new HashSet<>();
for(int i = 0; i < n; i++)
{
int cur = b[0] - sum[i];
int s = cur;
for(int j = 0; j < n; j++)
{
s += a[j];
taken.add(s);
}
boolean valid = true;
for(int x : b) if(!taken.contains(x)) valid = false;
if(valid)
ans.add(cur);
taken.clear();
}
out.println(ans.size());
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));}
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(){for(long i = 0; i < 3e9; i++);}
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | b98ad9012fecd944167c3af223c7d9c5 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.StringTokenizer;
public class Main {
static boolean visited[] ;
static boolean ends[] ;
static long mod = 1000000007 ;
static int lens[] ;
static int seeds[] ;
static int a[] ;
static double total ;
public static ArrayList adj[] ;
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in) ;
int k = sc.nextInt() ;
int n = sc.nextInt() ;
int a[]= new int[k];
int cuma[]= new int[k] ;
int b[] = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = sc.nextInt() ;
}
cuma[0]=a[0];
for (int i = 1; i < k; i++)
{
cuma[i] = a[i]+cuma[i-1];
}
HashMap<Integer,Integer> h = new HashMap<Integer,Integer>() ;
HashMap<Integer,Integer> y = new HashMap<Integer,Integer>() ;
ArrayList<Integer> possibleX = new ArrayList<Integer>() ;
for (int i = 0; i < n; i++)
{
b[i]=sc.nextInt() ;
}
// int c=0 ;
// for (int i = 0; i <= k-n; i++)
// {
// for (int j = 0; j < b.length; j++)
// {
// int x = b[j]-cuma[i];
// for (int l = i; l < k; l++)
// {
// h.put(x+cuma[l], 0);
// }
// int taken =0 ;
// for (int l = 0; l < b.length; l++)
// {
// if(h.containsKey(b[l]))
// taken++;
// }
// if(taken==n && !y.containsKey(x))
// {c++; y.put(x,0);}
// h = new HashMap<Integer , Integer>() ;
// }
//
//
// }
// System.out.println(c);
y = new HashMap<Integer,Integer>() ;
h = new HashMap<Integer , Integer>() ;
for (int i = 0; i < k; i++)
{
int x = b[0]-cuma[i];
if(!y.containsKey(x))
{y.put(x,0) ; possibleX.add(x);}
}
int d=0 ;
for (int i = 0; i <possibleX.size(); i++)
{
for (int l = 0; l < k; l++)
{
h.put(possibleX.get(i)+cuma[l], 0);
}
int taken =0 ;
for (int l = 0; l < b.length; l++)
{
if(h.containsKey(b[l]))
taken++;
}
if(taken==n )
d++;
h = new HashMap<Integer , Integer>() ;
}
System.out.println(d);
}
static int even(String x , int b )
{
for (int j = b; j>=0; j--)
{
int current = x.charAt(j)-48 ;
if(current%2==0)
return current ;
}
return -1;
}
static int odd(String x , int b )
{
for (int j = b; j>=0; j--)
{
int current = x.charAt(j)-48 ;
if(current%2!=0)
return current ;
}
return -1;
}
static long pow(long base, int exp) {
long res = 1;
while(exp > 0) {
if(exp % 2 == 1) {
res = (res * base) % mod;
}
base = (base * base) % mod;
exp /= 2;
}
return res;
}
public static long solve(int k1, long k2)
{
long x = 1l*k2*(pow(2, k1)-1) ;
return x%(1000000007) ;
}
public static long getN(long x)
{
long n = (long) Math.sqrt(x*2) ;
long y = n*(n+1)/2;
if(y==x)
return n ;
else if(y>x)
return n ;
else
for (long i = n; ; i++)
{
y = i*(i+1)/2 ;
if(y>=x)
return i ;
} }
public static void dfss(int root , int len)
{
visited[root]=true ;
if(ends[root] && root!=0) lens[root] = len ;
for (int i = 0; i < adj[root].size(); i++)
{
int c= (int) adj[root].get(i) ;
if(visited[c]==false)
dfss(c, len+1);
}
}
public static void pr(int root , int seed){
visited[root] = true ;
int dv = adj[root].size()-1 ;
if(root==0) dv++ ;
for (int i = 0; i < adj[root].size(); i++)
{
int c = (int)adj[root].get(i) ;
seeds[c]=dv*seed ;
}
for (int i = 0; i < adj[root].size() ; i++)
{
int c = (int)adj[root].get(i) ;
if(visited[c]==false)
pr(c , seeds[c]);
}
}
public static String concatinate(String s ,int n)
{
if(s.length()==n)
return s ;
else return concatinate("0"+s, n) ;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
public static long getGCD(long n1, long n2) {
if (n2 == 0) {
return n1;
}
return getGCD(n2, n1 % n2);
}
public static int cnt1(int mat[][]) //how many swaps to be a 1 matrix
{
int m = mat.length ;
int c=0 ;
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
int x = (i*m) +j ;
if(x%2==0 && mat[i][j]==0)
c++;
if(x%2!=0 && mat[i][j]==1)
c++;
}
}
return c;
}
public static int cnt0(int mat[][])
{
int m = mat.length ;
int c=0 ;
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat.length; j++)
{
int x = (i*m) +j ;
if(x%2!=0 && mat[i][j]==0)
c++;
if(x%2==0 && mat[i][j]==1)
c++;
}
}
return c;
}
public static boolean canFit2(int x1, int y1 , int x2 , int y2 , int x3 , int y3){
if(x1==x2)
if(x1==x3)
return true ;
else
return false ;
else
if(x1==x3)
return false ;
else
{
long a = 1l*(y2-y1)*(x3-x2) ;
long b = 1l*(y3-y2)*(x2-x1) ;
if(a==b)
return true;
else
return false ;
}
}
public static void shuffle(long[] a2){
if(a2.length==1)
return ;
for (int i = 0; i < a2.length; i++)
{
Random rand = new Random();
int n = rand.nextInt(a2.length-1) + 0;
long temp = a2[i] ;
a2[i] = a2[n] ;
a2[n] = temp ;
}
}
public static int binary(long[]arr, int l, int r, long x) /// begin by 0 and n-1
{
if (r>=l)
{
int mid = l + (r - l)/2;
if (arr[mid]== x)
return mid;
if (arr[mid]> x)
return binary(arr, l, mid-1, x);
return binary(arr, mid+1, r, x);
}
return -1;
}
/// searching for the index of first elment greater than x
public static int binary1(long[]arr , long x) {
int low = 0, high = arr.length; // numElems is the size of the array i.e arr.size()
while (low != high) {
int mid = (low + high) / 2; // Or a fancy way to avoid int overflow
if (arr[mid] <= x) {
/* This index, and everything below it, must not be the first element
* greater than what we're looking for because this element is no greater
* than the element.
*/
low = mid + 1;
}
else {
/* This element is at least as large as the element, so anything after it can't
* be the first element that's at least as large.
*/
high = mid;
}
}
return low ; // return high ;
}
private static boolean triangle(int a, int b , int c){
if(a+b>c && a+c>b && b+c>a)
return true ;
else
return false ;
}
private static boolean segment(int a, int b , int c){
if(a+b==c || a+c==b && b+c==a)
return true ;
else
return false ;
}
private static int gcdThing(long a, long b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
public static boolean is(int i){
if(Math.log(i)/ Math.log(2) ==(int) (Math.log(i)/ Math.log(2)))
return true ;
if(Math.log(i)/ Math.log(3) ==(int) (Math.log(i)/ Math.log(3)) )
return true ;
if(Math.log(i)/ Math.log(6) ==(int) (Math.log(i)/ Math.log(6)) )
return true ;
return false;
}
public static boolean contains(int b[] , int x)
{
for (int i = 0; i < b.length; i++)
{
if(b[i]==x)
return true ;
}
return false ;
}
public static int binary(long []arr , long target , int low , long shift) {
int high = arr.length;
while (low != high) {
int mid = (low + high) / 2;
if (arr[mid]-shift <= target) {
low = mid + 1;
}
else {
high = mid;
}
}
return low ; // return high ;
}
public static boolean isLetter(char x){
if(x+0 <=122 && x+0 >=97 )
return true ;
else if (x+0 <=90 && x+0 >=65 )
return true ;
else return false;
}
public static long getPrimes(long x ){
if(x==2 || x==3 || x==1)
return 2 ;
if(isPrime(x))
return 5 ;
for (int i = 2; i*i<=x; i++)
{
if(x%i==0 && isPrime(i))
return getPrimes(x/i) ;
}
return -1;
}
public static String solve11(String x){
int n = x.length() ;
String y = "" ;
for (int i = 0; i < n-2; i+=2)
{
if(ifPalindrome(x.substring(i, i+2)))
y+= x.substring(i, i+2) ;
else
break ;
}
return y+ solve11(x.substring(y.length(),x.length())) ;
}
public static String solve1(String x){
String y = x.substring(0 , x.length()/2) ;
return "" ;
}
public static String reverse(String x){
String y ="" ;
for (int i = 0; i < x.length(); i++)
{
y = x.charAt(i) + y ;
}
return y ;
}
public static boolean ifPalindrome(String x){
int numbers[] = new int[10] ;
for (int i = 0; i < x.length(); i++)
{
int z = Integer.parseInt(x.charAt(i)+"") ;
numbers[z] ++ ;
}
for (int i = 0; i < numbers.length; i++)
{
if(numbers[i]%2!=0)
return false;
}
return true ;
}
public static int get(int n){
return n*(n+1)/2 ;
}
// public static long getSmallestDivisor( long y){
// if(isPrime(y))
// return -1;
//
// for (long i = 2; i*i <= y; i++)
// {
// if(y%i ==0)
// {
// return i;
// }
// }
// return -1;
// }
public static int lis( int[]a , int n){
int lis[] = new int[n] ;
Arrays.fill(lis,1) ;
for(int i=1;i<n;i++)
for(int j=0 ; j<i; j++)
if (a[i]>a[j] && lis[i] < lis[j]+1)
lis[i] = lis[j] + 1;
int max = lis[0];
for(int i=1; i<n ; i++)
if (max < lis[i])
max = lis[i] ;
return (max);
// ArrayList<Integer> s = new ArrayList<Integer>() ;
// for (int i = n-1; i >=0; i--)
// {
// if(lis[i]==max)
// {
// s.add(a[i].z);
// max --;
// }
// }
//
// for (int i = s.size()-1 ; i>=0 ; i--)
// {
// System.out.print(s.get(i)+" ");
// }
//
}
public static int calcDepth(Vertix node){
if(node.depth>0) return node.depth;
// meaning it has been updated before;
if(node.parent != null)
return 1+ calcDepth(node.parent);
else
return -1;
}
public static boolean isPrime (long num){
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;
}
public static ArrayList<Long> getDiv(Long n)
{
ArrayList<Long> f = new ArrayList<Long>() ;
while (n%2==0)
{
if(!f.contains(2))f.add((long) 2) ;
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (long i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(!f.contains(i))f.add(i);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
if(!f.contains(n))f.add(n);
return f ;
}
// public static boolean dfs(Vertix v , int target){
// try{
// visited[v.i]= true ;
// } catch (NullPointerException e)
// {
// System.out.println(v.i);
// }
// if(v.i == target)
//
// return true ;
// for (int i =0 ; i< v.neighbours.size() ; i++)
// {
//
// Vertix child = v.neighbours.get(i) ;
// if(child.i == target){
// found = true ;
// }
// if(visited[child.i]==false){
// found |= dfs(child, target) ;
// }
// }
// return found;
// }
public static class Vertix{
long i ;
int depth ;
ArrayList<Vertix> neighbours ;
Vertix parent ;
Vertix child ;
public Vertix(long i){
this.i = i ;
this.neighbours = new ArrayList<Vertix> () ;
this.parent = null ;
depth =-1;
this.child = null ;
}
}
public static class pair implements Comparable<pair>{
int index ;
long value ;
public pair(int x, long s ){
this.index=x ;
this.value = s;
}
@Override
public int compareTo(pair p) {
if(this.value > p.value)
return 1 ;
else if (this.value == p.value)
return 0 ;
else
return -1 ;
}
}
public static class pair2 implements Comparable<pair2>{
int i ;
int j ;
int plus ;
public pair2(int i , int j , int plus){
this.i =i ;
this.j = j ;
this.plus = plus ;
}
@Override
public int compareTo(pair2 p) {
if(this.j > p.j)
return 1 ;
else if (this.j == p.j) return 0 ;
else
return -1 ;
}
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 403c46b9b52edae7ac463c512efe9031 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.SplittableRandom;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn Agrawal coderbond007
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
static final int bound = (int) 8e6;
public void solve(int testNumber, FastReader in, PrintWriter out) {
int k = in.nextInt();
int n = in.nextInt();
int[] a = in.nextIntArray(k);
int[] b = in.nextIntArray(n);
for (int i = 1; i < k; i++) {
a[i] += a[i - 1];
}
ArrayUtils.sort(a);
int[] ptr = new int[n];
ArrayUtils.fill(ptr, k - 1);
int ans = 0;
main:
for (int x = -bound; x <= bound; ++x) {
for (int i = 0; i < n; ++i) {
int p = ptr[i];
while (p >= 0 && x + a[p] > b[i])
--p;
ptr[i] = p;
if (p == -1 || x + a[p] < b[i])
continue main;
}
++ans;
}
out.println(ans);
}
}
static class ArrayUtils {
public static int[] sort(int[] a) {
a = shuffle(a, new SplittableRandom());
Arrays.sort(a);
return a;
}
public static int[] shuffle(int[] a, SplittableRandom gen) {
for (int i = 0, n = a.length; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public static void fill(int[] array, int value) {
Arrays.fill(array, value);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
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) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 53d623eb02bc78d84319d21c140eed1c | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Set;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int K = in.nextInt();
int N = in.nextInt();
int[] A = new int[K];
for (int i = 0; i < K; i++) {
A[i] = in.nextInt();
}
int[] S = new int[K];
S[0] = A[0];
for (int i = 1; i < K; i++) {
S[i] = S[i - 1] + A[i];
}
int[] B = new int[N];
for (int i = 0; i < N; i++) {
B[i] = in.nextInt();
}
TreeSet<Integer> possibleScores = new TreeSet<>();
for (int i = 0; i < K; i++) {
int x = B[0] - S[i];
possibleScores.add(x);
}
int ans = 0;
for (int possibleScore : possibleScores) {
Set<Integer> marks = new TreeSet<>();
for (int i = 0; i < K; i++) {
marks.add(possibleScore + S[i]);
}
if (allPresent(marks, B)) {
ans++;
}
}
out.println(ans);
}
private boolean allPresent(Set<Integer> marks, int[] B) {
for (int b : B) {
if (!marks.contains(b)) return false;
}
return true;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | c8b399ce59eecf2717204b2efd8045f0 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 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.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int K = in.nextInt();
int N = in.nextInt();
int[] A = new int[K];
for (int i = 0; i < K; i++) {
A[i] = in.nextInt();
}
int[] S = new int[K];
S[0] = A[0];
for (int i = 1; i < K; i++) {
S[i] = S[i - 1] + A[i];
}
int[] B = new int[N];
for (int i = 0; i < N; i++) {
B[i] = in.nextInt();
}
TreeSet<Integer> ans = new TreeSet<>();
for (int i = 0; i < N; i++) {
TreeSet<Integer> possible = new TreeSet<>();
for (int j = 0; j < K; j++) {
//liczba Bi przyporzadkowana to wyniku Bi=X+Sj, czyli X = Bi-Sj
int x = B[i] - S[j];
possible.add(x);
}
if (i == 0) {
ans.addAll(possible);
} else {
ans = cross(ans, possible);
}
}
out.println(ans.size());
}
private TreeSet<Integer> cross(TreeSet<Integer> ans, TreeSet<Integer> possible) {
TreeSet<Integer> result = new TreeSet<>();
for (Integer x : ans) {
if (possible.contains(x)) {
result.add(x);
}
}
return result;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 6309edbea866a6629f6fc8ffc52ccea4 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer s = new StringTokenizer(br.readLine());
int k = Integer.parseInt(s.nextToken());
int n = Integer.parseInt(s.nextToken());
s = new StringTokenizer(br.readLine());
int[] a = new int[k];
int[] b = new int[n];
for(int i=0;i<k;i++){
a[i] = Integer.parseInt(s.nextToken());
}
s = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
b[i] = Integer.parseInt(s.nextToken());
}
int[] sum = new int[k];
sum[0] = a[0];
for(int i=1;i<k;i++) sum[i] = sum[i-1]+a[i];
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<k;i++){
int d = b[0]-sum[i];
hs.add(d);
}
int c =0;
for(int d:hs){
HashSet<Integer> h = new HashSet<Integer>();
for(int i=0;i<k;i++){
int x = sum[i]+d;
h.add(x);
}
boolean ok = true;
for(int i=0;i<n;i++){
if(!h.contains(b[i])){
ok = false;
break;
}
}
if(ok) c++;
}
System.out.println(c);
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | f8687540d757c4d206dd29c21b657848 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | //CodeForces Round 424 Problem C
import java.io.*;
import java.util.*;
public class cf424c {
static class InputReader{
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader (new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while(tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
}catch(IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main (String[] args) {
//CODE GOES HERE
int k = r.nextInt();
int n = r.nextInt();
int[] sum = new int[k];
sum[0] = r.nextInt();
for(int i=1; i<k; i++) {
sum[i] = sum[i-1] + r.nextInt();
}
HashSet<Integer> start = new HashSet<Integer>();
int d = r.nextInt();
for(int i=0; i<k; i++) {
start.add(d-sum[i]);
}
HashSet<Integer> know = new HashSet<Integer>();
know.add(d);
for(int i=1; i<n; i++) {
know.add(r.nextInt());
}
int count = 0;
for(int ele:start) {
HashSet<Integer> set = new HashSet<Integer>();
for(int i=0; i<k; i++) {
set.add(ele + sum[i]);
}
boolean work = true;
for(int pre:know) {
if(!set.contains(pre)) {
work = false;
break;
}
}
if(work) {
count++;
}
}
pw.println(count);
pw.close();
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | d9c0064152095b409cc61f01d1eec38b | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.*;
import java.util.*;
//I'm allergic to TLE :(
public class JuryMarks {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
HashSet<Integer> h=new HashSet<>();
int n=scan.nextInt(), k=scan.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++) {
int x=scan.nextInt();
if(i==0) a[i]=x;
else a[i]=a[i-1]+x;
h.add(a[i]);
}
int[] rem=new int[k];
for(int i=0;i<k;i++) rem[i]=scan.nextInt();
int res=0;
for(int x:h) {
boolean good=true;
int off=rem[0]-x;
for(int j:rem) {
if(!h.contains(j-off)) {
good=false;
break;
}
}
if(good) res++;
}
out.println(res);
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | e1961975e76da10dc38cebebf62452d1 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
/**
*
* @author Asus
*/
public class NewClass3 {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = 0, k= 0;
n = in.nextInt();
k = in.nextInt();
int[] a = new int[n];
int[] b = new int[k];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < k; i++) {
b[i] = in.nextInt();
}
int[] sum = new int[n];
sum[0] = a[0];
for (int i = 1; i < n; i++) {
sum[i] = sum[i - 1] + a[i];
}
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
set.add(b[0] - sum[i]);
}
int ans = 0;
for (int j : set) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (int i = 0; i < k; i++) {
set1.add(b[i]);
}
for (int i = 0; i < n; i++) {
set1.remove(j + sum[i]);
}
if (set1.isEmpty()) {
ans++;
}
}
System.out.println(ans);
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | e1f8656b606528d29ba884fc7d690fae | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger.*;
public class C424 {
public static boolean has(int[] a, int b)
{
int l=0, h=a.length - 1;
while (h-l>1)
{
int m = (l+h)/2;
if (a[m] > b) h = m;
else l = m;
}
return a[l] == b || a[h] == b;
//for (int i=0; i<a.length; ++i)
//if (a[i]==b) return true;
//return false;
}
public static void main(String[] qwertyuiop)
{
Scanner sc = new Scanner(System.in);
int k = sc.nextInt(); int n = sc.nextInt();
int[] a = new int[k];
for (int i=0; i<k; ++i) a[i] = sc.nextInt();
int[] b = new int[n];
for (int i=0; i<n; ++i) b[i] = sc.nextInt();
sc.close();
int M = b[0];
ArrayList<Integer> vals = new ArrayList<Integer>();
for (int i=0; i<k; ++i)
{
int[] c = new int[k];
c[i] = M;
for (int j=i-1; j>=0; --j) c[j] = c[j+1] - a[j+1];
for (int j=i+1; j<k; ++j) c[j] = c[j-1] + a[j];
boolean good = true;
Arrays.sort(c);
for (int r=0; r<n; ++r)
if (!has(c, b[r])) { good = false; break; }
if (good)
{
int t = c[0] - a[0];
if (!vals.contains(t))
vals.add(t);
}
}
System.out.println(vals.size());
return;
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 3d622e81c984cee4496c5e40140c8425 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class C {
public static void main(String[] args) throws IOException {
FastScanner in= new FastScanner(System.in);
PrintWriter out= new PrintWriter(System.out);
int k= in.nextInt();
int n= in.nextInt();
int [] a= new int[k];
HashSet<Integer> v= new HashSet<>();
int [] poss= new int[n];
a[0]= in.nextInt();
for (int i = 1; i < a.length; i++) {
a[i]= a[i-1]+ in.nextInt();
v.add(a[i]);
}
v.add(a[0]);
for (int i = 0; i < n; i++) {
poss[i]= in.nextInt();
}
Arrays.sort(poss);
int res=0;
for(int cur: v) {
boolean good= true;
int d= poss[0]-cur;
for (int i = 0; i < poss.length; i++) {
int thisstep= poss[i]-d;
if(!v.contains(thisstep)) {
good= false;
break;
}
}
if(good) res++;
}
System.out.println(res);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public String next() throws IOException {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
return next();
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | fcf6ab3884d63ce8f29ed4f12f6dcd1c | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import org.omg.CORBA.MARSHAL;
import javax.sound.sampled.Line;
import java.io.*;
import java.math.BigDecimal;
import java.nio.Buffer;
import java.util.*;
import java.util.concurrent.atomic.AtomicReferenceArray;
public class codeforces
{
// public static long fact[];
// public static int mod=1000000007;
public static long []st;
public static int k;
public static int[][] grid;
public static boolean[][] visit;
public static long n;
public static long b;
public static void main(String[] args) throws IOException {
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int k = in.nextInt();
int n = in.nextInt();
int[] judges = new int[k];
for (int i = 0; i < k; i++) {
judges[i] = in.nextInt();
}
int[] marks = new int[n];
for (int i = 0; i < n; i++) {
marks[i] = in.nextInt();
}
int ans = 0;
Set<Integer> answers = new HashSet<>();
for (int start = 0; start < k; start++) {
Set<Integer> values = new HashSet<>();
values.add( marks[0]);
//System.out.println("Start with " + judges[start] + " as " + marks[0]);
int cnt = marks[0];
for (int i = start + 1; i < k; i++) {
cnt += judges[i];
values.add(cnt);
}
cnt = marks[0];
for (int i = start; i >= 0; i--) {
cnt -= judges[i];
if (i != 0) {
values.add(cnt);
}
}
//System.out.println("Judges: " + values + " , original = " + cnt);
boolean isError = false;
for (int i = 0; i < n; i++) {
if (!values.contains(marks[i])) {
isError = true;
//System.out.println("Not containig " + marks[i]);
break;
}
}
if (!isError && !answers.contains(cnt)) {
ans++;
answers.add(cnt);
//System.out.println("Correct");
}
}
out.println(ans);
out.close();
}
public static long ts(long start, long end)
{
long l = start, r = end;
for(int i=0; i<200; i++) {
long l1 = (l*2+r)/3;
long l2 = (l+2*r)/3;
if(fc(l1) > fc(l2))
r = l2;
else
l = l1;
}
long x=l;
return x;
}
public static long fc(long x) {
return x*(n-x*b);
}
public static int bfs(int i,int j,int n,int m)
{
int troop=0;
Queue<node> qq=new LinkedList<>();
qq.add(new node(i,j));
while (!qq.isEmpty())
{
node cur=qq.poll();
troop++;
for (int r=-1;r<=1;r++)
{
for (int c=-1;c<=1;c++)
{
if(cur.x+r>=0 && cur.x+r<n && cur.y+c>=0 && cur.y+c<m)
{
if(!visit[cur.x+r][cur.y+c])
{
visit[cur.x+r][cur.y+c]=true;
if(grid[cur.x+r][cur.y+c]==1)
{
qq.add(new node(cur.x+r,cur.y+c));
}
}
}
}
}
}
return troop;
}
static class node{
int x;
int y;
public node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static int nextPowerOf2(final int a) {
int b = 1;
while (b < a) {
b = b << 1;
}
return b;
}
public static long []contruct(long []a)
{
int next2power=nextPowerOf2(a.length);
st=new long[next2power*2-1];
//System.out.println(size);
// st=new long[size];
Arrays.fill(st,Integer.MAX_VALUE);
constructST(a,0,a.length-1,0);
return st;
}
public static void constructST(long []a,int start,int end,int pos)
{
if(start==end)
{
st[pos]=a[start];
return ;
}
int mid=(start+end)>>1;
constructST(a,start,mid,pos*2+1);
constructST(a,mid+1,end,pos*2+2);
st[pos]=st[2*pos+1]^st[2*pos+2];
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private InputReader.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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | bbf50790a47d8b4bb0ac5506b5b7bfb6 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;
public class R424C {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int k = scan.nextInt();
int n = scan.nextInt();
int[] arr = new int[k];
int[] rem = new int[n];
for(int i = 0; i < k; i++){
arr[i] = scan.nextInt();
}
for(int i = 0; i < n; i++){
rem[i] = scan.nextInt();
}
HashSet<Integer> vals = new HashSet<Integer>();
int good = 0;
int add = 10_000_000;
int max = 25_000_000;
int rm = 0;
int[] poss = new int[max];
for(int i = 0; i < n; i++) {
int curr = 0;
vals.clear();
for(int j = 0; j < k; j++) {
curr += arr[j];
int val = rem[i] - curr;
if(!vals.contains(add + val)) {
poss[val + add]++;
rm = Math.max(rm, val+add+1);
vals.add(val + add);
}
}
}
for(int i = 0; i < max; i++) {
if(poss[i] == n) {
good++;
}
}
System.out.println(good);
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | c137db8fb928c7dbae5a91772862bb31 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.util.*;
public class r424c {
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int k=in.nextInt();
int n=in.nextInt();
int ar1[]=new int[k];
for(int i=0;i<k;i++)
ar1[i]=in.nextInt();
int ar2[]=new int[n];
HashSet<Integer> hs=new HashSet<Integer>();
for(int i=0;i<n;i++)
{
ar2[i]=in.nextInt();
hs.add(ar2[i]);
}
int x=ar2[0];
hs.remove(x);
int missing=k-n;
HashSet<Integer> hs1=new HashSet<Integer>();
hs1.addAll(hs);
HashSet<Integer> ans=new HashSet<Integer>();
for(int i=0;i<k;i++)
{
int l=x,r=x,p=missing;
hs.addAll(hs1);
for(int j=i;j>=0;j--)
{
if(j==0)
{
l-=ar1[j];
break;
}
l-=ar1[j];
if(!hs.contains(l))
p--;
else
hs.remove(l);
if(p<0)
break;
}
if(p<0)
continue;
for(int j=i+1;j<k;j++)
{
r+=ar1[j];
if(!hs.contains(r))
p--;
else
hs.remove(r);
if(p<0)
break;
}
//pw.println(l+" "+r+" "+p);
if(p>=0&&hs.size()==0)
ans.add(l);
}
pw.println(ans.size());
pw.close();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 364bf01106e248fb3f6d2f1ab6aae111 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author dipankar12
*/
import java.io.*;
import java.util.*;
public class r424c {
public static void main(String args[])
{
fastio in=new fastio(System.in);
PrintWriter pw=new PrintWriter(System.out);
int k=in.nextInt();
int n=in.nextInt();
int ar1[]=new int[k];
for(int i=0;i<k;i++)
ar1[i]=in.nextInt();
int ar2[]=new int[n];
HashSet<Integer> hs=new HashSet<Integer>();
for(int i=0;i<n;i++)
{
ar2[i]=in.nextInt();
hs.add(ar2[i]);
}
int x=ar2[0];
hs.remove(x);
int missing=k-n;
HashSet<Integer> hs1=new HashSet<Integer>();
hs1.addAll(hs);
HashSet<Integer> ans=new HashSet<Integer>();
for(int i=0;i<k;i++)
{
int l=x,r=x,p=missing;
hs.addAll(hs1);
for(int j=i;j>=0;j--)
{
if(j==0)
{
l-=ar1[j];
break;
}
l-=ar1[j];
if(!hs.contains(l))
p--;
else
hs.remove(l);
if(p<0)
break;
}
if(p<0)
continue;
for(int j=i+1;j<k;j++)
{
r+=ar1[j];
if(!hs.contains(r))
p--;
else
hs.remove(r);
if(p<0)
break;
}
//pw.println(l+" "+r+" "+p);
if(p>=0&&hs.size()==0)
ans.add(l);
}
pw.println(ans.size());
pw.close();
}
static class fastio {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int cchar, snchar;
private SpaceCharFilter filter;
public fastio(InputStream stream) {
this.stream = stream;
}
public int nxt() {
if (snchar == -1)
throw new InputMismatchException();
if (cchar >= snchar) {
cchar = 0;
try {
snchar = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snchar <= 0)
return -1;
}
return buf[cchar++];
}
public int nextInt() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nxt();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = nxt();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = nxt();
while (isSpaceChar(c)) {
c = nxt();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = nxt();
while (isSpaceChar(c))
c = nxt();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nxt();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | fc45598777d5670605339ade7cf18e42 | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.util.*;
import java.io.*;
public class meramainmahan {
public static void solve(int m[],ArrayList<Integer> g,int c[]){
int think,ans=0;
HashSet<Integer> set=new HashSet();
ArrayList<Integer> initials=new ArrayList();
HashSet<Integer> res;
for(int j=0;j<c.length;j++){
think=g.get(0)-c[j];
initials.add(think);
}
for(int i=0;i<initials.size();i++){
res=new HashSet();
int input=initials.get(i);
int count=0;
for(int j=0;j<c.length;j++){
res.add(input+c[j]);
}
for(int k=0;k<g.size();k++){
if(res.contains(g.get(k)))count++;
}
if(count==g.size()){
set.add(input);
ans++;
}
}
System.out.println(set.size());
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String nums[]=new String[2];
nums=br.readLine().split(" ");
int k=Integer.parseInt(nums[0]);
int n=Integer.parseInt(nums[1]);
int marks[]=new int[k];
int cusum[]=new int[k];
ArrayList<Integer> guess=new ArrayList();
int mincu=999999999,maxcu=-999999999;
String nums1[]=new String[k];
nums1=br.readLine().split(" ");
for(int i=0;i<k;i++){
marks[i]=Integer.parseInt(nums1[i]);
if(i!=0)cusum[i]=marks[i]+cusum[i-1];
else cusum[i]=marks[i];
}
String nums2[]=new String[n];
nums2=br.readLine().split(" ");
for(int i=0;i<n;i++){
guess.add(Integer.parseInt(nums2[i]));
}
solve(marks,guess,cusum);
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 4f6ac9c971b78446a162033bf3b01deb | train_003.jsonl | 1499958300 | Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (nββ€βk) values b1,βb2,β...,βbn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. nβ<βk. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant. | 256 megabytes | import java.util.*;
import java.io.*;
public class meramainmahan {
public static void solve(int m[],ArrayList<Integer> g,int c[]){
HashSet<Integer> set=new HashSet();
ArrayList<Integer> initials=new ArrayList();
HashSet<Integer> res=new HashSet();
int think,count=0,input,ans=0;
for(int j=0;j<c.length;j++){
think=g.get(0)-c[j];
initials.add(think);
}
for(int i=0;i<initials.size();i++){
input=initials.get(i);
count=0;
for(int j=0;j<c.length;j++)
res.add(input+c[j]);
for(int k=0;k<g.size();k++){
if(res.contains(g.get(k)))count++;
}
if(count==g.size()){
set.add(input);
ans++;
}
res.clear();
}
System.out.println(set.size());
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String nums[]=new String[2];
nums=br.readLine().split(" ");
int k=Integer.parseInt(nums[0]);
int n=Integer.parseInt(nums[1]);
int marks[]=new int[k];
int cusum[]=new int[k];
ArrayList<Integer> guess=new ArrayList();
String nums1[]=new String[k];
nums1=br.readLine().split(" ");
for(int i=0;i<k;i++){
marks[i]=Integer.parseInt(nums1[i]);
if(i!=0)cusum[i]=marks[i]+cusum[i-1];
else cusum[i]=marks[i];
}
String nums2[]=new String[n];
nums2=br.readLine().split(" ");
for(int i=0;i<n;i++){
guess.add(Integer.parseInt(nums2[i]));
}
solve(marks,guess,cusum);
}
} | Java | ["4 1\n-5 5 0 20\n10", "2 2\n-2000 -2000\n3998000 4000000"] | 2 seconds | ["3", "1"] | NoteThe answer for the first example is 3 because initially the participant could have β-β10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4β002β000. | Java 8 | standard input | [
"constructive algorithms",
"brute force"
] | 6e5b5d357e01d86e1a6dfe7957f57876 | The first line contains two integers k and n (1ββ€βnββ€βkββ€β2β000) β the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1,βa2,β...,βak (β-β2β000ββ€βaiββ€β2β000) β jury's marks in chronological order. The third line contains n distinct integers b1,βb2,β...,βbn (β-β4β000β000ββ€βbjββ€β4β000β000) β the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order. | 1,700 | Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes). | standard output | |
PASSED | 34580c08c1ac54ab45590f3b20efc087 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
public class Yo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
HashMap<Integer,Integer> map=new HashMap<>();
long ans=0;
for(int i=0;i<n;i++)
{
int pos=lastSetBit(arr[i]);
if(map.containsKey(pos))
{
ans+=map.get(pos);
map.put(pos,map.get(pos)+1);
}
else
{ map.put(pos,1);
}
}
System.out.println(ans);
}
}
static int lastSetBit(int n)
{
int k= (int)(Math.log(n)/Math.log(2));
return (int)(Math.pow(2, k));
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | d042704e6774bf0bac970090fe00a972 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.*;
import java.util.*;
public class MyClass
{
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<T> void pr(T... arg)
{
for(T x : arg)System.out.print(x + " ");
System.out.println();
}
public static<T> void prc(T... arg)
{
for(T x : arg)System.out.print(x + " ");
}
public static void main(String args[])
{
FastReader s = new FastReader();
int t = s.nextInt();
while(t!=0)
{
t--;
int n = s.nextInt();
int arr[] = new int[n];
for(int i = 0; i<n; i++)arr[i] = s.nextInt();
//pr(Arrays.toString(arr));
long bits[] = new long[32];
int last;
for(int i = 0; i<32; i++)bits[i] = 0;
for(int i = 0; i<n; i++)
{
last = -1;
for(int j = 31; j>=0; j--)if(((long)arr[i] & (1 << j)) > (long)0){last = j; break;}
bits[last]++;
}
long ans = 0;
for(int i = 0; i<32; i++)
ans += ((bits[i])*(bits[i]-1))/2;
pr(ans);
//pr(Arrays.toString(bits));
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | d75ffb47d8cf577f1065045bf6ae3ed9 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Hello{
public static class MyScanner{
BufferedReader read;
StringTokenizer token;
public MyScanner(){
read=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(token==null || !token.hasMoreElements()){
try{
token=new StringTokenizer(read.readLine());
}
catch(IOException e){
e.printStackTrace();
}
}
return token.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine(){
String str="";
try{
str=read.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)throws IOException{
MyScanner sc=new MyScanner();
///*
StringBuilder sb=new StringBuilder();
//System.out.println(logValue(1000000000));
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<n;i++) {
int val=sc.nextInt();
int lv=logValue(val);
map.put(lv, map.getOrDefault(lv,0)+1);
}
long ans=0;
for(Map.Entry<Integer,Integer> it:map.entrySet()) {
long val = it.getValue();
ans=ans+(val*(val-1))/2;
}
sb.append(ans+"\n");
}
System.out.println(sb);
//*/
}
static int logValue(int n) {
return (int)((Math.log(n))/(Math.log(2)));
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 40842e633763216bed9fe11e01ad0d17 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Hello{
public static class MyScanner{
BufferedReader read;
StringTokenizer token;
public MyScanner(){
read=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(token==null || !token.hasMoreElements()){
try{
token=new StringTokenizer(read.readLine());
}
catch(IOException e){
e.printStackTrace();
}
}
return token.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine(){
String str="";
try{
str=read.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)throws IOException{
MyScanner sc=new MyScanner();
///*
StringBuilder sb=new StringBuilder();
//System.out.println(logValue(1000000000));
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<n;i++) {
int val=sc.nextInt();
int lv=logValue(val);
map.put(lv, map.getOrDefault(lv,0)+1);
}
long ans=0;
for(Map.Entry<Integer,Integer> it:map.entrySet()) {
long val=it.getValue();
ans=ans+(val*(val-1))/2;
}
sb.append(ans+"\n");
}
System.out.println(sb);
//*/
}
static int logValue(int n) {
return (int)((Math.log(n))/(Math.log(2)));
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 612514a6d8b550b8ab413ab392b9819c | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
public class RockandLever {
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){
int n = Integer.parseInt(br.readLine());
String [] input_str = br.readLine().split(" ");
int []input = new int[n];
for(int i=0;i<n;i++){
input[i] = Integer.parseInt(input_str[i]);
}
HashMap<Integer, Integer> map = new HashMap<>();
long ans = 0;
for(int i:input){
i = Integer.highestOneBit(i);
ans+=map.getOrDefault(i, 0);
map.put(i, map.getOrDefault(i, 0)+1);
}
System.out.println(ans);
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 37ae412a00187a8035295e4d5d72135d | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int ii=0;ii<t;ii++) {
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
List<List<Integer>>li1=new ArrayList<>();
for(int j=0;j<n;j++) {
List<Integer>li=new ArrayList<>();
for(int i=0;i<63;i++) {
long f=1;
f=f<<i;
long res=f&arr[j];
if(res==0) {
li.add(0);
}
else{
li.add(1);
}
}
li1.add(li);
}
long count=0;
long st=0;
for(int i=0;i<63;i++) {
count=0;
for(int j=0;j<n;j++) {
int pow= 1<<i+1;
int pow2= 1<<i;
if(li1.get(j).get(i)==1&&arr[j]<pow&&arr[j]>=pow2) {
count++;
}
}
if(count!=1&&count!=0) {
st=(st+(count*(count-1)/2));
}
}
if(st>0) {
System.out.println(st);
}else{
System.out.println(0);
}
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | e2dedcfe75c8c8b779c4fb85646ddb20 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static long MOD = (long) (1e9 + 7);
static long powerLL(long x, long n)
{
long result = 1;
while (n > 0)
{
if (n % 2 == 1)
{
result = result * x % MOD;
}
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(String sa, String sb)
{
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++)
{
a = (a * 10 + (sa.charAt(i) - '0')) %
MOD;
}
for (int i = 0; i < sb.length(); i++)
{
b = (b * 10 + (sb.charAt(i) - '0')) %
(MOD - 1);
}
return powerLL(a, b);
}
static long gcd(long a, long b)
{
if (a==0) return b;
else return gcd(b%a,a);
}
static long lcm(long a, long b)
{
return (a*b)/gcd(a,b);
}
static int lower_bound(List<Integer> list, int k)
{
int s = 0;
int e = list.size();
while (s!=e)
{
int mid = (s+e)>>1;
if (list.get(mid)<k) s = mid+1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static int upper_bound(List<Integer> list, int k)
{
int s = 0;
int e = list.size();
while (s!=e)
{
int mid = (s+e)>>1;
if (list.get(mid)<=k) s = mid+1;
else e = mid;
}
if (s == list.size()) return -1;
return s;
}
static void addEdge(ArrayList<ArrayList<Integer>>graph, int edge1, int edge2)
{
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
static int BFS(ArrayList<ArrayList<Integer>>graph, int vertices, int source)
{
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
boolean[] visited = new boolean[vertices+1];
visited[source] = true;
//int count = 0;
int k = 0;
int count = 1;
int c = 0;
while (!queue.isEmpty())
{
int vertex = queue.poll();
if (vertex == 1) return count;
for (int i : graph.get(vertex))
{
if (i == 1) return count;
if (!visited[i])
{
count++;
visited[i] = true;
queue.add(i);
}
}
}
return count;
}
static int findmaxelements(List<Long>list1, List<Long>list2, int n)
{
n = list1.size();
// Index counter for arr1
int cnt1 = 0;
// Index counter for arr1
int cnt2 = 0;
// To store the maximum elements
int maxelements = 0;
while(cnt1 < n && cnt2 < n)
{
// If element is greater,
// update maxelements and counters
// for both the arrays
if(list1.get(cnt1) >= list2.get(cnt2))
{
maxelements++;
cnt1++;
cnt2++;
}
else
{
cnt1++;
}
}
// Print the maximum elements
//System.out.println(maxelements);
return maxelements;
}
public static void main(String[] args) throws java.lang.Exception
{
try
{
//FastReader fr = new FastReader();
Reader fr = new Reader();
try(OutputStream out = new BufferedOutputStream(System.out))
{
int queries = fr.nextInt();
while (queries -- > 0)
{
int n = fr.nextInt();
List<Long> list = new ArrayList<>();
for (int i=0;i<n;i++) list.add(fr.nextLong());
/*
0 0 0 1
0 1 0 0
0 0 1 1
0 1 1 1
1 0 1 0
1
1
1
6 -> 1 1 0 // 3 -> 1
5 -> 0 1 0 // 2 -> 1
2 -> 1 0 1 // 3 -> 2
3 -> 0 1 1 // 2 -> 2
*/
HashMap<Long,Long> setBits = new HashMap<>();
for (int i=0;i<n;i++)
{
String s = Long.toBinaryString(list.get(i));
long count = s.length();
for (int j=0;j<s.length();j++)
{
if (s.charAt(j) == '1')
{
if (setBits.containsKey(count)) setBits.put(count,setBits.get(count)+1);
else setBits.put(count,1L);
break;
}
else
{
count--;
}
}
}
long count = 0;
for (Map.Entry<Long,Long>entry : setBits.entrySet())
{
long freq = entry.getValue();
// out.write((freq+" ").getBytes());
if (freq>1) count+=((freq)*(freq-1))/2;
}
if (count == 0) out.write((count+"\n").getBytes());
else
{
// long ans = ((count)*(count-1))/2;
out.write((count+"\n").getBytes());
}
}
out.flush();
}
}
catch(Exception e){}
finally{}
}
}
//(()) () (()((()()()()))) | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | c9d7782d732d7025d578446ab3f634ef | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class A
{
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader fs;
static void in(int a[]) {
for (int i = 0; i < a.length; i++) {
a[i] = fs.nextInt();
}
}
static void in(long a[]) {
for (int i = 0; i < a.length; i++) {
a[i] = fs.nextLong();
}
}
static void in(int a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = fs.nextInt();
}
}
}
static void sort(int a[]) {
Arrays.sort(a);
}
static void sort(long a[]) {
Arrays.sort(a);
}
static void sort(String a[]) {
Arrays.sort(a);
}
static long diffSum(ArrayList<Long> al,int pos){
long sum=0,v=al.get(pos);
for(Long i:al)
sum+=Math.abs(i-v);
return sum;
}
static long count(ArrayList<Long> al){
if(al.size()%2==0)
return Math.max(diffSum(al,al.size()/2-1),diffSum(al,al.size()/2));
else
return diffSum(al,al.size()/2);
}
static long gcd(long a, long b)
{
if(b == 0l)
return a;
return gcd(b, a % b);
}
public static void main(String[] args)
{
fs=new FastReader();
int t;
t=fs.nextInt();
while(t-->0)
{
int n=fs.nextInt();
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=fs.nextLong();
long c=0l;
Arrays.sort(a);
int x[]=new int[n];
for(int i=0;i<n;i++)
x[i] = (int)(Math.log(a[i]) / Math.log(2));
int tmp=x[0];
long s=1l;
for(int i=1;i<n;i++)
{
if(x[i]==tmp)
{
c+=s;
s++;
}
else
{
tmp=x[i];
s=1l;
}
}
System.out.println(c);
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | eacfdbe689b6c89ac1fc7e9b9bc089df | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | // template halnix16
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Math.*;
public class Main {
static BufferedReader br;
public static void main(String[] args) throws Exception {
// write your code here
br = new BufferedReader(new InputStreamReader(System.in));
int t = (int)in();
while (t-->0){
int n = integer();
long arr[] = arr(n);
long f[] = new long[33];
for(int i =0;i<n;i++){
long val = arr[i];
for(int j=32;j>=0;j--){
long v = (1L<<j);
if((v&val)!=0){
f[j]+=1;
break;
}
}
}
long ans=0;
for(int i=0;i<33;i++){
// System.out.print(f[i]+" "+i+" ,");
ans += (f[i]*(f[i]-1))/2;
}
System.out.println(ans);
}
}
static long[] arr(long n) throws Exception {
String read[] = sarrin();
long arr[] = new long[(int) n];
for (int k = 0; k < n; k++)
arr[k] = in(read[k]);
return arr;
}
static long[][] arr(long n, long m) throws Exception {
long arr[][] = new long[(int) n][(int) m];
for (int k = 0; k < n; k++) {
String read[] = sarrin();
for (int j = 0; j < m; j++)
arr[k][j] = in(read[k]);
}
return arr;
}
static long in() throws Exception {
return Long.parseLong(br.readLine());
}
static long in(String num) throws Exception {
return Long.parseLong(num);
}
static String sin() throws Exception {
return br.readLine();
}
static String[] sarrin() throws Exception {
return br.readLine().split(" ");
}
static String[] regexSplit() throws Exception {
return br.readLine().split(" ?(?<!\\G)((?<=[^\\p{Punct}])(?=\\p{Punct})|\\b) ?");
}
static int integer() throws Exception{
return Integer.parseInt(br.readLine());
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 25074e135d5dd691a5fd0d8b61dd675c | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt();
long bits[]=new long[32];
for(int i=0;i<n;i++){
int a=sc.nextInt();
for(int j=31;j>=0;j--){
if((a&(1<<j))>0){
bits[j]++;break;
}
}
}
long ans=0;
for(int i=0;i<32;i++){
ans+=(bits[i]*(bits[i]-1))/2;
}
System.out.println(ans);
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | e7861c68cb0c64748952c507c8fc0ca5 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class B {
private static FastScanner fs = new FastScanner();
public static void main(String[] args) {
int t = fs.nextInt();
while(t-->0)
{
int n = fs.nextInt();
int digit[] = new int [31];
for(int i=0;i<n;i++)
{
int temp= fs.nextInt();
String a = Integer.toBinaryString(temp);
digit[a.length()]++;
}
long res =0;
for(int i=1;i<=30;i++)
{
if(digit[i]>=1)
{
res +=(((long)(digit[i])*(digit[i]-1))/2);
}
}
System.out.println(res);
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
int gcd(int a,int b)
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
private int upper(int arr[],int key){
int low = 0;
int high = arr.length-1;
while(low < high){
int mid = low + (high - low+1)/2;
if(arr[mid] <= key){
low = mid;
}
else{
high = mid-1;
}
}
return low;
}
public int lower(int arr[],int key){
int low = 0;
int high = arr.length-1;
while(low < high){
int mid = low + (high - low)/2;
if(arr[mid] >= key){
high = mid;
}
else{
low = mid+1;
}
}
return low;
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 5416fea662c236108fea8b95d248b193 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | // package codeforces672.cubessorting;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
while(T-->0){
int n=fs.nextInt();
HashMap<Integer,Integer> map = new HashMap<>();
int[] arr=fs.readArray(n);
long ans=0;
int k;
for(int i=0;i<n;i++){
k=Integer.highestOneBit(arr[i]);
if(map.containsKey(k)) {
map.put(k, map.get(k)+1);
} else {
map.put(k,0);
}
ans+=map.getOrDefault(k,0);
}
System.out.println(ans);
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 03fe8e6fa64b0cc6508303303784968e | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static int getpos(int val)
{
int cnt=0;
while(val!=0)
{
val=val>>1;
cnt++;
}
return cnt;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t-->0)
{
int n=s.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=s.nextInt();
long ans=0;
int map[]=new int[50];
for(int i=0;i<n;i++)
{
int cnt=getpos(arr[i]);
ans+=map[cnt];
map[cnt]++;
}
System.out.println(ans);
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 0ad2d2560a6ddde425bf557f0f2f0252 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
public class B_672 {
public static void main(String[] args) throws java.lang.Exception{
Scanner input = new Scanner(System.in);
int t = input.nextInt();
for(int i=0;i<t;i++){
input.nextLine();
int n = input.nextInt();
int[] nums = new int[n];
for(int j=0;j<n;j++){
nums[j] = input.nextInt();
}
long res = 0;
long count = 0;
for(int j=31;j>=0;j--){
count=0;
for(int k=0;k<nums.length;k++){
if(((nums[k]&(1<<j))==(1<<j))&&(nums[k]<(1<<(j+1)))){
count++;
}
}
res = res+((long)(count*(count-1)/2));
}
System.out.println(res);
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 5d609224b9f4200328d9864ec8389ce6 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
final static long mod = (long)10e9+7;
static void debug(Object...args)
{
System.out.println(Arrays.deepToString(args));
}
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
Random gen = new Random();
int test = sc.nextInt();
while(test-->0) {
StringBuffer sb = new StringBuffer();
int n = sc.nextInt();
int[] ar = sc.nextIntArray(n);
long ans = 0;
HashMap<Integer,Integer> map = new HashMap<>();
for(int i : ar)
{
i = Integer.highestOneBit(i);
ans += map.getOrDefault(i,0);
map.put(i,map.getOrDefault(i,0)+1);
}
pw.println(ans);
}
pw.flush();
pw.close();
}
static class Data implements Comparable<Data>{
int x, a;
public Data (int m, int n) {
x = m;
a = n;
}
@Override
public int compareTo(Data o) {
return a - o.a;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int [] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public static int[] shuffle(int[] a, Random gen)
{ for(int i = 0, n = a.length;i < n;i++)
{ int ind = gen.nextInt(n-i)+i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 7fabace6ee8221a3a60491f60ebb60bc | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
public static void main(String[] args){
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static final long mxx = (long)(1e18 + 5);
static final int mxN = (int)(1e6);
static final int mxV = (int)(1e6), log = 18;
static long mod = (long)(1e9+7);
static final int INF = (int)1e9;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, k, q;
static char[]str;
public static void solve() throws Exception {
// solve the problem here
s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
// out = new PrintWriter("output.txt");
int tc = s.nextInt();
for(int i=1; i<=tc; i++) {
// out.print("Case #" + i + ": ");
testcase();
}
out.flush();
out.close();
}
static void testcase() {
n = s.nextInt();
int[] a = s.nextIntArray(n);
int[] msbCount = new int[31];
for(int i=0; i<n; i++) {
int msb = getMsb(a[i]);
msbCount[msb]++;
}
long ans = 0;
for(int i=0; i<31; i++) {
ans += 1L * msbCount[i] * (msbCount[i] - 1) / 2;
}
out.println(ans);
}
private static int getMsb(int x) {
for(int j=31; j>=0; j--) {
if(((1<<j) & x) > 0)return j;
}
return -1;
}
public static PrintWriter out;
public static MyScanner s;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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()); }
int[] nextIntArray(int n){
int[]a = new int[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextlongArray(int n) {
long[]a = new long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
Integer[] nextIntegerArray(int n){
Integer[]a = new Integer[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[]a = new Long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
char[][] next2DCharArray(int n, int m){
char[][]arr = new char[n][m];
for(int i=0; i<n; i++) {
arr[i] = this.next().toCharArray();
}
return arr;
}
ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
return adj;
}
ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
}
return adj;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 39193d6127d38af769adddd0fe66de2a | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
public static void main(String[] args){
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static final long mxx = (long)(1e18 + 5);
static final int mxN = (int)(1e6);
static final int mxV = (int)(1e6), log = 18;
static long mod = (long)(1e9+7);
static final int INF = (int)1e9;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, k, q;
static char[]str;
public static void solve() throws Exception {
s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
int tc = s.nextInt();
for(int i=1; i<=tc; i++) {
testcase();
}
out.flush();
out.close();
}
static void testcase() {
n = s.nextInt();
int[] a = s.nextIntArray(n);
int[] msbCount = new int[31];
for(int i=0; i<n; i++) {
int msb = getMsb(a[i]);
msbCount[msb]++;
}
long ans = 0;
for(int i=0; i<31; i++) {
ans += 1L * msbCount[i] * (msbCount[i] - 1) / 2;
}
out.println(ans);
}
private static int getMsb(int x) {
for(int j=31; j>=0; j--) {
if(((1<<j) & x) > 0)return j;
}
return -1;
}
public static PrintWriter out;
public static MyScanner s;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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()); }
int[] nextIntArray(int n){
int[]a = new int[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextlongArray(int n) {
long[]a = new long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
Integer[] nextIntegerArray(int n){
Integer[]a = new Integer[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[]a = new Long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
char[][] next2DCharArray(int n, int m){
char[][]arr = new char[n][m];
for(int i=0; i<n; i++) {
arr[i] = this.next().toCharArray();
}
return arr;
}
ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
return adj;
}
ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
}
return adj;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 1b791c94122b423edb515b690b4ac805 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 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.Random;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
int[] a=fs.readArray(n);
HashMap<Integer, Integer> map=new HashMap<>();
long ans=0;
for (int i:a) {
i=Integer.highestOneBit(i);
ans+=map.getOrDefault(i, 0);
map.put(i, map.getOrDefault(i, 0)+1);
}
System.out.println(ans);
}
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 45f6b57c307c01fae9bf2b94c4477c36 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Main {
public static void main(String[] args){
new Thread(null, null, "Anshum Gupta", 99999999) {
public void run() {
try {
solve();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static final long mxx = (long)(1e18 + 5);
static final int mxN = (int)(1e6);
static final int mxV = (int)(1e6), log = 18;
static long mod = (long)(1e9+7); //
static final int INF = (int)1e9;
static boolean[]vis;
static ArrayList<ArrayList<Integer>> adj;
static int n, m, k, q;
static char[]str;
public static void solve() throws Exception {
// solve the problem here
s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
// out = new PrintWriter("output.txt");
int tc = s.nextInt();
for(int i=1; i<=tc; i++) {
// out.print("Case #" + i + ": ");
testcase();
}
out.flush();
out.close();
}
static void testcase() {
n = s.nextInt();
int[] a = s.nextIntArray(n);
int[] msbCount = new int[31];
for(int i=0; i<n; i++) {
int msb = getMsb(a[i]);
msbCount[msb]++;
}
long ans = 0;
for(int i=0; i<31; i++) {
ans += 1L * msbCount[i] * (msbCount[i] - 1) / 2;
}
out.println(ans);
}
private static int getMsb(int x) {
for(int j=31; j>=0; j--) {
if(((1<<j) & x) > 0)return j;
}
return -1;
}
public static PrintWriter out;
public static MyScanner s;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
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()); }
int[] nextIntArray(int n){
int[]a = new int[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextlongArray(int n) {
long[]a = new long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
Integer[] nextIntegerArray(int n){
Integer[]a = new Integer[n];
for(int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[]a = new Long[n];
for(int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
char[][] next2DCharArray(int n, int m){
char[][]arr = new char[n][m];
for(int i=0; i<n; i++) {
arr[i] = this.next().toCharArray();
}
return arr;
}
ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
adj.get(v).add(u);
}
return adj;
}
ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) {
ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>());
for(int i=0; i<m; i++) {
int u = s.nextInt();
int v = s.nextInt();
adj.get(u).add(v);
}
return adj;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | d2f0248797adae0a4799091075a43e5a | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes |
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class B {
public static PrintWriter out = new PrintWriter(System.out);
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int t = ni();
while (t-- > 0) solve();
out.flush();
}
private static void solve() {
int n = ni();
int[] a = na(n);
long[] bits = new long[32];
for (int i = 0; i < n; i++) {
int msb = (int) (Math.log(Integer.highestOneBit(a[i])) / Math.log(2));
bits[msb]++;
}
long sum = 0;
for (long x : bits) sum += (x * (x - 1) / 2);
out.println(sum);
}
private static int ni() {
return in.nextInt();
}
private static int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private static long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
private static long nl() {
return in.nextLong();
}
private float nf() {
return in.nextFloat();
}
private static double nd() {
return in.nextDouble();
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 722d9ee79e5a7ce7013bf6109f0fe014 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int looplim=sc.nextInt();
for(int iter=0;iter<looplim;iter++)
{int n=sc.nextInt();
long[] arr=new long[32];
int temp=0,remp;
for(int i=0;i<n;i++)
{
temp=sc.nextInt();
remp=(int)(Math.log(temp) / Math.log(2));
arr[remp]++;
}
long cunt=0;
for(int i=0;i<32;i++)
{if(arr[i]>1)
{cunt+= arr[i]*(arr[i]-1)/2;
}
}
System.out.println(cunt);
// your code goes here
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 7871bc971d0010b4e95ee7d21e90fc95 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
import java.util.HashMap;
public class rock{
public static void main(String[] args) {
Scanner fs = new Scanner(System.in);
int T = fs.nextInt();
for(int t = 0;t<T;t++){
int n = fs.nextInt();
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = fs.nextInt();
}
HashMap<Integer,Integer> hmap = new HashMap<>();
long ans = 0;
for(int i : arr){
i = Integer.highestOneBit(i);
ans += hmap.getOrDefault(i,0);
hmap.put(i,hmap.getOrDefault(i,0)+1);
}
System.out.println(ans);
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 3e88a7f6845476039c428d9837476c40 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class solution {
public static void main (String[] args) {
//code
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
long[] a=new long[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextLong();
}
long[] b=new long[33];
for(int i=0;i<n;i++)
{
int count=0;
long z=a[i];
while(z!=0)
{
z>>=1;
count++;
}
b[count]++;
}
long ans=0;
for(int i=0;i<33;i++)
{
ans+=b[i]*(b[i]-1)/2;
}
System.out.println(ans);
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 156f79c59d63067baacc6cd6031dd8a8 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
public class rock_and_lever {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int[] a=new int[n+1];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
long[] b=new long[32];
for(int i=0;i<n;i++) {
String s=Integer.toBinaryString(a[i]);
b[s.length()-1]++;
}
long sum=0;
for(int i=0;i<32;i++) {
sum+=(b[i]*b[i]-b[i])/2;
}
System.out.println(sum);
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 433e0152cee1eac77566910bc3a8711c | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
public class Rock {
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
int t = scan.nextInt();
for (int l = 0; l < t; l++) {
int n = scan.nextInt(); int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = Integer.toBinaryString(scan.nextInt()).length();
long count = 0; long cur = 0;
Arrays.sort(arr);
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) cur++;
if (arr[i] != arr[i - 1] || i == n - 1) {
count += ((long)cur*((long)cur + 1))/2;
cur = 0;
}
}
System.out.println(count);
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 26f131d7d2672e049346cda87335dc99 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class rocklever
{
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) throws IOException
{
FastReader s=new FastReader();
int t = s.nextInt();
while (t-->0){
int n = s.nextInt();
String s1 = s.nextLine();
String[] tk = s1.split(" ");
long[] a = new long [n];
for (int i=0; i<n; i++)
a[i] = Long.parseLong(tk[i]);
long[] b = new long[n];
long[] f = new long[61];
if (n==1)
System.out.println("0");
else{
long sm = 0;
for (int i=0; i<n; i++){
b[i] = (long)(Math.log(a[i])/Math.log(2));
f[(int)b[i]]++;
}
for (int i=0; i<60; i++){
if(f[i]>1)
sm+=f[i]*(f[i]-1)/2;
}
System.out.println(sm);
}
}
}
} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 92839feb2b054126dd3211c5073af10d | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
//System.out.println(t);
int max=0;
int n=sc.nextInt();
int ar[]=new int[n];
for(int x=0;x<n;x++)
{
ar[x]=sc.nextInt();
if(ar[x]>max)
max=ar[x];
}
int nb=0;
while(max!=0)
{
nb++;
max/=2;
}
long bits[]=new long[nb+1];
for(int x=0;x<n;x++)
{
int temp=ar[x];
int c=0;
while(temp!=0)
{
c++;
temp/=2;
}
bits[c]++;
}
long sum=0;
for(int x=1;x<=nb;x++)
{
long c=bits[x];
c=c*(c-1);
c/=2l;
sum+=c;
}
System.out.println(sum);
}
//System.out.println("Hello World");
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | fa0fe5093433b3f0b019a9dc399e4dab | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.ArrayList;
import java.util.Scanner;
public class adaking {
static class pair
{
int first;
int second;
pair(int a, int b)
{
first = a;
second = b;
}
}
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 final int mod = 1000000007;
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static String findSubString(String str, String pat)
{
int len1 = str.length();
int len2 = pat.length();
// check if string's length is less than pattern's
// length. If yes then no such window can exist
if (len1 < len2)
{
System.out.println("No such window exists");
return "";
}
int hash_pat[] = new int[256];
int hash_str[] = new int[256];
// store occurrence ofs characters of pattern
for (int i = 0; i < len2; i++)
hash_pat[pat.charAt(i)]++;
int start = 0, start_index = -1, min_len = Integer.MAX_VALUE;
// start traversing the string
int count = 0; // count of characters
for (int j = 0; j < len1 ; j++)
{
// count occurrence of characters of string
hash_str[str.charAt(j)]++;
// If string's char matches with pattern's char
// then increment count
if (hash_pat[str.charAt(j)] != 0 &&
hash_str[str.charAt(j)] <= hash_pat[str.charAt(j)] )
count++;
// if all the characters are matched
if (count == len2)
{
// Try to minimize the window i.e., check if
// any character is occurring more no. of times
// than its occurrence in pattern, if yes
// then remove it from starting and also remove
// the useless characters.
while ( hash_str[str.charAt(start)] > hash_pat[str.charAt(start)]
|| hash_pat[str.charAt(start)] == 0)
{
if (hash_str[str.charAt(start)] > hash_pat[str.charAt(start)])
hash_str[str.charAt(start)]--;
start++;
}
// update window size
int len_window = j - start + 1;
if (min_len > len_window)
{
min_len = len_window;
start_index = start;
}
}
}
// If no window found
if (start_index == -1)
{
System.out.println("No such window exists");
return "";
}
// Return substring starting from start_index
// and length min_len
return str.substring(start_index, start_index + min_len);
}
public static int first(int arr[],int n,int ind,HashMap<Integer,Integer>hm)
{
int c=0;
for(int j=0;j<ind;j++)
{
if(hm.get(j)!=null)
{
for(int in=ind+1;in<n;in++)
{
if(hm.get(in)==null&&arr[in]<arr[j])
{
hm.put(in,1);
c++;
}
}
}
}
for(int j=ind+1;j<n;j++)
{
if(hm.get(j)!=null)
{
for(int in=ind-1;in>=0;in--)
{
if(hm.get(in)==null&&arr[in]>arr[j])
{
hm.put(in,1);
c++;
}
}
}
}
return c;
}
public static long second(int arr[][],int n)
{
long res=0;
int k=n-1;
int ind1=n-1;
while (ind1>0)
{
int q=ind1+1;
if(res%2!=0)
{
if(arr[n-k-1][ind1]==q)
res++;
}
else
{
if(arr[n-k-1][ind1]!=q)
res++;
}
ind1--;
}
//System.out.println(res);
return (res);
}
public static void calculeate(int a[][],int n)
{
int res=0;
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
if(k!=a[k][j])
{
if(res%2==0)
res++;
else
res+=2;
}
}
}
//System.out.println(res);
long s=second(a,n);
System.out.println(s);
}
public static int[][] merge(int[][] intervals)
{
int n=intervals.length;
pair a[]=new pair[n];
for(int j=0;j<n;j++)
{
a[j]=new pair(intervals[j][0],intervals[j][1]);
}
Arrays.sort(a,new Comparator<pair>(){
@Override
public int compare(pair p1, pair p2)
{
return p1.first-p2.first;
}
});
ArrayList<pair>li=new ArrayList<>();
int s=a[0].first;
int e=a[0].second;
for(int j=1;j<n;j++)
{
if(e>=a[j].first)
{
e=Math.max(e,a[j].second);
}
else
{
li.add(new pair(s,e));
//System.out.println(s+" "+e);
s=a[j].first;
e=a[j].second;
//System.out.println(s+" "+e);
}
}
li.add(new pair(s,e));
//System.out.println(li);
int res[][]=new int[li.size()][2];
for(int j=0;j<li.size();j++)
{
res[j][0]=li.get(j).first;
res[j][1]=li.get(j).second;
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
//sc.nextLine();
for (int test = 0; test < t; test++)
{
int n=sc.nextInt();
long a[]=new long[n];
int b[]=new int[n];
HashMap<Integer,Integer>hm=new HashMap<>();
for(int j=0;j<n;j++)
{
a[j]=sc.nextLong();
}
long ans=0;
for(int j=29;j>=0;j--)
{
long c=0;
for(int k=0;k<n;k++)
{
if(a[k]>=(1<<j)&&a[k]<(1<<(j+1)))
{
c++;
}
}
ans+=c*(c-1)/2;
}
System.out.println(ans);
}
}
}
| Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 5792f7b52130089206aaee17d8cdd7c9 | train_003.jsonl | 1600958100 | "You must lift the dam. With a lever. I will give it to you.You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.You are given a positive integer $$$n$$$, and an array $$$a$$$ of positive integers. The task is to calculate the number of such pairs $$$(i,j)$$$ that $$$i<j$$$ and $$$a_i$$$ $$$\&$$$ $$$a_j \ge a_i \oplus a_j$$$, where $$$\&$$$ denotes the bitwise AND operation, and $$$\oplus$$$ denotes the bitwise XOR operation.Danik has solved this task. But can you solve it? | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
//solution start :-)
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
ArrayList<Integer> al = new ArrayList<>();
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
long co = 0;
long sum = 0;
for(int i=0;i<(n-1);i++) {
//System.out.println((int)(Math.log(a[i])/Math.log(2))+" "+(int)(Math.log(a[i+1])/Math.log(2)));
if((int)(Math.log(a[i])/Math.log(2))==(int)(Math.log(a[i+1])/Math.log(2))) co++;
else {
sum+=(co*(co+1))/2;
co=0;
}
// System.out.println(sum);
}
sum+=(co*(co+1))/2;
System.out.println(sum);
}
//solution end <-_->
}} | Java | ["5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1"] | 1 second | ["1\n3\n2\n0\n0"] | NoteIn the first test case there is only one pair: $$$(4,7)$$$: for it $$$4$$$ $$$\&$$$ $$$7 = 4$$$, and $$$4 \oplus 7 = 3$$$.In the second test case all pairs are good.In the third test case there are two pairs: $$$(6,5)$$$ and $$$(2,3)$$$.In the fourth test case there are no good pairs. | Java 11 | standard input | [
"bitmasks",
"math"
] | 04e2e1ce3f0b4efd2d4dda69748a0a25 | Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10$$$) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 10^5$$$)Β β length of the array. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 1,200 | For every test case print one non-negative integerΒ β the answer to the problem. | standard output | |
PASSED | 4fa1bba19a322ab6fd073ec63160629a | train_003.jsonl | 1406480400 | You are given three strings (s1,βs2,βs3). For each integer l (1ββ€βlββ€βmin(|s1|,β|s2|,β|s3|) you need to find how many triples (i1,βi2,βi3) exist such that three strings sk[ik... ikβ+βlβ-β1] (kβ=β1,β2,β3) are pairwise equal. Print all found numbers modulo 1000000007Β (109β+β7).See notes if you are not sure about some of the denotions used in the statement. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf452e {
public static void main(String[] args) throws IOException {
char s[][] = {rcha(), rcha(), rcha()};
int len[] = {s[0].length, s[1].length, s[2].length}, n = minof(len), ansdiff[] = new int[n + 1];
int suf0[] = suffix(s[0]), lcp0[] = lcp(s[0], suf0);
char[] str = new char[len[0] + 1 + len[1] + 1 + len[2]];
int tag[] = new int[str.length], cnt[][] = new int[str.length + 1][3];
fill(tag, -1);
{
int ind = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < len[i]; ++j) {
tag[ind] = i;
str[ind++] = s[i][j];
}
if (i < 2) {
str[ind++] = '#';
}
}
}
int suf[] = suffix(str), lcp[] = lcp(str, suf), invsuf[] = new int[len[0]];
for (int i = 1; i <= str.length; ++i) {
if (suf[i] < len[0]) {
invsuf[suf[i]] = i;
}
}
for (int i = 1; i <= str.length; ++i) {
for (int j = 0; j < 3; ++j) {
cnt[i][j] = cnt[i - 1][j] + (tag[suf[i]] == j ? 1 : 0);
}
}
SpTb rmq = new SpTb(lcp);
// prln(lcp);
// for (int i : suf) {
// prln(new String(str, i, str.length - i));
// }
for (int i = 1; i <= len[0]; ++i) {
int curlen = 0, lb = str.length - 1, ub = 3;
for (int l = 1, r = min(n, len[0] - suf0[i]); l <= r; ) {
int m = l + (r - l) / 2, llb = invsuf[suf0[i]], uub = invsuf[suf0[i]];
for (int ll = 3, rr = invsuf[suf0[i]] - 1; ll <= rr; ) {
int mm = ll + (rr - ll) / 2, cp = rmq.qry(invsuf[suf0[i]], mm);
if (cp >= m) {
llb = mm;
rr = mm - 1;
} else {
ll = mm + 1;
}
}
for (int ll = invsuf[suf0[i]] + 1, rr = str.length; ll <= rr; ) {
int mm = ll + (rr - ll) / 2, cp = rmq.qry(invsuf[suf0[i]], mm);
if (cp >= m) {
uub = mm;
ll = mm + 1;
} else {
rr = mm - 1;
}
}
// prln(llb, uub, cnt[uub][0] - cnt[llb - 1][0], cnt[uub][1] - cnt[llb - 1][1], cnt[uub][2] - cnt[llb - 1][2]);
if (llb <= uub && cnt[uub][0] - cnt[llb - 1][0] > 0 && cnt[uub][1] - cnt[llb - 1][1] > 0 && cnt[uub][2] - cnt[llb - 1][2] > 0) {
curlen = m;
lb = llb;
ub = uub;
l = m + 1;
} else {
r = m - 1;
}
}
// prln(curlen, lb, ub);
while (curlen > lcp0[i - 1]) {
// pr("\t");
// prln(curlen, cnt[ub][0] - cnt[lb - 1][0], cnt[ub][1] - cnt[lb - 1][1], cnt[ub][2] - cnt[lb - 1][2]);
int add = mmul(cnt[ub][0] - cnt[lb - 1][0], cnt[ub][1] - cnt[lb - 1][1], cnt[ub][2] - cnt[lb - 1][2]);
int nextlen = max(lcp[lb - 1], ub < str.length ? lcp[ub] : 0);
ansdiff[nextlen] = madd(ansdiff[nextlen], add);
ansdiff[curlen] = msub(ansdiff[curlen], add);
while (lb > 0 && lcp[lb - 1] >= nextlen) {
--lb;
}
while (ub < str.length && lcp[ub] >= nextlen) {
++ub;
}
curlen = nextlen;
}
}
int[] ans = new int[n];
ans[0] = ansdiff[0];
for (int i = 1; i < n; ++i) {
ans[i] = madd(ans[i - 1], ansdiff[i]);
}
prln(ans);
close();
}
// cannot use with summation
static class SpTb {
int n, lg[], lookup[][];
SpTb(int[] a) {
n = a.length + 1;
int[] arr = new int[n];
for (int i = 0; i < n - 1; ++i) {
arr[i] = a[i];
}
a = arr;
lg = new int[n + 1];
int pow2 = 4;
for (int i = 2, ind = 1; i <= n; ++i) {
if (pow2 == i) {
++ind;
pow2 <<= 1;
}
lg[i] = ind;
}
lookup = new int[n][lg[n] + 1];
for (int i = 0; i < n; ++i) {
lookup[i][0] = a[i];
}
for (int j = 1; (1 << j) <= n; ++j) {
for (int i = 0; (i + (1 << j)) <= n; ++i) {
lookup[i][j] = min(lookup[i][j - 1], lookup[i + (1 << (j - 1))][j - 1]);
}
}
}
int qry(int l, int r) {
if (r < l) {
int __swap = l;
l = r;
r = __swap;
}
int j = lg[r - l];
return min(lookup[l][j], lookup[r - (1 << j)][j]);
}
}
static int mmod = 1000000007;
static int madd(int a, int b) {
return (a + b) % mmod;
}
static int madd(int... a) {
int ans = a[0];
for (int i = 1; i < a.length; ++i) {
ans = madd(ans, a[i]);
}
return ans;
}
static int msub(int a, int b) {
return (a - b + mmod) % mmod;
}
static int mmul(int a, int b) {
return (int) ((long) a * b % mmod);
}
static int mmul(int... a) {
int ans = a[0];
for (int i = 1; i < a.length; ++i) {
ans = mmul(ans, a[i]);
}
return ans;
}
static int minv(int x) {
return mpow(x, mmod - 2);
}
static int mpow(int a, int b) {
if (a == 0) {
return 0;
}
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) {
ans = mmul(ans, a);
}
a = mmul(a, a);
b >>= 1;
}
return ans;
}
// suffix(str) returns suffix arr of str
// lcp(str<, sufarr>) returns longest common prefix arr of str
static int[] lcp(char[] s) {
return lcp(s, suffix(s));
}
static int[] lcp(char[] s, int[] suf) {
int n = s.length, rank[] = new int[n + 1], ans[] = new int[n], k = 0;
for (int i = 0; i <= n; ++i) rank[suf[i]] = i;
for (int i = 0; i < n; ++i) {
if (k > 0) --k;
int p = suf[rank[i] - 1];
while (i + k < n && p + k < n && s[i + k] == s[p + k]) ++k;
ans[rank[i] - 1] = k;
}
return ans;
}
static int[] suffix(char[] s) {
int n = s.length + 1, ans[] = new int[n], cls[] = new int[n], cnt[] = new int[128], ncls[] = new int[n];
ans[0] = n - 1;
for (char c : s) ++cnt[c];
for (int i = 1; i < 128; ++i) cnt[i] += cnt[i - 1];
for (int i = 0; i < n - 1; ++i) ans[cnt[s[i]]--] = i;
cls[ans[1]] = 1;
for (int i = 2; i < n; ++i) cls[ans[i]] = cls[ans[i - 1]] + (s[ans[i]] > s[ans[i - 1]] ? 1 : 0);
for (int offset = 1; offset <= n; offset <<= 1) {
cntsort(ans, cls, n, offset);
cntsort(ans, cls, n, 0);
fill(ncls, 0);
for (int i = 1; i < n; ++i)
ncls[ans[i]] = ncls[ans[i - 1]] + (cls[ans[i]] > cls[ans[i - 1]] || cls[(ans[i] + offset) % n] > cls[(ans[i - 1] + offset) % n] ? 1 : 0);
cls = copy(ncls);
}
return ans;
}
static void cntsort(int[] a, int[] by, int n, int offset) {
int[] cnt = new int[n + 1], ans = new int[n];
for (int b : by) ++cnt[b + 1];
for (int i = 1; i <= n; ++i) cnt[i] += cnt[i - 1];
for (int i = 0; i < n; ++i) ans[cnt[by[(a[i] + offset) % n]]++] = a[i];
for (int i = 0; i < n; ++i) a[i] = ans[i];
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int)d;}
static int cei(double d) {return (int)ceil(d);}
static long fll(double d) {return (long)d;}
static long cel(double d) {return (long)ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long hash(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// graph util
static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;}
static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;}
static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);}
static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);}
static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);}
static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;}
static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);}
static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;}
static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();}
static void h() {__out.println("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["abc\nbc\ncbc", "abacaba\nabac\nabcd"] | 2 seconds | ["3 1", "11 2 0 0"] | NoteConsider a string tβ=βt1t2... t|t|, where ti denotes the i-th character of the string, and |t| denotes the length of the string.Then t[i... j] (1ββ€βiββ€βjββ€β|t|) represents the string titiβ+β1... tj (substring of t from position i to position j inclusive). | Java 11 | standard input | [
"data structures",
"dsu",
"string suffix structures",
"strings"
] | 607dd33e61f57caced7b61ca8001e871 | First three lines contain three non-empty input strings. The sum of lengths of all strings is no more than 3Β·105. All strings consist only of lowercase English letters. | 2,400 | You need to output min(|s1|,β|s2|,β|s3|) numbers separated by spaces β answers for the problem modulo 1000000007Β (109β+β7). | standard output | |
PASSED | ace8c057cd652582e548f2954c339829 | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main (String[]args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] lengths = new int[n];
for (int i = 0; i < n; i++)
lengths[i] = scanner.nextInt();
int numAlive = 0;
int kill = n;
for (int i = n - 1; i >= 0; i--) {
if (i < kill)
numAlive++;
kill = Math.min(kill, i - lengths[i]);
}
System.out.println(numAlive);
}
}
| Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | f18effa264e5b315efd870afb1393795 | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF892B extends PrintWriter {
CF892B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF892B o = new CF892B(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int[] ll = new int[n];
for (int i = 0; i < n; i++)
ll[i] = sc.nextInt();
int ans = 0, k = n;
for (int i = n - 1; i >= 0; i--) {
if (i < k)
ans++;
k = Math.min(k, i - ll[i]);
}
println(ans);
}
}
| Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | 41444173e592266980f055d577b23aa9 | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | import org.w3c.dom.ls.LSOutput;
import java.util.*;
import java.lang.*;
import java.io.*;
public class RPS {
public static void main(String[] args) throws java.lang.Exception {
// BufferedReader br = new BufferedReader(new InputStreamReader((System.in)));
// StringTokenizer s = new StringTokenizer(br.readLine());
// int n = Integer.parseInt(s.nextToken());
// s = new StringTokenizer(br.readLine());
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] claws = new int[n];
for (int i = 0; i < n; i++)
claws[i] = in.nextInt();
int numAlive = 0;
for (int i = n - 1, k = n; i >= 0; i--) {
if (i < k) numAlive++;
k = Math.min(k, i - claws[i]);
}
System.out.println(numAlive);
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
// bw.write(numAlive);
// bw.close();
}
} | Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | eadf7a17553330dc221c785b66778337 | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Letters {
public static void main(String[] args) throws java.lang.Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] length = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i=0;i<n;i++)
length[i] = Integer.parseInt(st.nextToken());
int res = 0;
for (int i=n-1, j=n; i>= 0; i--) {
if (i < j)
res++;
j =Math.min(j, i-length[i]);
}
System.out.println(res);
}
} | Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | 98a0cca486ca119056af24839e6a5f5f | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Cf182 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 Cf182(),"Main",1<<27).start();
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// array sorting by colm
public static void sortbyColumn(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;
}
});
}
// gcd
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;
}
// fibonaci
static int fib(int n)
{
int a = 0, b = 1, c;
if (n == 0)
return a;
for (int i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return b;
}
// sort a string
public static String sortString(String inputString)
{
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// pair function
// list.add(new Pair<>(sc.nextInt(), i + 1));
// Collections.sort(list, (a, b) -> Integer.compare(b.first, a.first));
private static class Pair<F, S> {
private F first;
private S second;
public Pair() {}
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
int a[] = new int[n+1];
for(int i=1;i<=n;i++)
a[i] = sc.nextInt();
int ans = 0;
int min = Integer.MAX_VALUE;
for(int j = n;j>=1;j--)
{
if(j<min)
ans++;
min = Math.min(j-a[j],min);
}
System.out.println(ans);
}
} | Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | 361b507b7557646188534aec88317a00 | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] length = new int[n];
for (int i = 0; i < n; i++) {
length[i] = in.nextInt();
}
int alive = 0;
int kill = n;
for (int i = n - 1; i >= 0; i--) {
if (i < kill) {
alive++;
}
kill = Math.min(kill, i - length[i]);
}
System.out.println(alive);
}
} | Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | 239ab4a9ccc69b670707bfeddb4d4ab6 | train_003.jsonl | 1510929300 | Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if jβ<βi and jββ₯βiβ-βLi.You are given lengths of the claws. You need to find the total number of alive people after the bell rings. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.*;
import java.util.function.*;
import java.util.function.Predicate;
import java.math.BigInteger;
import java.rmi.MarshalException;
import java.time.Instant;
import java.time.Duration;
import java.util.concurrent.*;
public class a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// long startTime = System.nanoTime();
/////////////////////////////////////////////////////
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int kill = 0;
int cnt = 0;
for (int i = n - 1; i >= 0; --i) {
// System.out.println(kill + " " + arr[i]);
if (kill <= 0) {
++cnt;
}
kill = Math.max(kill, arr[i] + 1);
--kill;
}
System.out.println(cnt);
/////////////////////////////////////////////////////
// long endTime = System.nanoTime();
// System.out.printf("Executed in: %.2fms\n", ((double)endTime - startTime) / 1000000);
// sc.close();
}
static boolean isPrime(int n) {
if (n == 0 || n == 1) {
return false;
} else {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
}
class Pair {
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
// System.out.println("inside equals");
if (o == this) {
return true;
} else if (!(o instanceof Pair)) {
return false;
} else {
Pair p = (Pair)o;
return this.x == p.x && this.y == p.y;
}
}
@Override
public int hashCode() {
// System.out.println("inside hashcode");
return Arrays.hashCode(new int[]{this.x, this.y});
}
@Override
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
} | Java | ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"] | 2 seconds | ["1", "2", "3"] | NoteIn first sample the last person kills everyone in front of him. | Java 11 | standard input | [
"two pointers",
"implementation",
"greedy"
] | beaeeb8757232b141d510547d73ade04 | The first line contains one integer n (1ββ€βnββ€β106) β the number of guilty people. Second line contains n space-separated integers L1,βL2,β...,βLn (0ββ€βLiββ€β109), where Li is the length of the i-th person's claw. | 1,200 | Print one integer β the total number of alive people after the bell rings. | standard output | |
PASSED | 6a2eaeff4cbad0c8aa5634f6bdaa1298 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class A {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
char[][] b = new char[n][n];
for (int i = 0; i < n; i++) {
String line = scan.next();
for (int j = 0; j < n; j++) {
b[i][j] = line.charAt(j);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (count(b, i, j) % 2 != 0) {
System.out.println("NO");
return;
}
}
}
System.out.println("YES");
}
static int count(char[][] arr, int i, int j) {
return neighbourCount(arr, i > 0 && check(arr, i - 1, j)) +
neighbourCount(arr, i < arr.length - 1 && check(arr, i + 1, j)) +
neighbourCount(arr, j > 0 && check(arr, i, j - 1)) +
neighbourCount(arr, j < arr.length - 1 && check(arr, i, j + 1));
}
static int neighbourCount(char[][] arr, boolean condition) {
return condition ? 1 : 0;
}
static boolean check(char[][] arr, int i, int j) {
return arr[i][j] == 'o';
}
} | Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 8bba76755472d03b330c272a0d1f1f48 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.*;
public class Code462A {
private BufferedReader in;
private BufferedWriter out;;
private char[][] A;
private int gridSize;
private boolean isValid;
public static void main(String[] args) throws IOException {
new Code462A();
}
public Code462A() throws IOException {
readData();
solve();
writeData();
}
private void solve() {
int[] dx = {0, 1, 0, -1};
int[] dy = {-1, 0, 1, 0};
isValid = true;
int newX, newY, count;
for (int i=0;i<gridSize;++i) {
for (int j=0;j<gridSize;++j) {
count = 0;
for (int k=0;k<4;++k) {
newX = i + dx[k];
newY = j + dy[k];
if (newX >= 0 && newX < gridSize && newY >=0 && newY < gridSize && A[newX][newY] == 'o') {
count++;
}
}
if (count > 0 && count % 2 == 1) {
isValid = false;
break;
}
}
}
}
private void writeData() throws IOException {
out = new BufferedWriter(new OutputStreamWriter(System.out));
if (isValid) {
out.write("YES");
}
else {
out.write("NO");
}
out.flush();
out.close();
}
private void readData() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
gridSize = Integer.parseInt(in.readLine());
A = new char[gridSize][gridSize];
String line;
for (int i=0;i<gridSize;++i) {
line = in.readLine();
for (int j=0;j<gridSize;++j) {
A[i][j] = line.charAt(j);
}
}
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | d2cae5d24e4823c6049b92ec4c87fbb4 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class Appleman_A {
public static int n;
public static char[][] arr;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = Integer.parseInt(scan.nextLine());
arr = new char[n][n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextLine().toCharArray();
}
System.out.println(easyTask());
}
public static String easyTask() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (evenAdjacent(i,j) % 2 != 0) {
return "NO";
}
}
}
return "YES";
}
public static int evenAdjacent(int i, int j) {
int num = 0;
try {
if (arr[i-1][j] == 'o')
num++;
} catch (Exception e) {
}
try {
if (arr[i+1][j] == 'o')
num++;
} catch (Exception e) {
}
try {
if (arr[i][j-1] == 'o')
num++;
} catch (Exception e) {
}
try {
if (arr[i][j+1] == 'o')
num++;
} catch (Exception e) {
}
return num;
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | f95ad8b2c2f8cf296f525b9c98473cd0 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.*;
public class EasyTask1
{
public static void main(String[]args)throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
char a[][]=new char[n+2][n+2];
int i,j;
for(i=1;i<=n;i++)
{
String s=br.readLine();
for(j=1;j<=n;j++)
{
a[i][j]=s.charAt(j-1);
}
}
int f=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
int c=0;
if(a[i-1][j]=='o')
c++;
if(a[i][j-1]=='o')
c++;
if(a[i+1][j]=='o')
c++;
if(a[i][j+1]=='o')
c++;
if(c%2!=0)
{
f=1;
System.out.println("NO");
break;
}
}
if(f==1)
break;
}
if(f==0)
System.out.println("YES");
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 0b272634af3fc57c3dee7de6533f8d32 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class XOGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int [][]input = new int[n][n];
int count=0,previousFlag =0;
for(int i=0;i<n;i++)
{
String random = in.next();
for(int j=0;j<n;j++)
{
input[i][j] = random.charAt(j);
}
}
int noFlag =0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
//System.out.println("in loop");
count=0;
if(n>1)
{
if(i==0&&j==0)
{
if(input[0][1]=='o')
count++;
if(input[1][0]=='o')
count++;
}
else if(i==0&&j==(n-1))
{
if(input[0][n-2]=='o')
count++;
if(input[n-1][1]=='o')
count++;
}
else if(i==(n-1)&&j==0)
{
if(input[n-2][0]=='o')
count++;
if(input[1][n-1]=='o')
count++;
}
else if(i==(n-1)&&j==(n-1))
{
if(input[n-2][n-1]=='o')
count++;
if(input[n-1][n-2]=='o')
count++;
}
else if(i==0)
{
if(input[0][j-1]=='o')
count++;
if(input[0][j+1]=='o')
count++;
if(input[1][j]=='o')
count++;
}
else if(i==(n-1))
{
if(input[n-1][j-1]=='o')
count++;
if(input[n-1][j+1]=='o')
count++;
if(input[n-2][j]=='o')
count++;
}
else if(j==0)
{
if(input[i-1][0]=='o')
count++;
if(input[i+1][0]=='o')
count++;
if(input[i][1]=='o')
count++;
}
else if(j==(n-1))
{
if(input[i-1][j]=='o')
count++;
if(input[i+1][j]=='o')
count++;
if(input[i][n-2]=='o')
count++;
}
else
{
if(input[i-1][j]=='o')
count++;
if(input[i+1][j]=='o')
count++;
if(input[i][j-1]=='o')
count++;
if(input[i][j+1]=='o')
count++;
}
if(count%2!=0)
{
noFlag =1;
break;
}
}
}
if(noFlag==1)
break;
}
if(noFlag==0)
System.out.println("YES");
else
System.out.println("NO");
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 9763970fdf278fb72978320931d29eb9 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Problem_A
{
private static MyScanner scanner = new MyScanner();
//private static Scanner scanner = new Scanner(System.in);
private static char[][] board;
private static boolean bool = true;
public static void main(String[] args) throws IOException {
int n = scanner.nextInt();
board = new char[n][n];
for (int i = 0; i < n; i++) {
String string = scanner.next();
char[] array = new char[n];
string.getChars(0, n, array, 0);
for (int j = 0; j < n; j++) {
board[i][j] = array[j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int count = 0;
if (i < n - 1 && board[i+1][j] == 'o') count++;
if (i >= 1 && board[i-1][j] == 'o') count++;
if (j < n - 1 && board[i][j+1] == 'o') count++;
if (j >= 1 && board[i][j-1] == 'o') count++;
if (count % 2 != 0) {
bool = false;
break;
}
}
if (!bool) {
break;
}
}
if (bool) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
// -----------MyScanner class for faster input----------
public static class MyScanner
{
BufferedReader br;
StringTokenizer st;
public MyScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 7594ea715ffda843249cc094eff20b3b | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class Task1 {
private static final Scanner sc = new Scanner(System.in);
private static int n;
public static void main(String[] args) {
n = nextInt();
char[][] matrix;
matrix = nextCharMatrix(n, n);
try {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (countNeighbors(matrix, i, j, 'o') % 2 != 0) {
System.out.println("NO");
return;
}
}
}
System.out.println("YES");
} finally {
cleanUp();
}
}
private static int countNeighbors(char[][] matrix, int row, int col,
char sign) {
int count = 0;
if (row - 1 >= 0 && matrix[row - 1][col] == sign) {
count++;
}
if (row + 1 < n && matrix[row + 1][col] == sign) {
count++;
}
if (col - 1 >= 0 && matrix[row][col - 1] == sign) {
count++;
}
if (col + 1 < n && matrix[row][col + 1] == sign) {
count++;
}
return count;
}
private static void cleanUp() {
sc.close();
}
private static int nextInt() {
return sc.nextInt();
}
private static char[][] nextCharMatrix(int rows, int cols) {
char[][] matrix = new char[rows][cols];
for (int i = 0; i < rows; i++) {
matrix[i] = sc.next().toCharArray();
}
return matrix;
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 20bf5196288f4b7601b62d6149b5725e | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
public class Solution {
private static final Scanner sc = new Scanner(System.in);
private static int n;
public static void main(String[] args) {
n = nextInt();
char[][] matrix;
try {
matrix = nextCharMatrix(n, n);
String answer = getAnswer(matrix);
System.out.println(answer);
} catch (IOException e) {
}
cleanUp();
}
private static String getAnswer(char[][] matrix) {
String answer = "YES";
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
int count = countNeighbors(matrix, row, col);
if (count % 2 != 0) {
answer = "NO";
return answer;
}
}
}
return answer;
}
private static int countNeighbors(char[][] matrix, int row, int col) {
int count = 0;
if (row - 1 >= 0 && matrix[row - 1][col] != 'x') {
count++;
}
if (row + 1 < n && matrix[row + 1][col] != 'x') {
count++;
}
if (col - 1 >= 0 && matrix[row][col - 1] != 'x') {
count++;
}
if (col + 1 < n && matrix[row][col + 1] != 'x') {
count++;
}
return count;
}
private static void cleanUp() {
sc.close();
}
private static int nextInt() {
return sc.nextInt();
}
private static float nextFloat() {
return sc.nextFloat();
}
private static int[] nextIntArray(int count) {
int[] array = new int[count];
for (int i = 0; i < count; ++i) {
array[i] = nextInt();
}
return array;
}
private static float[] nextFloatArray(int count) {
float[] array = new float[count];
for (int i = 0; i < count; ++i) {
array[i] = nextFloat();
}
return array;
}
private static int[][] nextIntMatrix(int rows, int cols) {
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
matrix[row][col] = nextInt();
}
}
return matrix;
}
private static char[][] nextCharMatrix(int rows, int cols)
throws IOException {
char[][] matrix = new char[rows][cols];
for (int i = 0; i < rows; i++) {
matrix[i] = sc.next().toCharArray();
}
return matrix;
}
private static float[][] nextFloatMatrix(int rows, int cols) {
float[][] matrix = new float[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
matrix[row][col] = nextFloat();
}
}
return matrix;
}
private static void printIntArray() {
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 7d382fd2fd2cad61ff67433ac3bff93f | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class Problem1_26AUG2014 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
int n = sc.nextInt();
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < n; j++) {
board[i][j] = s.charAt(j);
}
}
boolean bool = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int o = 0;
if (i > 0 && board[i - 1][j] == 'o') {
o++;
}
if (j < (n - 1) && board[i][j + 1] == 'o') {
o++;
}
if (i < (n - 1) && board[i + 1][j] == 'o') {
o++;
}
if (j > 0 && board[i][j - 1] == 'o') {
o++;
}
if (o % 2 != 0) {
bool = bool && false;
break;
}
}
}
if (bool) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 5f1aef1b404197fecae5aae3e9e84a2f | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class Task {
private static int[] a = {-1, 1};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
char[][] m = new char[n][];
for (int i = 0; i < n; i++) {
m[i] = in.nextLine().toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int t = 0;
for (int k : a) {
if (i + k >= 0 && i + k < n && m[i + k][j] == 'o') t++;
if (j + k >= 0 && j + k < n && m[i][j + k] == 'o') t++;
}
if (t % 2 == 1) {
System.out.println("NO");
return;
}
}
}
System.out.println("YES");
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 89d5b62f2b2420ecd797149f97e344d3 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | //package general_problems;
import java.util.Scanner;
public class ApplemanandEasyTask {
static char array [][];
static int n;
static boolean disaster = false;
public static void solve(int col, int row){
if (disaster==true){return;}
if (col>=n){row++;col=0;}
if (row>=n){return;}
if (disaster==false){
int count=0;
if (col!=n-1 && array[row][col+1]=='o')count++;
if (row!=n-1 && array[row+1][col]=='o')count++;
if (col!=0 && array[row][col-1]=='o')count++;
if (row!=0 && array[row-1][col]=='o')count++;
if (count%2==1){disaster=true;}
}
solve(col+1,row);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner (System.in);
n = scan.nextInt();
array = new char[n] [n];
String temp;
for(int i=0 ; i<n ; i++){
temp = scan.next();
for(int j=0 ; j<n ; j++){
array[i][j] = temp.charAt(j);
}
}
solve(0,0);
if (disaster==true)System.out.println("NO");
else System.out.println("YES");
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 2f5c5c86c5911c171feee52ed0a23cb9 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 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.io.*;
/**
*
* @author DELL
*/
public class Problem_B {
public static void main(String[] args) throws IOException {
BufferedReader x = new BufferedReader(new InputStreamReader(System.in));
//1st line contating only 1 integer
int n = Integer.parseInt(x.readLine());
// 1st containing only 2 integer
//// nxt m line containg 2 or more ints
char[][] a = new char[n][n];
for (int i = 0; i < n; i++) {
String s = x.readLine();
for (int j = 0; j < n; j++) {
a[i][j] = s.charAt(j);
}
}
boolean q=true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int add=0;
if(j!=n-1 && a[i][j+1]=='o') add++;
if(j!=0 && a[i][j-1]=='o') add++;
if(i!=n-1 && a[i+1][j]=='o') add++;
if(i!=0 && a[i-1][j]=='o') add++;
if(add%2!=0) q=false;
}
}
if(q) System.out.println("YES");
else System.out.println("NO");
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 0382d4ff5067741da3e87821ca2dbf93 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes |
import java.util.*;
import java.io.*;
import org.omg.CORBA.FREE_MEM;
public class Main implements Runnable {
class Message implements Comparable<Message> {
int time;
String from;
String to;
boolean completed;
Message(String f, String t, int time) {
this.time = time;
from = f;
to = t;
completed = false;
}
public String reverse() {
return to + " " + from;
}
public String current() {
return from + " " + to;
}
public int time() {
return time;
}
public int compareTo(Message other) {
return time - other.time;
}
}
String[] a;
int N;
public void solve() throws IOException {
N = nextInt();
boolean good = true;
a = new String[N];
for (int i = 0; i < N; i++) {
a[i] = nextToken();
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
good = good & check(i, j);
}
}
System.out.println(good ? "YES" : "NO");
}
boolean valid(int i, int j) {
return i >= 0 && j >= 0 && i < N && j < N;
}
boolean check(int i, int j) {
int cnt = 0;
if (valid(i - 1, j) && a[i - 1].charAt(j) == 'o') {
cnt++;
}
if (valid(i, j - 1) && a[i].charAt(j - 1) == 'o') {
cnt++;
}
if (valid(i + 1, j) && a[i + 1].charAt(j) == 'o') {
cnt++;
}
if (valid(i, j + 1) && a[i].charAt(j + 1) == 'o') {
cnt++;
}
return cnt % 2 == 0;
}
void print(Object... obj) {
for (Object o : obj) {
System.out.println(o);
}
}
void print(int[] a) {
System.out.println();
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
void print(int[][] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
void print(boolean[][] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 3b1d3fb5cee6eee712b14c2e8790f5c8 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner x=new Scanner (System.in);
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=x.nextInt();
char arr[][]=new char [n][n] ;
for(int i=0;i<n;i++){
String str=x.next();
arr[i]=str.toCharArray();
}
boolean f=false;
int c=0;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
c=0;
if(i+1<n&&arr[i+1][j]=='o')c++;
if(j+1<n&&arr[i][j+1]=='o')c++;
if(i-1>=0&&arr[i-1][j]=='o')c++;
if(j-1>=0&&arr[i][j-1]=='o')c++;
if(c%2==1){f=true;}
}
}
if(f==true){System.out.println("NO");}
else{
System.out.println("YES");
}
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 9a7e04454a775ea3242524b6f88f4776 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.Scanner;
public class practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char [][] b = new char[n][n];
boolean yes = true;
int numo = 0;
for(int i = 0; i<n; i++) {
String a = sc.next();
int j = 0;
for(char z : a.toCharArray()) {
b[i][j++] = z;
if(z == 'o') numo++;
}
}
for(int i = 0; i<n; i++) {
for(int j = 0; j<n; j++) {
int count =0;
if(check(i+1,j,n) && b[i+1][j] == 'o')
count++;
if(check(i-1, j,n) && b[i-1][j] == 'o')
count++;
if(check(i, j+1, n) && b[i][j+1] == 'o')
count++;
if(check(i, j-1, n) && b[i][j-1] == 'o')
count++;
if(count %2 != 0) {
yes = false;
}
}
}
if(yes)
System.out.println("YES");
else
System.out.println("NO");
}
public static boolean check(int i, int j, int n) {
if(i>=0 && i<n && j>=0 && j<n)
return true;
return false;
}
// public static Set<Set<Character>> combinations(char[] input) {
// Set<Set<Character>> combinations = new HashSet<Set<Character>>();
// combinations.add(new HashSet<Character>());
// while (true) {
// Set<Set<Character>> newElements = new HashSet<Set<Character>>();
// for (Set<Character> aCombination : combinations) {
// for (char c : input) {
// Set<Character> aNewCombination = new HashSet<Character>();
// aNewCombination.addAll(aCombination);
// if (aNewCombination.add(c)) {
// newElements.add(aNewCombination);
// System.out.println(aCombination + " -> "
// + aNewCombination);
// }
// }
// }
//
// if (combinations.addAll(newElements) == false)
// break;
//
// }
// return combinations;
// }
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 281ac4da50a9bbf2a4f2187716509447 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class AppleMan {
private void solve() throws IOException {
int n = nextInt();
char arr[][] = new char[n][n];
for (int i = 0; i < n; i++) {
String l = nextToken();
for (int j = 0; j < n; j++) {
arr[i][j] = l.charAt(j);
}
}
boolean good = true;
int o = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (i - 1 >= 0) {
if (arr[i - 1][j] == 'o')
o++;
}
if (i + 1 < arr.length) {
if (arr[i + 1][j] == 'o')
o++;
}
if (j - 1 >= 0) {
if (arr[i][j - 1] == 'o')
o++;
}
if (j + 1 < arr.length) {
if (arr[i][j + 1] == 'o')
o++;
}
if (o % 2 != 0) {
good = false;
break;
}
o = 0;
}
}
writer.println((good) ? "YES" : "NO");
}
public static void main(String[] args) {
new AppleMan().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | e8503679623b914b17738e73bea415ba | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.*;
public class Code462A {
private int size;
private int a[][];
public static void main(String args[]){
new Code462A();
}
public Code462A(){
readInput();
solve();
}
private void solve() {
boolean breaking = false;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < 3; k++) {
int parity = 0;
if(i > 0 && a[i-1][j] == 0)
parity++;
if(j > 0 && a[i][j-1] == 0)
parity++;
if(i < size-1 && a[i+1][j] == 0)
parity++;
if(j < size-1 && a[i][j+1] == 0)
parity++;
if(parity%2 != 0)
{
breaking = true;
break;
}
}
if(breaking)
break;
}
if( breaking)
break;
}
try {
if(breaking)
printResult("NO");
else
printResult("YES");
} catch (IOException e) {
e.printStackTrace();
}
}
public void printResult(String solution) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
out.write(String.valueOf(solution) + "\n");
out.flush();
out.close();
}
private void readInput() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine();
size = Integer.parseInt(line);
a = new int[size][size];
for (int i=0;i<size;++i) {
line = in.readLine();
for (int j = 0; j < size; j++) {
if(line.charAt(j) == 'x')
{
a[i][j] = 1;
}
}
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | f7e05d2aaceacee84693c2e5ccc35b74 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A_ApplemanAndEasyTask {
public static char[][] getMatrix(BufferedReader br){
try{
int n = Integer.parseInt(br.readLine());
char [][] matrix = new char[n][n];
for (int i = 0; i < n; i++) {
String s = br.readLine();
for (int j = 0; j < n; j++) {
matrix[i][j] = s.charAt(j);
}
}
// for (int i = 0; i < matrix.length; i++) {
// for (int j = 0; j < matrix.length; j++) {
// System.out.print(matrix[i][j]);
// }
// System.out.println();
// }
return matrix;
}catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new char[1][1];
}
public static String checkCheckerBoard(char[][] matrix){
int count = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
/*Left & right bounds cases*/
if(i>0)
if(matrix[i-1][j]=='o')count++;
if(i<matrix.length-1)
if(matrix[i+1][j]=='o')count++;
/*bottm & down bounds cases*/
if(j>0)
if(matrix[i][j-1]=='o')count++;
if(j<matrix.length-1)
if(matrix[i][j+1]=='o')count++;
if(count%2!=0){
// System.out.println(i+" "+j);
return "NO";
}else
count = 0;
}
}
return "YES";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br;
br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(A_ApplemanAndEasyTask.checkCheckerBoard(A_ApplemanAndEasyTask.getMatrix(br)));
// try {
// br = new BufferedReader(new FileReader("TestFile.in"));
// System.out.println(A_ApplemanAndEasyTask.checkCheckerBoard(A_ApplemanAndEasyTask.getMatrix(br)));
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | d390b1f84bc7bcb2d340eea95c0bd844 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.*;
import java.util.*;
public class SolutionA {
public void solve(){
int n = nextInt();
int ar[][] = new int[n][n];
for (int i = 0; i < n; i++) {
String s = nextLine();
for (int j = 0; j < n; j++) {
if(s.charAt(j) == 'x')
ar[i][j] = 0;
else
ar[i][j] = 1;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int c = 0;
if(j+1< n && ar[i][j+1] == 1)
c++;
if(j-1>= 0 && ar[i][j-1] == 1)
c++;
if(i+1< n && ar[i+1][j] == 1)
c++;
if(i-1>= 0 && ar[i-1][j] == 1)
c++;
if(c%2==1){
out.println("NO");
out.flush();
return;
}
}
}
out.println("YES");
out.flush();
}
public static void main(String args[]){
new SolutionA().solve();
}
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
String line;
StringTokenizer st;
public String nextLine(){
try {
line = bf.readLine();
st = new StringTokenizer(line);
} catch (IOException e) {
return null;
}
return line;
}
public String nextString(){
while (st == null || !st.hasMoreElements()) {
try {
line = bf.readLine();
st = new StringTokenizer(line);
} catch (IOException e) {
return null;
}
}
return st.nextToken();
}
public int nextInt(){
return Integer.parseInt(nextString());
}
public long nextLong(){
return Long.parseLong(nextString());
}
public double nextDouble(){
return Double.parseDouble(nextString());
}
} | Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | e419de6a09f415f11ad4ba36de9b53a7 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static char [][]map;
static int n;
public static boolean solve(){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int count = 0;
if(j!=n-1&&map[i][j+1]=='o')count++;
if(i!=n-1&&map[i+1][j]=='o')count++;
if(j!=0&&map[i][j-1]=='o')count++;
if(i!=0&&map[i-1][j]=='o')count++;
if(count%2==1) return false;
}
}
return true;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
n = in.nextInt();
map = new char[n][n];
for (int i = 0; i < n; i++) {
String s = in.next();
for (int j = 0; j < n; j++) {
map[i][j] = s.charAt(j);
}
}
if(solve()) System.out.println("YES");
else System.out.println("NO");
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
} | Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 9c4db2c3b12c50db4e4aca79e4876a34 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 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 invisible
*/
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);
AppleMan solver = new AppleMan();
solver.solve(1, in, out);
out.close();
}
static class AppleMan {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
char ch[][] = new char[n][n];
for (int i = 0; i < n; i++) {
ch[i] = in.readLine().toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!check(i, j, ch)) {
//System.out.println(i+" "+j);
out.printLine("NO");
return;
}
}
}
out.printLine("YES");
}
public boolean check(int i, int j, char ch[][]) {
int count = 0;
//left
int n = ch.length;
//System.out.println(n);
if (j - 1 >= 0) {
count += ch[i][j - 1] == 'o' ? 1 : 0;
}
if (j + 1 < n)//right
{
count += ch[i][j + 1] == 'o' ? 1 : 0;
}
if (i - 1 >= 0)//up
{
count += ch[i - 1][j] == 'o' ? 1 : 0;
}
if (i + 1 < n)//down
{
//System.out.println("here"+" "+i+" "+j);
count += ch[i + 1][j] == 'o' ? 1 : 0;
}
//System.out.println(count+" "+i+" "+j);
return count % 2 == 0;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 270405051d37417d03c2c21b0f799580 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Integer.parseInt;
public final class SumDif {
public static void main(String[] args) throws IOException{
new SumDif().run();
}
BufferedReader in;
PrintWriter out;
/* int nextInt() throws IOException {
in.nextToken();
return (int)in.nval;
}*/
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
}
void solve() throws IOException {
String nn = in.readLine();
int n = parseInt(nn);
if(n == 1) {
out.print("YES");
return;
}
char[][] arr = new char[n][n];
for(int i = 0; i < n; i++) {
String s = in.readLine();
for(int j = 0; j < n; j++) {
char c = s.charAt(j);
arr[j][i] = c;
}
}
int res = 0;
int r = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
char c = arr[i][j];
char a,b,d,e;
if(i == 0){
if(j == 0){
a = arr[i][j+1];
b = arr[i+1][j];
if(a=='o')r++;
if(b=='o')r++;
if(r%2 == 0)res++;
}
else if(j == n-1){
a = arr[i][j-1];
b = arr[i+1][j];
if(a=='o')r++;
if(b=='o')r++;
if(r%2 == 0)res++;
}
else {
a = arr[i][j-1];
b = arr[i+1][j];
d = arr[i][j+1];
if(a=='o')r++;
if(b=='o')r++;
if(d=='o')r++;
if(r%2 == 0)res++;}
}
else if(i == n-1) {
if(j == 0){
a = arr[i][j+1];
b = arr[i-1][j];
if(a=='o')r++;
if(b=='o')r++;
if(r%2 == 0)res++;
}
else if(j == n-1){
a = arr[i][j-1];
b = arr[i-1][j];
if(a=='o')r++;
if(b=='o')r++;
if(r%2 == 0)res++;
}else{
a = arr[i][j-1];
b = arr[i-1][j];
d = arr[i][j+1];
if(a=='o')r++;
if(b=='o')r++;
if(d=='o')r++;
if(r%2 == 0)res++;
}
} else {
if(j == 0){
b = arr[i-1][j];
d = arr[i][j+1];
e = arr[i+1][j];
if(b=='o')r++;
if(d=='o')r++;
if(e=='o')r++;
if(r%2 == 0)res++;}
else if(j == n-1) {
a = arr[i][j-1];
b = arr[i-1][j];
e = arr[i+1][j];
if(a=='o')r++;
if(b=='o')r++;
if(e=='o')r++;
if(r%2 == 0)res++;}
else{
a = arr[i][j-1];
b = arr[i-1][j];
d = arr[i][j+1];
e = arr[i+1][j];
if(a=='o')r++;
if(b=='o')r++;
if(d=='o')r++;
if(e=='o')r++;
if(r%2 == 0)res++;
}
}
r = 0;
}
}
if(res == n*n)out.print("YES");
else out.print("NO");
}
}
| Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 89a6f5b88ad2de30550d8586e0fb7511 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();;
String s[]=new String[n];
for(int i=0;i<n;i++){
s[i]=in.next();
}
for(int i=0;i<n/2;i++)
{
for(int j=0;j<n;j++)
{
if(s[i].charAt(j)!=s[n-i-1].charAt(n-j-1))
{
System.out.println("NO");
System.exit(0);
}
}
}
System.out.println("YES");
}
} | Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | fbcd1106d44f98ab563e130fbdf793c5 | train_003.jsonl | 1409061600 | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a nβΓβn checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main
{
private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0};
public boolean isLegal(int x, int y, int n)
{
return x >= 0 && x < n && y >= 0 && y < n;
}
public boolean judge(char[][] map, int n)
{
for(int i = 0;i < n;++i)
{
for(int j = 0;j < n;++j)
{
int cnt = 0;
for(int k = 0;k < 4;++k)
{
int iNext = i + DY[k];
int jNext = j + DX[k];
if(isLegal(iNext, jNext, n) && 'o' == map[iNext][jNext])
{
++cnt;
}
}
if(1 == cnt % 2)
{
return false;
}
}
}
return true;
}
public void foo()
{
MyScanner scan = new MyScanner();
int n = scan.nextInt();
char[][] map = new char[n][n];
for(int i = 0;i < n;++i)
{
map[i] = scan.next().toCharArray();
}
System.out.println(judge(map, n) ? "YES" : "NO");
}
public static void main(String[] args)
{
new Main().foo();
}
class MyScanner
{
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
BufferedInputStream bis = new BufferedInputStream(System.in);
public int read()
{
if (-1 == numChars)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = bis.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 & 15;
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 & 15) * m;
c = read();
}
}
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
}
}
} | Java | ["3\nxxo\nxox\noxx", "4\nxxxo\nxoxo\noxox\nxxxx"] | 1 second | ["YES", "NO"] | null | Java 7 | standard input | [
"implementation",
"brute force"
] | 03fcf7402397b94edd1d1837e429185d | The first line contains an integer n (1ββ€βnββ€β100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces. | 1,000 | Print "YES" or "NO" (without the quotes) depending on the answer to the problem. | standard output | |
PASSED | 0401e2bb81be91600fa2126962360508 | train_003.jsonl | 1290096000 | Baldman is a warp master. He possesses a unique ability β creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head.Because of such extraordinary abilities, Baldman has caught the military's attention. He has been charged with a special task. But first things first.The military base consists of several underground objects, some of which are connected with bidirectional tunnels. There necessarily exists a path through the tunnel system between each pair of objects. Additionally, exactly two objects are connected with surface. For the purposes of security, a patrol inspects the tunnel system every day: he enters one of the objects which are connected with surface, walks the base passing each tunnel at least once and leaves through one of the objects connected with surface. He can enter and leave either through the same object, or through different objects. The military management noticed that the patrol visits some of the tunnels multiple times and decided to optimize the process. Now they are faced with a problem: a system of wormholes needs to be made to allow of a patrolling which passes each tunnel exactly once. At the same time a patrol is allowed to pass each wormhole any number of times.This is where Baldman comes to operation: he is the one to plan and build the system of the wormholes. Unfortunately for him, because of strict confidentiality the military can't tell him the arrangement of tunnels. Instead, they insist that his system of portals solves the problem for any arrangement of tunnels which satisfies the given condition. Nevertheless, Baldman has some information: he knows which pairs of objects he can potentially connect and how much it would cost him (in hair). Moreover, tomorrow he will be told which objects (exactly two) are connected with surface. Of course, our hero decided not to waste any time and calculate the minimal cost of getting the job done for some pairs of objects (which he finds likely to be the ones connected with surface). Help Baldman! | 256 megabytes | import java.util.*;
import java.io.*;
public class b {
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt(), m = input.nextInt();
Edge[] es = new Edge[m];
for(int i = 0; i<m; i++)
{
int a = input.nextInt()-1, b = input.nextInt()-1, c = input.nextInt();
es[i] = new Edge(a, b, c);
}
Arrays.sort(es);
long cost = 0;
int count = 0;
DisjointSet ds = new DisjointSet(n);
ArrayList<Edge>[] g = new ArrayList[n];
for(int i = 0; i<n; i++) g[i] = new ArrayList<Edge>();
for(Edge e : es)
{
if(ds.find(e.a) == ds.find(e.b)) continue;
count++;
cost += e.c;
ds.union(e.a, e.b);
Edge fromA = new Edge(e.a, e.b, e.c);
fromA.to = e.b;
Edge fromB = new Edge(e.a, e.b, e.c);
fromB.to = e.a;
g[e.a].add(fromA);
g[e.b].add(fromB);
}
LCT lct = new LCT(n, Node.MAX);
b.g = new ArrayList[n];
b.n = n;
for(int i = 0; i<n; i++)b.g[i] = new ArrayList<Integer>();
Queue<Integer> q = new LinkedList<Integer>();
boolean[] seen = new boolean[n];
for(int i= 0; i<n; i++)
{
if(seen[i]) continue;
q.add(i);
seen[i] = true;
while(!q.isEmpty())
{
int at = q.poll();
for(Edge e : g[at])
{
int to = e.to;
if(seen[to]) continue;
seen[to] = true;
lct.link(to, at);
q.add(to);
lct.add(to, to, e.c);
b.g[at].add(to);
}
}
}
tree();
binaryLift();
int Q = input.nextInt();
for(int qq= 0; qq<Q; qq++)
{
int a = input.nextInt()-1, b = input.nextInt()-1;
if(count < n-2)out.println(-1);
else if(count == n-2)
{
if(lct.connected(a, b)) out.println(-1);
else out.println(cost);
}
else
{
int lca = lca(a, b);
long ans = 0;
if(a != lca)
{
int diff = depths[a] - depths[lca];
ans = Math.max(ans, lct.sum(a, getParent(a, diff - 1)));
}
if(b != lca)
{
int diff = depths[b] - depths[lca];
ans = Math.max(ans, lct.sum(b, getParent(b, diff - 1)));
}
out.println(cost - ans);
}
}
out.close();
}
static class Node
{
static int SUM = 0, MIN = 1, MAX = 2;
Node left, right, parent;
int size;
int id;
boolean revert;
int type;
long delta, nodeValue, subtreeValue;
Node(int i, int t)
{
id = i;
type = t;
}
boolean isRoot()
{
if(parent == null) return true;
if(parent.left == this || parent.right == this) return false;
return true;
}
void push()
{
if (revert)
{
revert = false;
Node t = left;
left = right;
right = t;
if (left != null) left.revert = !left.revert;
if (right != null) right.revert = !right.revert;
}
if (left != null) left.delta += delta;
if (right != null) right.delta += delta;
nodeValue += delta;
if(type == SUM) subtreeValue += delta * size;
else subtreeValue += delta;
delta = 0;
}
void update()
{
size = 1;
subtreeValue = nodeValue;
if (left != null)
{
if(type == SUM) subtreeValue += left.subtreeValue + left.delta * left.size;
else if(type == MIN) subtreeValue = Math.min(subtreeValue, left.subtreeValue + left.delta);
else if(type == MAX) subtreeValue = Math.max(subtreeValue, left.subtreeValue + left.delta);
size += left.size;
}
if (right != null)
{
if(type == SUM) subtreeValue += right.subtreeValue + right.delta * right.size;
else if(type == MIN) subtreeValue = Math.min(subtreeValue, right.subtreeValue + right.delta);
else if(type == MAX) subtreeValue = Math.max(subtreeValue, right.subtreeValue + right.delta);
size += right.size;
}
}
}
static int[] depths;
static int[] ps;
static int[][] bl;
static int n;
static ArrayList<Integer>[] g;
static void tree()
{
ps = new int[n];
depths = new int[n];
boolean[] vis = new boolean[n];
vis[0] = true;
ps[0] = -1;
Queue<Integer> q = new LinkedList<Integer>();
q.add(0);
ArrayList<Integer>[] tree = new ArrayList[n];
for(int i = 0; i<n; i++) tree[i] = new ArrayList<Integer>();
while(!q.isEmpty())
{
int at = q.poll();
for(int e : g[at])
{
if(!vis[e])
{
tree[at].add(e);
vis[e] = true;
q.add(e);
ps[e] = at;
depths[e] = 1 + depths[at];
}
}
}
g = tree;
}
static int lca(int a, int b)
{
if(depths[a] < depths[b])
{
int temp = a; a = b; b = temp;
}
int log = 0;
for(log = 1; (1<<log) <= depths[a]; log++);
log--;
for(int i = log; i >= 0; i--)
if(depths[a] - (1<<i) >= depths[b])
a = bl[i][a];
if(a == b) return a;
for(int i = log; i>=0; i--)
if(bl[i][a] != -1 && bl[i][a] != bl[i][b])
{
a = bl[i][a];
b = bl[i][b];
}
return ps[a];
}
static int dist(int a, int b)
{
int lca = lca(a, b);
return depths[a] + depths[b] - 2 * depths[lca];
}
/*
* Returns the ancestor of at that is distance p away.
*/
static int getParent(int at, int p)
{
//System.out.println(at+" "+p);
if(p == 0) return at;
int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(p));
return getParent(bl[log][at], p - (1<<log));
}
static void binaryLift()
{
bl = new int[Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 1][n];
for(int i = 0; i<n; i++) bl[0][i] = ps[i];
for(int i = 1; i < bl.length; i++)
{
Arrays.fill(bl[i], -1);
for(int j = 0; j<n; j++)
if(bl[i-1][j] >= 0)
bl[i][j] = bl[i-1][bl[i-1][j]];
}
}
static class LCT
{
Node[] nodes;
LCT(int n, int type)
{
nodes = new Node[n];
for(int i = 0; i<n; i++) nodes[i] = new Node(i, type);
}
void connect(Node ch, Node p, int type)
{
if (ch != null) ch.parent = p;
if(type == 0) p.left = ch;
else if(type == 1) p.right = ch;
}
void rotate(Node x)
{
Node p = x.parent, g = p.parent;
boolean isRootP = p.isRoot();
boolean leftChildX = (x == p.left);
// create 3 edges: (x.r(l),p), (p,x), (x,g)
connect(leftChildX ? x.right : x.left, p, leftChildX ? 0 : 1);
connect(p, x, leftChildX ? 1 : 0);
connect(x, g, isRootP ? 2 : (p == g.left ? 0 : 1));
p.update();
}
void splay(Node x)
{
while (!x.isRoot())
{
Node p = x.parent, g = p.parent;
if (!p.isRoot()) g.push();
p.push();
x.push();
if (!p.isRoot()) rotate((x == p.left) == (p == g.left) ? p/*zig-zig*/ : x/*zig-zag*/);
rotate(x);
}
x.push();
x.update();
}
/*
* Makes q the root of its tree of splay trees.
*/
Node access(Node q)
{
Node r = null;
for(Node p = q; p != null; p = p.parent)
{
splay(p);
p.left = r;
p.update();
r = p;
}
splay(q);
return r;
}
void makeRoot(Node x)
{
access(x);
x.revert = !x.revert;
}
/*
* Makes qq the parent of pp.
*/
void link(int pp, int qq)
{
Node p = nodes[pp], q = nodes[qq];
//if (connected(p, q)) throw new RuntimeException("error: x and y are already connected");
makeRoot(p);
p.parent = q;
}
int findRoot(Node p)
{
access(p);
while(p.right != null) p = p.right;
splay(p);
return p.id;
}
void cut(int pp, int qq)
{
Node p = nodes[pp], q = nodes[qq];
makeRoot(p);
access(q);
//if (q.right != p || p.left != null || p.right != null) throw new RuntimeException("error: no edge (x,y)");
q.right.parent = null;
q.right = null;
}
long sum(int from, int to)
{
makeRoot(nodes[from]);
access(nodes[to]);
return nodes[to].subtreeValue;
}
void add(int from, int to, int delta)
{
makeRoot(nodes[from]);
access(nodes[to]);
nodes[to].delta += delta;
}
boolean connected(int pp, int qq)
{
Node p = nodes[pp], q = nodes[qq];
if(p == q) return true;
access(p);
access(q);
return p.parent != null;
}
int lca(int p, int q) {
//if (findRoot(x) != findRoot(y)) throw new RuntimeException("error: x and y are not connected");
access(nodes[p]);
return access(nodes[q]).id;
}
}
public static class DisjointSet
{
int[] map; //negative if root, more negative means bigger set; if nonnegative, then it indicates the parent
public DisjointSet(int n)
{
map = new int[n+1];
Arrays.fill(map, -1);
}
public int find(int x)
{
if(map[x] < 0)
return x;
else
{
map[x] = find(map[x]);
return map[x];
}
}
public void union(int a, int b)
{
int roota = find(a), rootb = find(b);
if(roota == rootb)
return;
if(map[roota] < map[rootb])
{
map[roota] += map[rootb]; //add the sizes
map[rootb] = roota; //connect the smaller to the bigger
}
else
{
map[rootb] += map[roota];
map[roota] = rootb;
}
}
}
static class Edge implements Comparable<Edge>
{
int a, b, c, to;
public Edge(int aa, int bb, int cc)
{
a = aa; b = bb; c = cc;
}
@Override
public int compareTo(Edge o) {
// TODO Auto-generated method stub
return c - o.c;
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
} | Java | ["2\n1\n1 2 3\n1\n1 2", "3\n1\n1 2 3\n2\n1 2\n1 3"] | 4 seconds | ["0", "-1\n3"] | null | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 14842015e645d41071b04235e155f712 | First line of the input contains a single natural number n (2ββ€βnββ€β100000) β the number of objects on the military base. The second line β one number m (1ββ€βmββ€β200000) β the number of the wormholes Baldman can make. The following m lines describe the wormholes: each line contains three integer numbers a,βb,βc (1ββ€βa,βbββ€βn,β1ββ€βcββ€β100000) β the numbers of objects which can be connected and the number of hair Baldman has to spend to make this wormhole. The next line contains one natural number q (1ββ€βqββ€β100000) β the number of queries. Finally, the last q lines contain a description of one query each β a pair of numbers of different objects ai,βbi (1ββ€βai,βbiββ€βn, aiββ βbi). There could be more than one wormhole between a pair of objects. | 2,700 | Your program should output q lines, one for each query. The i-th line should contain a single integer number β the answer for i-th query: the minimum cost (in hair) of a system of wormholes allowing the optimal patrol for any system of tunnels (satisfying the given conditions) if ai and bi are the two objects connected with surface, or "-1" if such system of wormholes cannot be made. | standard output | |
PASSED | 4f17ce83da212c5388f139fcfeab523b | train_003.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String a = in.next();
String b = in.next();
String c = in.next();
n = Math.min(n, a.length());
String[] arr = new String[]{a, b, c};
int[] res = new int[3];
for (int i = 0; i < 3; i++) {
int[] L = new int[26];
int[] U = new int[26];
int max = 0;
for (char ch : arr[i].toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
L[ch - 'a']++;
max = Math.max(max, L[ch - 'a']);
} else {
U[ch - 'A']++;
max = Math.max(max, U[ch - 'A']);
}
}
res[i] = max;
}
for (int i = 0; i < 3; i++) {
if (n != 1) {
res[i] += n;
res[i] = Math.min(a.length(), res[i]);
} else {
if (res[i] != a.length()) {
res[i]++;
} else {
res[i]--;
}
}
}
if (res[0] > res[1] && res[0] > res[2]) {
System.out.println("Kuro");
} else if (res[1] > res[0] && res[1] > res[2]) {
System.out.println("Shiro");
} else if (res[2] > res[0] && res[2] > res[1]) {
System.out.println("Katie");
} else {
System.out.println("Draw");
}
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$)Β β the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | d7ca3aca516b63661947f654fa10c852 | train_003.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
new Solution().solve(in, out);
out.close();
}
}
class Solution {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
String[] stra = new String[3];
for(int i = 0; i < 3; i++) stra[i] = in.next();
int m = stra[0].length();
int[][] letterCount = new int[3][52];
for(int i = 0; i < 3; i++) {
for(int j = 0; j < m; j++){
char c = stra[i].charAt(j);
if(c >= 'a' && c <= 'z') letterCount[i][c-'a']++;
else letterCount[i][c-'A'+26]++;
}
}
int[] maxCount = new int[3];
if(n == 1){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 52; j++){
if(letterCount[i][j] == m) letterCount[i][j] = m-1;
else letterCount[i][j]++;
if(letterCount[i][j] > maxCount[i]) maxCount[i] = letterCount[i][j];
}
}
}else{
for(int i = 0; i < 3; i++){
for(int j = 0; j < 52; j++){
letterCount[i][j] += n;
if(letterCount[i][j] > m) letterCount[i][j] = m;
if(letterCount[i][j] > maxCount[i]) maxCount[i] = letterCount[i][j];
}
}
}
int max = 0;
for(int i = 0; i < 3; i++) max = maxCount[i] > max ? maxCount[i] : max;
int maxc = 0;
for(int i = 0; i < 3; i++) maxc += (maxCount[i] == max) ? 1 : 0;
if(maxc > 1) out.println("Draw");
else if(maxCount[0] == max) out.println("Kuro");
else if(maxCount[1] == max) out.println("Shiro");
else out.println("Katie");
}
}
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());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
try {
s = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$)Β β the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 1251157b088a5293aaad41c3d1624e84 | train_003.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class B979part2 {
public static void main(String[] args) throws IOException {
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
int turns = Integer.parseInt(inp.readLine());
String[] s1 = inp.readLine().split("");
String[] s2 = inp.readLine().split("");
String[] s3 = inp.readLine().split("");
int[] kuroo = new int[200];
int[] shiro = new int[200];
int[] katie = new int[200];
int size = s1.length;
int max1 = 0;
int max2 = 0;
int max3 = 0;
for(int i=0;i<size;i++){
int a = s1[i].charAt(0);
int b = s2[i].charAt(0);
int c = s3[i].charAt(0);
kuroo[a]++;
shiro[b]++;
katie[c]++;
max1 = Math.max(max1,kuroo[a]);
max2 = Math.max(max2,shiro[b]);
max3 = Math.max(max3,katie[c]);
}
//System.out.println(max1+" "+max2+" "+max3);
int left1 = size-max1;
int left2 = size-max2;
int left3 = size-max3;
int win = -2;
if(left1>turns){
left1 = left1-turns;
max1 = size-left1;
}
else{
if(left1==0){
if(turns!=1){
max1 = size;
}
else{
max1 = size-1;
}
}
else{
max1 = size;
}
}
if(left2>turns){
left2 = left2-turns;
max2 = size-left2;
}
else{
if(left2==0){
if(turns!=1){
max2 = size;
}
else{
max2 = size-1;
}
}
else{
max2 = size;
}
}if(left3>turns){
left3 = left3-turns;
max3 = size-left3;
}
else{
if(left3==0){
if(turns!=1){
max3 = size;
}
else{
max3 = size-1;
}
}
else{
max3 = size;
}
}
boolean ans = true;
int[] s = new int[3];
s[0] = max1;
s[1] = max2;
s[2] = max3;
Arrays.sort(s);
win = s[2];
if(ans) {
if(s[2]==s[1]){
System.out.println("Draw");
}
else if (win == max1) {
System.out.println("Kuro");
} else if (win == max2) {
System.out.println("Shiro");
} else {
System.out.println("Katie");
}
}
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$)Β β the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | 4f4819dcbe14139523510a57dd1847c2 | train_003.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class Main {
private static final int MAXN = 5000;
private static final String NO = "NO";
private static final String YES = "YES";
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long MOD = 1000000007L;
private static final long MAX = Long.MAX_VALUE / 2;
int[][] range;
int ans[];
void solve() {
int N = ni();
int l[] = new int[3];
for (int i = 0; i < 3; i++) {
int cnt[] = new int[128];
String str = ns();
for (char c : str.toCharArray())
cnt[c]++;
int max = 0;
for (int c : cnt) {
max = Math.max(max, get(str.length(), N, c));
}
l[i] = max;
}
// tr(l);
String a[] = new String[] { "Kuro", "Shiro", "Katie" };
for (int i = 0; i < 3; i++) {
if (l[i] > l[(i + 1) % 3] && l[i] > l[(i + 2) % 3]) {
out.println(a[i]);
return;
}
}
out.println("Draw");
}
private int get(int N, int round, int cur) {
if (cur + round <= N)
cur += round;
else {
if (cur == N && round == 1)
cur = N - 1;
else
cur = N;
}
return cur;
}
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private boolean vis[];
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private Integer[] na2(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private Integer[][] na2(int n, int m) {
Integer[][] a = new Integer[n][];
for (int i = 0; i < n; i++)
a[i] = na2(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$)Β β the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | fb7aa9e89fc187dd47d8699df24cb745 | train_003.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.util.Scanner;
public class TreasureHunt {
public static String Solve() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String kuro = sc.nextLine(), shiro = sc.nextLine(), katie = sc.nextLine();
sc.close();
String[] output = {"Kuro", "Shiro", "Katie", "Draw"};
if(n >= kuro.length())
return output[3];
int[] maxArr = new int[3];
int[][] freq = new int[3][58];
for(int i = 0; i < kuro.length(); i++) {
maxArr[0] = ++freq[0][kuro.charAt(i) - 65] > maxArr[0]? freq[0][kuro.charAt(i) - 65] : maxArr[0];
maxArr[1] = ++freq[1][shiro.charAt(i) - 65] > maxArr[1]? freq[1][shiro.charAt(i) - 65] : maxArr[1];
maxArr[2] = ++freq[2][katie.charAt(i) - 65] > maxArr[2]? freq[2][katie.charAt(i) - 65] : maxArr[2];
}
int winner = 0, max = 0;
for(int i = 0; i < 3; i++) {
if(kuro.length() - maxArr[i] >= n)
maxArr[i] += n;
else
maxArr[i] = n == 1? kuro.length() - 1: kuro.length();
if(max < maxArr[i]) {
winner = i;
max = maxArr[i];
}
}
return (maxArr[0] == max && maxArr[1] == max)
|| (maxArr[0] == max && maxArr[2] == max)
|| (maxArr[1] == max && maxArr[2] == max)? output[3] : output[winner];
}
public static void main(String[] args) {
System.out.println(Solve());
}
}
| Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$)Β β the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.