exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 28de88116a4d6e471405d13195bbd645 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes |
import java.io.*;
import java.util.*;
public class Educational_Codeforces_Round_54_A {
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
int number = reader.nextInt();
String result = "", s = reader.next();
char[] arr = s.toCharArray();
boolean check = false;
for (int i = 0; i < number - 1; i++) {
if (arr[i] > arr[i + 1]) {
check = true;
result = s.substring(0, i) + s.substring(i + 1, number);
break;
}
}
System.out.print(check ? result : s.substring(0, number - 1));
}
static class InputReader {
StringTokenizer tokenizer;
BufferedReader reader;
String token;
String temp;
public InputReader(InputStream stream) {
tokenizer = null;
reader = new BufferedReader(new InputStreamReader(stream));
}
public InputReader(FileInputStream stream) {
tokenizer = null;
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() throws IOException {
return reader.readLine();
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
if (temp != null) {
tokenizer = new StringTokenizer(temp);
temp = null;
} else {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
}
}
return tokenizer.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 701108101873be916944bfeef9d68c34 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | /**
* 8
* rkqggsab
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int length = Integer.parseInt(br.readLine());
String word = br.readLine();
String ans = word;
for(int i = 0; i < length - 1; i++) {
String current = "" +word.charAt(i);
String next = "" + word.charAt(i + 1);
//System.out.println("actual " + current + " anterior: " + next);
if(current.compareTo(next) > 0 ) {
ans = word.replaceFirst(current, "");
break;
}
}
if(ans == word) {
ans = ans.substring(0, length-1);
}
System.out.println(ans);
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 12d975abbb277190da08db2bc21e6eff | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
InputReader scan = new InputReader();
int n = scan.nextInt();
String in = scan.next();
boolean found = false;
for (int i = 0; i < n-1; i++) {
if (in.charAt(i) > in.charAt(i+1)) {
found = true;
System.out.println(in.substring(0, i)+in.substring(i+1));
break;
}
}
if (!found) System.out.println(in.substring(0,n-1));
}
static class InputReader {
InputStream is = System.in;
byte[] inbuf = new byte[1 << 23];
int lenbuf = 0, ptrbuf = 0;
public InputReader() throws IOException {
lenbuf = is.read(inbuf);
}
public int readByte() {
if (ptrbuf >= lenbuf) {
return -1;
}
return inbuf[ptrbuf++];
}
public boolean hasNext() {
int t = skip();
if (t == -1) {
return false;
}
ptrbuf--;
return true;
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char nextChar() {
return (char) skip();
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public 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);
}
public char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) {
map[i] = ns(m);
}
return map;
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 68722ed906a4212ed030ef1d8d5cb4d3 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class MinimizingTheSreing {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scn = new Scanner(System.in);
int N = scn.nextInt();
String s = scn.next();
if (N == 1) {
if (s.charAt(0) != 'a') {
System.out.println("a");
} else {
System.out.println("");
}
} else {
int check = 0;
int idx = -1;
for (int i = 0; i < N - 1; i++) {
char ch1 = s.charAt(i);
char ch2 = s.charAt(i + 1);
if ((int) ch2 < (int) ch1) {
check++;
idx = i;
break;
}
}
// abdahdjha
if (check > 0) {
System.out.println(s.substring(0, idx) + s.substring(idx + 1));
} else {
System.out.println(s.substring(0, N - 1));
}
}
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 5a26aff6161834a0084359dc7aebe917 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
import java.lang.Math;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
boolean open = true;
char[] arr = sc.nextLine().toCharArray();
for (int i=0; i<n; i++) {
if (i < n-1) {
if (open && arr[i] > arr[i +1])
open = false;
else
System.out.print(Character.toString(arr[i]));
} else if (!open)
System.out.print(Character.toString(arr[i]));
}
System.out.println("");
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | f307899a8c25995bcd09c2c1ed7c1816 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int t = in.nextInt();
in.nextLine();
String s = in.nextLine();
StringBuilder temp = new StringBuilder(s);
//temp.append(s);
String min =temp.toString();
ArrayList<String> st = new ArrayList<>();
int dif = Integer.MIN_VALUE;
int del = s.length()-1;
for(int i = 0;i<s.length()-1;i++) {
if(s.charAt(i)>s.charAt(i+1)&&s.charAt(i)-s.charAt(i+1)>dif)
{
dif = s.charAt(i)-s.charAt(i+1);
del = i;
break;
}
}
temp.deleteCharAt(del);
System.out.println(temp.toString());
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 368275f317ae54e1be78dc375c03978a | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
import java.io.*;
public class a{
static Scanner sc=new Scanner(System.in);
public static void main(String [] args){
int n=sc.nextInt();
String s=sc.next();
StringBuilder ss=new StringBuilder("");
boolean found=false;
for(int i=0;i<n-1;i++){
if(s.charAt(i)>s.charAt(i+1) && !found){
found=true;
}else{
ss.append(s.charAt(i));
}
}
if(found)ss.append(s.charAt(n-1));
System.out.println(ss.toString());
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 81f200cc30c00464a973aa4e3349dddb | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter pw = new PrintWriter(System.out);
int n = Integer.parseInt(sc.next());
String cad = sc.next();
char mayor = 0;
boolean rta = false;
boolean v = false;
for (int i = 0; i < n - 1; i++) {
if (cad.charAt(i) <= cad.charAt(i + 1) || v) {
pw.print(cad.charAt(i));
} else {
v = true;
}
}
if (v) {
pw.println(cad.charAt(n - 1));
} else {
pw.println();
}
pw.close();
}
static class Scanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
int spaces = 0;
public String nextLine() throws IOException {
if (spaces-- > 0) {
return "";
} else if (st.hasMoreTokens()) {
return new StringBuilder(st.nextToken("\n")).toString();
}
return br.readLine();
}
public String next() throws IOException {
spaces = 0;
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public boolean hasNext() throws IOException {
while (!st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return false;
}
if (line.equals("")) {
spaces = Math.max(spaces, 0) + 1;
}
st = new StringTokenizer(line);
}
return true;
}
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 5de4a73f6c329d5d1d44bbbca838dfc3 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
String s = sc.next();
TreeSet set = new TreeSet();
for (int i = 0; i < s.length(); i++) {
set.add(s.charAt(i));
}
boolean cond = false;
StringBuilder rta = new StringBuilder("");
for (int i = 0; i < s.length(); i++) {
if (i != s.length() - 1 && s.charAt(i) > s.charAt(i + 1) && !cond) {
cond = true;
continue;
}
rta.append(s.charAt(i));
}
if (rta.length() == s.length() || set.size() == 1) {
System.out.println(s.substring(0, s.length() - 1));
} else {
System.out.println(rta);
}
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | d577590a193743c551a67c3600d22226 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main (String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
int n = Integer.parseInt(reader.readLine());
String s = reader.readLine();
if(n == 1) {
System.out.println(s);
return;
}
int index = n-1;
for(int i=0;i<n-1;i++) {
char c = s.charAt(i);
char a = s.charAt(i+1);
if(a < c) {
index = i;
break;
}
}
System.out.println(s.substring(0,index)+s.substring(index+1,n));
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 5db3d482f0deba71abcd395d1512eddb | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pranay2516
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt(), ind = n - 1;
char c[] = in.next().toCharArray();
for (int i = 0; i < n - 1; ++i) {
if (c[i + 1] < c[i]) {
ind = i;
break;
}
}
//out.println(ind);
for (int i = 0; i < n; ++i) if (i != ind) out.print(c[i]);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public 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\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 23051ce585e203c4aa53baf4f87488d1 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class MinimizingTheString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String ns = sc.next();
for (int i = 0; i < n-1; i++) {
if (ns.charAt(i) > ns.charAt(i + 1)) {
System.out.println(ns.substring(0, i) + ns.substring(i+1));
return;
}
}
System.out.println(ns.substring(0,n-1));
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 02bbf70c2192d15179a0683783c21b3b | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static int mod = 1000000007;
public static void solve(InputReader in) {
int n = in.readInt();
char s[] = in.readString().toCharArray();
int index = n-1;
for(int i = 0; i<n-1; i++) {
if(s[i] > s[i+1]) {
index = i;
break;
}
}
s[index] = '4';
for(char c : s) {
if(c == '4') continue;
System.out.print(c);
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
int t = 1;
while (t-- > 0)
solve(in);
}
}
class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 62e714cfbf0b07dbe2f950d92953356c | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 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;
}
}
public static long function(long n)
{
long mod = n % 4;
if (mod == 0)
return n;
// If n % 4 gives remainder 1
else if (mod == 1)
return 1;
// If n % 4 gives remainder 2
else if (mod == 2)
return n + 1;
// If n % 4 gives remainder 3
else if (mod == 3)
return (long)0;
return (long)0;
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
String s = sc.next();
int l = s.length();
int index = l-1;
for(int i=1;i<l;i++)
{
if(s.charAt(i)>=s.charAt(i-1))
continue;
else
{
index = i-1;
break;
}
}
for(int i=0;i<l;i++)
{
if(index!=i)
w.print(s.charAt(i));
}
w.println();
w.flush();
w.close();
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | a7bb2f972336ed9b17e85afc0a7cdcc7 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class MinimizingTheString1076A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
String str = scan.nextLine();
StringBuilder temp = new StringBuilder(str);
int index = n-1;
for(int i = 0; i < n-1; i++) {
if(str.charAt(i) > str.charAt(i+1)) {
index = i;
break;
}
}
scan.close();
String res = temp.deleteCharAt(index).toString();
System.out.println(res);
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | d0b80c06cca956d3ca5519ca8bba83e4 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class myFile
{
public static void main(String args[]) throws IOException
{
int i,n;
boolean found=false;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s[]=br.readLine().split(" ");
n = Integer.parseInt(s[0]);
String str=br.readLine();
StringBuilder sb = new StringBuilder(str);
for(i=0;i<str.length()-1;i++)
{
if(str.charAt(i)>str.charAt(i+1) && found==false)
{
sb = sb.deleteCharAt(i);
found=true;
}
}
if(found==false)
sb.deleteCharAt(n-1);
System.out.println(sb);
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 0faaf5151a4ce3d4005030d462c21506 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class Main {
//COmment
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.nextInt();
String full=input.next();
for(int x=1;x<full.length();x++){
if(full.charAt(x)<full.charAt(x-1)){
System.out.println(full.substring(0,x-1)+full.substring(x));
return;
}
}
System.out.println(full.substring(0,full.length()-1));
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | b40aed0e26d6e0704ccfde9fb4e88db3 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
import java.io.IOException;
public class aa
{
public static void main(String[]args)throws IOException
{ Scanner sc=new Scanner (System.in);
int n=sc.nextInt();
String s=sc.next();
String ns=""; char max='$';
for(int i=0;i<n-1;i++)
{
if(s.charAt(i)>s.charAt(i+1))
{max=s.charAt(i);
ns=s.substring(0,s.indexOf(max))+s.substring(s.indexOf(max)+1);break;}
}
if(max=='$')
{
ns=s.substring(0,n-1);
}
System.out.println(ns);
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 6a4fdfeb2bf02e43bed7b3fa524f05b4 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
import java.io.IOException;
public class againtwentyfive
{
public static void main(String[]args)throws IOException
{ Scanner sc=new Scanner (System.in);
int n=sc.nextInt();
String s=sc.next();
int c=0;
for(int i=0;i<n-1;i++)
{
if(s.charAt(i)>s.charAt(i+1))
{s=s.substring(0,i)+"$"+s.substring(i+1);
c++;
break;}
}
if(c!=0)
{for(int i=0;i<n;i++)
{
if(s.charAt(i)!='$')
System.out.print(s.charAt(i));
}
}
else
{
for(int i=0;i<n-1;i++)
System.out.print(s.charAt(i));
}
}
} | Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 2fcf338c29a45a6b058f74ae7a633022 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.*;
import java.io.IOException;
public class againtwentyfive
{
public static void main(String[]args)throws IOException
{ Scanner sc=new Scanner (System.in);
int n=sc.nextInt();
String s=sc.next();
int c=0;
for(int i=0;i<n-1;i++)
{
if(s.charAt(i)>s.charAt(i+1))
{s=s.substring(0,i)+"#"+s.substring(i+1);
c++;
break;}
}
if(c!=0)
{for(int i=0;i<n;i++)
{
if(s.charAt(i)!='#')
System.out.print(s.charAt(i));
}
}
else
{
for(int i=0;i<n-1;i++)
System.out.print(s.charAt(i));
}
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 3838f5021e78037e827d7ed425818dec | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner jin = new Scanner(System.in);
jin.nextLine();
String str = jin.nextLine();
for (int i = 0; i < str.length() - 1; ++i) {
if (str.charAt(i) > str.charAt(i + 1)) {
System.out.println(str.substring(0, i) + str.substring(i + 1, str.length()));
return;
}
}
System.out.println(str.substring(0, str.length() - 1));
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 5bfbb805c8798a9e12f26c1d812f7427 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class orffjab
{
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
String s=sc.next();
int a=t-1;
int i=0;
while(i<t-1){
if((int)s.charAt(i)>(int)s.charAt(i+1)){
a=i;
break;
}
i++;
}
if(a==0){
System.out.println(s.substring(1,t));
}
else if(a==t-1){
System.out.println(s.substring(0,a));
}
else{
System.out.println(s.substring(0,a)+s.substring(a+1,t));
}
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | 459d3f36523d1438b0c4829cdd6362e0 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.util.Scanner;
public class minimizingstring {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
sc.close();
String ans = "";
for(int i = 0; i + 1 < n; i++) {
if(s.charAt(i) - s.charAt(i+1) > 0) {
ans = s.substring(0, i) + s.substring(i+1);
break;
}
}
if(ans.length() == 0) {
ans = s.substring(0, n-1);
}
System.out.println(ans);
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | bb76706c1617f8371dd77f6de43a5c77 | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.io.*;
import java.util.*;
public class Towers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String temp = input.nextLine();
String str = input.nextLine();
int to_delete = -1;
for ( int i = 0; i < str.length() - 1; i++){
if ( str.charAt(i) > str.charAt(i + 1) ){
to_delete = i;
break;
}
}
if ( to_delete == -1 ){
for ( int i = 0; i < str.length() - 1; i++){
System.out.print(str.charAt(i));
}
}
else {
for ( int i =0 ; i < str.length(); i++){
if ( to_delete != i )
System.out.print(str.charAt(i));
}
}
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | e05a2cbc1df44a725c10b31a238f3c0b | train_000.jsonl | 1542033300 | You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". | 256 megabytes | import java.io.*;
import java.util.*;
public class MinimizeTheString
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int N = Integer.parseInt(br.readLine().trim());
String st = br.readLine();
if(N == 1)
{
pw.println();
}
else
{
int max = (int)st.charAt(0);
int maxIndex = 0;
for(int i = 1 ; i < N ; i++)
{
// System.out.println("CharAt "+ i +" "+(int)st.charAt(i));
if(st.charAt(i) > max)
{
max = (int)st.charAt(i);
maxIndex = i;
/* System.out.println("Hello MAX==>" + max);
System.out.println("Hello MAXIndex==>" + maxIndex);*/
}
}
for(int i = 0 ; i < N - 1 ; i++)
{
if(st.charAt(i) > st.charAt(i + 1))
{
maxIndex = i;
break;
}
}
StringBuilder sbr = new StringBuilder();
for(int i = 0 ; i < N ; i++)
{
if(i == maxIndex)
{
continue;
}
sbr.append(new StringBuilder(Character.toString(st.charAt(i))));
}
pw.println(sbr);
}
pw.close();
}
}
| Java | ["3\naaa", "5\nabcda"] | 1 second | ["aa", "abca"] | NoteIn the first example you can remove any character of $$$s$$$ to obtain the string "aa".In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". | Java 8 | standard input | [
"greedy",
"strings"
] | c01fc2cb6efc7eef290be12015f8d920 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters — the string $$$s$$$. | 1,200 | Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$. | standard output | |
PASSED | a79da74ac28f0c20909789c6f488b61b | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | // Author: Param Singh <[email protected]>
// Kefa and Park: http://codeforces.com/contest/580/problem/C
import java.io.*;
import java.util.*;
public class Kefa {
static class Node {
List<Node> children;
int id;
int num;
boolean cat;
int left, right;
Node() {
left = right = 0;
children = new ArrayList<Node>();
num = 0;
cat = false;
}
void add_child(Node x) {
num++;
children.add(x);
}
void add_cat() {
cat = true;
}
}
public static int num_leafs(Node vertex, Node prev, int consecutive, int m) {
int ans = 0;
if (vertex.num == 1 && prev != null) {
if (vertex.cat)
consecutive++;
if (m >= consecutive)
ans = 1;
else
ans = 0;
}
else {
if (vertex.cat) {
if (m == consecutive)
ans = 0;
else {
for (Node x: vertex.children) {
if (prev != null && prev.id == x.id)
continue;
ans += num_leafs(x, vertex, consecutive+1, m);
}
}
}
else {
for (Node x: vertex.children) {
if (prev != null && prev.id == x.id)
continue;
ans += num_leafs(x, vertex, 0, m);
}
return ans;
}
}
return ans;
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s[] = in.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
s = in.readLine().split(" ");
Node tree[] = new Node[n];
for (int i = 0; i < n; i++) {
tree[i] = new Node();
tree[i].id = i;
if (s[i].equals("1"))
tree[i].add_cat();
}
if (n == 1) {
if (tree[0].cat && m != 0)
System.out.println(0);
else
System.out.println(1);
System.exit(0);
}
int a, b;
for (int i = 1; i < n; i++) {
s = in.readLine().split(" ");
a = Integer.parseInt(s[0]);
b = Integer.parseInt(s[1]);
tree[a-1].add_child(tree[b-1]);
tree[b-1].add_child(tree[a-1]);
}
System.out.println(num_leafs(tree[0], null, 0, m));
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 14582e854356d91cda08b0505e94592b | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.*;
public class Test {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
vertex[] v=new vertex[n];
for(int i=0;i<n;i++){
v[i]=new vertex(i,sc.nextInt());
}
for(int i=0;i<n-1;i++){
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
v[a].next.add(v[a].n, v[b]);
v[a].n++;
v[b].next.add(v[b].n,v[a]);
v[b].n++;
}
Stack<vertex> st=new Stack<vertex>();
st.push(v[0]);
int[] visited=new int[n];
if(v[0].cat) v[0].c++;
visited[0]=1;
int cnt=0;
while(!st.isEmpty()){
vertex tmp=st.pop();
int flag=0;
for(int i=0;i<tmp.n;i++){
if(visited[tmp.next.get(i).id]==0){
flag=1;
if(tmp.c<=m){
st.push(tmp.next.get(i));
}
visited[tmp.next.get(i).id]=1;
if(tmp.next.get(i).cat||tmp.c>m){
tmp.next.get(i).c=1+tmp.c;
}
}
}
if(flag==0&&tmp.c<=m){
cnt++;
}
}
System.out.println(cnt);
}
}
class vertex{
boolean cat;
int n;
int c=0;
ArrayList<vertex> next=new ArrayList<vertex>();
int id;
vertex(int i,int a){
if(a==1) cat=true;
else cat=false;
id=i;
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | acd19cf84b46868d4701681a66751458 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
public class Park {
public static void main(String[] args) throws java.lang.Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in, out);
out.close();
}
}
class TaskA {
public final static int maxn = (int)(1e5+5);
public adj[] E = new adj[maxn];
public int[] a = new int[maxn];
int n, m;
int ans = 0;
public void solve(InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
int i, j, k;
for (i=1; i<=n; ++i) {
a[i] = in.nextInt();
E[i] = new adj();
}
for (i=1; i<n; ++i) {
j = in.nextInt();
k = in.nextInt();
E[j].add(k);
E[k].add(j);
}
dfs(1, 0, a[1]);
out.println(ans);
}
private void dfs(int u, int fa, int cn) {
int sz = E[u].size(), v;
int c = 0, cn_;
if (cn > m)
return ;
for (int i=0; i<sz; ++i) {
v = E[u].get(i);
if (v == fa)
continue;
++c;
cn_ = a[v]>0 ? cn+1 : 0;
dfs(v, u, cn_);
}
if (c==0 && cn<=m)
++ans;
}
}
class adj {
ArrayList<Integer> m;
public adj() {
m = new ArrayList<Integer>();
}
public int size() {
return m.size();
}
public int get(int x) {
return m.get(x);
}
public void add(int x) {
m.add(x);
}
}
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\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 050d41cd5b3c574b0b8875bec477442e | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
public class C {
static int n;
static int m;
static boolean[] hasCat;
static List<Set<Integer>> graph;
static int answer;
public static void main(String[] args) {
Scanner scanner = new Scanner();
n = scanner.nextInt();
m = scanner.nextInt();
hasCat = new boolean[n];
graph = new ArrayList<>();
answer = 0;
for (int i = 0; i < n; i++) {
hasCat[i] = scanner.nextInt() == 1;
graph.add(new HashSet<Integer>());
}
for (int i = 0; i < n-1; i++) {
int x = scanner.nextInt()-1;
int y = scanner.nextInt()-1;
graph.get(x).add(y);
graph.get(y).add(x);
}
search(0, 0, -1);
System.out.println(answer);
}
static void search(int vertex, int catsSoFar, int parent) {
if (hasCat[vertex]) {
catsSoFar++;
} else {
catsSoFar = 0;
}
if (catsSoFar > m) {
return;
}
if (isLeaf(vertex)) {
answer++;
} else {
for (int child : graph.get(vertex)) {
if (child != parent) {
search(child, catsSoFar, vertex);
}
}
}
}
static boolean isLeaf(int vertex) {
return graph.get(vertex).size() == 1 && vertex != 0;
}
public static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(Reader in) {
br = new BufferedReader(in);
}
public Scanner() { this(new InputStreamReader(System.in)); }
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
// Slightly different from java.util.Scanner.nextLine(),
// which returns any remaining characters in current line,
// if any.
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 20c8ac2e8c33d88903e248148ce188a6 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
private static int n, m, cnt;
private static boolean[] cat;
private static Map<Integer, List<Integer>> adjacency;
private static void dfs(int cur, int prev, int catCnt) {
if (cat[cur]) {
catCnt++;
if (catCnt > m) return;
} else
catCnt = 0;
List<Integer> list = adjacency.get(cur);
if (list.size() == 1 && list.get(0) == prev) {
cnt++;
return;
}
for (Integer i: list)
if (i != prev) dfs(i, cur, catCnt);
}
private static void solve(InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
cat = new boolean[n + 1];
for (int i = 1; i <= n; i++)
if (in.nextInt() == 1) cat[i] = true;
adjacency = new HashMap<Integer, List<Integer>>();
int x, y;
for (int i = 0; i < n - 1; i++) {
x = in.nextInt();
y = in.nextInt();
if (!adjacency.containsKey(x)) adjacency.put(x, new ArrayList<Integer>());
if (!adjacency.containsKey(y)) adjacency.put(y, new ArrayList<Integer>());
adjacency.get(x).add(y);
adjacency.get(y).add(x);
}
cnt = 0;
dfs(1, 0, 0);
out.print(cnt);
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
solve(in, out);
in.close();
out.close();
}
private static class InputReader {
private BufferedReader br;
private StringTokenizer st;
InputReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = null;
}
String nextLine() {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String line = nextLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class OutputWriter {
BufferedWriter bw;
OutputWriter(OutputStream os) {
bw = new BufferedWriter(new OutputStreamWriter(os));
}
void print(int i) {
print(Integer.toString(i));
}
void println(int i) {
println(Integer.toString(i));
}
void print(long l) {
print(Long.toString(l));
}
void println(long l) {
println(Long.toString(l));
}
void print(double d) {
print(Double.toString(d));
}
void println(double d) {
println(Double.toString(d));
}
void print(boolean b) {
print(Boolean.toString(b));
}
void println(boolean b) {
println(Boolean.toString(b));
}
void print(char c) {
try {
bw.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(char c) {
println(Character.toString(c));
}
void print(String s) {
try {
bw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
}
void println(String s) {
print(s);
print('\n');
}
void close() {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 921f8411b8dfc6474e1504f99e664164 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Program {
static InputReader I = new InputReader(System.in);
static PrintWriter O = new PrintWriter(System.out);
static List<Integer>[] G;
static int[] isCat;
static int[] catCount;
static int m;
static int ans = 0;
static boolean[] vis;
static void dfs(int v) {
vis[v] = true;
if (catCount[v] > m) {
return;
}
int cnt = 0;
for (int x : G[v]) {
if (!vis[x]) {
catCount[x] = catCount[v] + isCat[x];
if (isCat[x] == 0) catCount[x] = 0;
dfs(x);
cnt++;
}
}
if(cnt == 0) ans++;
}
public static void main(String[] args) {
int n = I.nextInt();
m = I.nextInt();
G = new ArrayList[n];
isCat = new int[n];
vis = new boolean[n];
catCount = new int[n];
for (int i = 0; i < n; ++i) {
isCat[i] = I.nextInt();
G[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; ++i) {
int v = I.nextInt();
int u = I.nextInt();
u--;
v--;
G[v].add(u);
G[u].add(v);
}
catCount[0] = isCat[0];
dfs(0);
O.print(ans);
O.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 589004df5d4d659efa300c27ae56e8f3 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class C {
private static class v {
boolean cat;
ArrayList<v> c = new ArrayList<>();
public v(boolean cat) {
this.cat = cat;
}
}
private static int bfs(v node, int currM, int m, v par) {
if (node.cat) {
currM++;
} else {
currM = 0;
}
if (currM > m) {
return 0;
} else {
if (par == null || node.c.size() > 1) {
int sum = 0;
for (v ch : node.c) {
if (par == null || !ch.equals(par)) {
sum += bfs(ch, currM, m, node);
}
}
return sum;
} else {
return 1;
}
}
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String[] as = br.readLine().split(" ");
int n = Integer.parseInt(as[0]);
int m = Integer.parseInt(as[1]);
as = br.readLine().split(" ");
v[] vs = new v[n + 1];
for (int i = 0; i < n; i++) {
if (as[i].equals("1")) {
vs[i + 1] = new v(true);
} else {
vs[i + 1] = new v(false);
}
}
for (int i = 0; i < n - 1; i++) {
as = br.readLine().split(" ");
vs[Integer.parseInt(as[0])].c.add(vs[Integer.parseInt(as[1])]);
vs[Integer.parseInt(as[1])].c.add(vs[Integer.parseInt(as[0])]);
}
System.out.println(bfs(vs[1], 0, m, null));
} catch (IOException ex) {
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 60c299066e09ab325d35a51b30fc4175 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Locale;
import java.util.StringTokenizer;
public class Main implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Thread(null, new Main(), "", 128 * (1L << 20)).start();
}
void init() throws FileNotFoundException {
Locale.setDefault(Locale.US);
/*if(ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}else {
in = new BufferedReader(new FileReader("INPUT.TXT"));
out = new PrintWriter("OUTPUT.TXT");
}*/
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
init();
solve();
out.close();
time();
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
String readString(String s) throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), s + "\n \t");
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
int readInt(String s) throws IOException {
return Integer.parseInt(readString(s));
}
boolean isPrime(int a) throws IOException {
int del = 0;
if (a == 2) {
return true;
}
for (int i = 2; i < Math.sqrt(a) + 1; i++) {
if (a % i == 0) {
del = i;
break;
}
}
if (del > 0) {
return false;
} else return true;
}
public long factorial(int num) throws IOException {
long res = 1;
for (int i = 2; i <= num; i++) {
res *= i;
}
return res;
}
public int[] readIntArr(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = readInt();
}
return a;
}
public class pair implements Comparable<pair>{
long money, value;
public pair(int money, int value){
this.money = money;
this.value = value;
}
@Override
public int compareTo(pair pair) {
if(pair.money>this.money){
return -1;
}return 1;
}
}
static int res = 0;
boolean[] used;
void solve() throws Exception{
int n=readInt();
int m=readInt();
used = new boolean[n];
int[] cat = readIntArr(n);
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i]=new ArrayList<Integer>();
}
for (int i = 0; i < n-1; i++) {
int from = readInt()-1;
int to = readInt()-1;
graph[from].add(to);
graph[to].add(from);
}
if(cat[0]==1) {
dfs(graph, 1, cat, 0, m, -1);
}else{
dfs(graph, 0, cat, 0, m, -1);
}
System.out.println(res);
}
public void dfs(ArrayList<Integer>[] graph, int currCat, int[] cats, int curr, int maxCat, int prev){
used[curr]=true;
if(graph[curr].size()==1 && graph[curr].get(0)==prev){
res++;
return;
}
for (int i = 0; i < graph[curr].size(); i++) {
int to = graph[curr].get(i);
if(used[to])continue;
if(cats[to]==1){
int cCat = currCat+1;
if(cCat<=maxCat){
dfs(graph, cCat, cats, to, maxCat, curr);
}
}
else{
dfs(graph, 0, cats, to, maxCat, curr);
}
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 1c724218ccce85b1248c33436de34a55 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.*;
import java.io.*;
public class Major {
static int decide[];
static ArrayList<Integer>list[];
static int ans = 0;
static boolean cont = true;
static boolean leaf[];
static int m;
static void dfs(int start,int tot,boolean visited[]){
visited[start] = true;
if(decide[start] == 1 && cont)tot++;
else if(decide[start] == 1 && !cont){
cont = true;tot++;
}
else if(decide[start] == 0){
cont = false;tot = 0;
}
if(tot > m)return;
for(int temp : list[start]){
if(!visited[temp])
dfs(temp,tot,visited);
}
if(leaf[start] && tot <= m)ans++;
}
public static void main(String [] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
decide = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0;i < n;i++){
decide[i] = Integer.parseInt(st.nextToken());
}
list = new ArrayList[n];
for(int i = 0;i < n;i++)
list[i] = new ArrayList<Integer>();
boolean visited[] = new boolean[n];
int deg[] = new int[n];
leaf = new boolean[n];
for(int i = 0;i < n - 1 ;i++){
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken()) - 1;
int y = Integer.parseInt(st.nextToken()) - 1;
list[x].add(y);
list[y].add(x);
deg[x]++;
deg[y]++;
}
for(int i = 0;i < n;i++)
if(deg[i] == 1 && i != 0){
leaf[i] = true;
}
dfs(0,0,visited);
System.out.print(ans);
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 81fe9b644cfdef2f598f53f56502d109 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes |
import java.awt.Point;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
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.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import static java.lang.Math.*;
/**
*
* @author Mojtaba
*/
public class Main {
static int n, m;
static boolean[] cats;
static boolean[] visited;
static long sum;
static ArrayList<Edge>[] graph;
public static void main(String[] args) throws IOException {
MyScanner in = new MyScanner(System.in);
PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out));
StringBuilder sb = new StringBuilder("");
n = in.nextInt();
m = in.nextInt();
cats = new boolean[n];
graph = new ArrayList[n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
cats[i] = in.nextInt() == 1;
}
for (int i = 1; i < n; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
graph[from].add(new Edge(from, to));
graph[to].add(new Edge(to, from));
}
DFS(0, 0, false);
sb.append(sum);
//System.out.println(sb.toString().trim());
writer.println(sb.toString().trim());
writer.flush();
in.close();
}
static void sort(int[] a) {
Random rand = new Random();
for (int i = a.length - 1; i > 0; i--) {
int index = rand.nextInt(i + 1);
// Simple swap
int temp = a[index];
a[index] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
private static void DFS(int vertex, int con, boolean b) {
if (visited[vertex]) {
return;
}
visited[vertex] = true;
if (cats[vertex]) {
con++;
}
if (con > m) {
//b = true;
return;
}
if (!cats[vertex]) {
con = 0;
}
if (graph[vertex].size() == 1 && !b && vertex != 0) {
sum++;
}
for (Edge e : graph[vertex]) {
if (e.to != vertex) {
DFS(e.to, con, b);
}
}
}
}
class Edge {
int from, to;
public Edge(int from, int to) {
this.from = from;
this.to = to;
}
}
class MyScanner {
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntegerArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < a.length; i++) {
a[i] = nextLong();
}
return a;
}
public int nextInt(int radix) throws IOException {
return Integer.parseInt(next(), radix);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long nextLong(int radix) throws IOException {
return Long.parseLong(next(), radix);
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public BigInteger nextBigInteger(int radix) throws IOException {
return new BigInteger(next(), radix);
}
public String next() throws IOException {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
return this.next();
}
return tokenizer.nextToken();
}
public void close() throws IOException {
this.reader.close();
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | b9453821c983b4e3639e75d719bc485c | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static int K = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
boolean cats[] = new boolean[n];
LinkedList<Integer>[] ll = new LinkedList[n];
for(int i = 0; i < n; i++){
ll[i] = new LinkedList<Integer>();
}
for(int i = 0; i < n; i++){
int c = sc.nextInt();
if(c == 0){
cats[i] = false;
}else{
cats[i] =true;
}
}
for(int i = 0; i< n-1; i++){
int a = sc.nextInt();
int b = sc.nextInt();
ll[a-1].add(b-1);
ll[b-1].add(a-1);
}
boolean bb[] = new boolean[n];
Arrays.fill(bb, false);
BFS(ll, bb, cats, 0, 0, m);
System.out.println(K);
}
public static void BFS(LinkedList<Integer>[] ll, boolean visited[], boolean cats[], int Ncats, int pos, int max){
if(cats[pos]){
Ncats ++;
}else{
Ncats = 0;
}
visited[pos] = true;
if(Ncats <= max){
int s = 0;
for(Integer i : ll[pos]){
if(!visited[i]){
s++;
BFS(ll, visited, cats, Ncats, i, max);
}
}
if(s == 0){
K++;
}
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 52d3d07c0bd2e50668d471545d62f81d | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.*;
public class C {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
adj = new ArrayList[n];
for(int i = 0; i < n; i ++)
adj[i] = new ArrayList<Integer>();
cats = new boolean[n];
for(int i = 0; i < n; i ++)
cats[i] = in.nextInt() == 1;
for(int i = 0; i < n - 1; i ++)
{
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
adj[x].add(y);
adj[y].add(x);
}
adj[0].add(0);
System.out.println(go(0, 0, 0));
}
static ArrayList<Integer>[] adj;
static int n;
static int m;
static boolean[] cats;
static int go(int prev, int c, int at)
{
if(cats[at])
c++;
else
c = 0;
// System.out.println(at +" " + prev + " " + c);
if(c > m)
{
// System.out.println(at + " " + c);
return 0;
}
// System.out.println(at + " " + prev + " " + c);
if(adj[at].size() == 1)
{
// System.out.println("!");
return 1;
}
int ans = 0;
for(int e: adj[at])
{
if(e == prev)
continue;
ans += go(at, c, e);
}
return ans;
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 82972d1c557ddb0496b53cb05a1552ca | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
static class Graph
{
ArrayList<Vertex> vertex;
public Graph()
{
vertex = new ArrayList<>();
}
public Graph(int vertexCount)
{
vertex = new ArrayList<>();
for (int i=0; i<vertexCount; i++)
vertex.add(new Vertex(0));
}
public void addEdge (int source, int destination, int weight)
{
vertex.get(source).edges.add(new Edge(destination, weight));
}
}
static class Vertex
{
ArrayList<Edge> edges; int data;
public Vertex (int data)
{
this.data = data;
edges = new ArrayList<>();
}
}
static class Edge
{
int destination, weight;
public Edge (int destination, int weight)
{
this.destination = destination;
this.weight = weight;
}
}
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
outputStream, "ASCII"));
CustomScanner sc = new CustomScanner(inputStream);
solve(sc, out);
out.flush();
out.close();
}
static void solve(CustomScanner sc, BufferedWriter out) throws IOException {
int n = sc.nextInt(), m = sc.nextInt();
Graph g = new Graph(n);
for (int i=0; i<n; i++)
{
int a = sc.nextInt();
g.vertex.get(i).data = a;
}
for (int i=1; i<=n-1; i++)
{
int x= sc.nextInt()-1, y =sc.nextInt()-1;
g.addEdge(x, y, 0);
g.addEdge(y, x, 0);
}
boolean[] visited = new boolean[n];
getPossiblePaths(g, 0, visited, m, 0);
out.write(Integer.toString(totalPaths));
out.newLine();
}
static int totalPaths = 0;
static void getPossiblePaths(Graph g, int v, boolean[] visited, int m, int consecutiveCats)
{
Vertex curr = g.vertex.get(v);
visited[v] = true;
if (consecutiveCats==m && curr.data==1)
return;
if (curr.edges.size()==1 && v>0)
{
totalPaths++;
return;
}
int cats = (curr.data==0)?0:consecutiveCats+1;
for (Edge e: curr.edges)
{
if (!visited[e.destination])
getPossiblePaths(g, e.destination, visited, m, cats);
}
}
static class CustomScanner {
BufferedReader br;
StringTokenizer st;
public CustomScanner(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
private String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 59b3310e3f23c880942fb5bd1a981826 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.*;
import java.util.*;
public class c2 {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public static void main(String[] args) throws IOException {
new c2().run();
}
static int cat[];
static ArrayList<Integer> edges[];
static int ans;
static boolean was[];
static int m;
static void dfs(int cur, int cnt, boolean w) {
boolean fl = w;
if (cnt > m){
fl = true;
}
int deg = 0;
was[cur] = true;
for (int i : edges[cur]) {
if (!was[i]) {
if (cat[i] == 1) {
dfs(i, cnt + 1, fl);
} else {
dfs(i, 0, fl);
}
deg++;
}
}
if (deg == 0 && cnt <= m && !fl) {
ans++;
}
}
public void solve() throws IOException {
int n = nextInt();
m = nextInt();
edges = new ArrayList[n];
cat = new int[n];
was = new boolean[n];
for (int i = 0; i < n; i++) {
cat[i] = nextInt();
was[i] = false;
}
for (int i = 0; i < n; i++) {
edges[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++) {
int x = nextInt() - 1;
int y = nextInt() - 1;
edges[x].add(y);
edges[y].add(x);
}
ans = 0;
if (cat[0] == 1) {
dfs(0, 1, false);
} else {
dfs(0, 0, false);
}
out.println(ans);
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 7855da213d0a6f316082041ed57c6ca8 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.Character.Subset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import javax.management.RuntimeErrorException;
public class Codeforces {
StringTokenizer tok;
BufferedReader in;
PrintWriter out;
final boolean OJ = System.getProperty("ONLINE_JUDGE") != null;
void init() {
try {
if (OJ) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
String readString() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
public static void main(String[] args) {
new Codeforces().run();
}
void run() {
init();
long time = System.currentTimeMillis();
solve();
System.err.println(System.currentTimeMillis() - time);
out.close();
}
class Friend implements Comparable<Friend> {
int a;
int b;
public Friend(int a, int b) {
super();
this.a = a;
this.b = b;
}
@Override
public int compareTo(Friend arg0) {
return a - arg0.a;
}
}
ArrayList<Integer>[] graph;
int[] cat;
int m;
int ans;
void dfs(int x, int cnt, int p) {
if (cat[x] == 1) {
cnt++;
} else {
cnt = 0;
}
if (cnt > m) return;
if (graph[x].size() == 1 && p != -1) {
ans++;
return;
}
for (int y : graph[x]) {
if (y != p)
dfs(y, cnt, x);
}
}
void solve() {
int n = readInt();
m = readInt();
graph = new ArrayList[n];
for (int i=0;i<n;i++) graph[i] = new ArrayList<Integer>();
cat = new int[n];
for (int i=0;i<n;i++) {
cat[i] = readInt();
}
for (int i=0;i<n - 1;i++) {
int a = readInt()-1;
int b = readInt()-1;
graph[a].add(b);
graph[b].add(a);
}
dfs(0,0,-1);
out.println(ans);
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | b2cf343dd1276f36c892abadfd54f93f | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by smalex on 22/09/15.
*/
public class P580C {
static BufferedReader in;
static StringTokenizer tok;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
int m = nextInt();
int[] cats = nextIntArray(n, 0);
Map<Integer, List<Integer>> connected = new HashMap<>();
for (int i = 1; i < n; i++) {
int a = nextInt();
int b = nextInt();
connectVertex(connected, a, b);
connectVertex(connected, b, a);
}
int[] costs = new int[n + 1];
Arrays.fill(costs, Integer.MAX_VALUE);
costs[1] = cats[0];
LinkedList<Integer> q = new LinkedList<>();
q.add(1);
boolean[] visited = new boolean[n + 1];
boolean[] isLeaf = new boolean[n + 1];
Arrays.fill(isLeaf, true);
visited[1] = true;
while (!q.isEmpty()) {
Integer pop = q.pop();
int cost = costs[pop];
List<Integer> vertexes = connected.get(pop);
if (vertexes != null) {
for (Integer vertex : vertexes) {
int cat = cats[vertex - 1];
if (!visited[vertex]) {
visited[vertex] = true;
isLeaf[pop] = false;
costs[vertex] = Math.min(newCost(cost, cat), costs[vertex]);
if (costs[vertex] <= m) {
q.add(vertex);
}
}
}
}
}
// System.out.println("costs = " + Arrays.toString(costs));
// System.out.println("isLeaf = " + Arrays.toString(isLeaf));
int res = 0;
for (int i = 2; i < costs.length; i++) {
if (costs[i] <= m && isLeaf[i]) {
res++;
}
}
System.out.println(res);
}
private static int newCost(int cost, int cat) {
return cat == 0 ? 0 : cost + cat;
}
private static void connectVertex(Map<Integer, List<Integer>> connected, int a, int b) {
List<Integer> values = connected.get(a);
if (values == null) {
values = new ArrayList<>();
connected.put(a, values);
}
values.add(b);
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static int[] nextIntArray(int len, int start) throws IOException {
int[] a = new int[len];
for (int i = start; i < len; i++)
a[i] = nextInt();
return a;
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static long[] nextLongArray(int len, int start) throws IOException {
long[] a = new long[len];
for (int i = start; i < len; i++)
a[i] = nextLong();
return a;
}
static String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | bbb38e56dfd2595cb68fdebe668ba46d | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class Main {
public static PrintWriter out;
public static void main(String args[]) {
MyScanner in = new MyScanner();
int n = in.nextInt();
int m = in.nextInt();
int[] presenOfCat = new int[n + 1];
for (int i = 1; i <= n; i++) {
presenOfCat[i] = in.nextInt();
}
int[] visited = new int[n + 1];
Map<Integer, List> edges = new TreeMap<Integer, List>();
List<Boolean> visitedEdge = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int sourceEdge = in.nextInt();
int destinationEdge = in.nextInt();
if (!edges.containsKey(sourceEdge)) {
List<Integer> list = new ArrayList<>();
list.add(destinationEdge);
edges.put(sourceEdge, list);
} else {
List<Integer> list = edges.get(sourceEdge);
list.add(destinationEdge);
edges.put(sourceEdge, list);
}
if (!edges.containsKey(destinationEdge)) {
List<Integer> list = new ArrayList<>();
list.add(sourceEdge);
edges.put(destinationEdge, list);
} else {
List<Integer> list = edges.get(destinationEdge);
list.add(sourceEdge);
edges.put(destinationEdge, list);
}
}
int current = 0;
if (presenOfCat[1] == 1) {
current++;
}
System.out.println(getRestaurent(edges, presenOfCat, current, 1, m));
}
private static long getRestaurent(Map<Integer, List> edges, int[] presenOfCat, int current, int root, int m) {
if (!edges.containsKey(root))
return 1;
List<Integer> connectedVertices = edges.get(root);
long count = 0;
for (int i = 0; i < connectedVertices.size(); i++) {
List<Integer> removeList = edges.get(connectedVertices.get(i));
if (removeList.contains(root)) {
removeList.remove(new Integer(root));
if (removeList.size() == 0)
edges.remove(connectedVertices.get(i));
else
edges.put(connectedVertices.get(i), removeList);
}
int localCurrent = current;
if (presenOfCat[connectedVertices.get(i)] == 1) {
localCurrent++;
} else
localCurrent = 0;
if (localCurrent <= m)
count += getRestaurent(edges, presenOfCat, localCurrent, connectedVertices.get(i), m);
}
return count;
}
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 | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 1af064adeaf143e7ba53fafcbc4b3f5a | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
public class TaskRunner {
public static List<Integer>[] g;
public static boolean[] prime;
public static boolean[] visited;
public static StringTokenizer st;
public static BufferedReader br;
public static PrintWriter out;
public static int[] tree;
public static boolean[][] visit;
public static int m;
public static int resh = 0;
public static int[] a;
public static void main(String... args) throws IOException {
// br= new BufferedReader(new FileReader("input.txt"));
// out = new PrintWriter("output.txt");
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
m = nextInt();
a = readIntArray(n);
g = new List[n];
for (int i =0;i<n;i++) {
g[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n-1; i++) {
int x = nextInt();
int y = nextInt();
x--;y--;
g[x].add(y);
g[y].add(x);
}
visited= new boolean[n];
dfs(0,a[0]);
// bfs(0,way);
out.print(resh);
out.close();
}
public static long gcd(long a, long b) {
return b > 0 ? gcd(b, a % b) : a;
}
public static long lcd(long a, long b) {
return a / gcd(a, b) * b;
}
public static void bfs(int v,List<Integer> way)
{
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(v);
while(!queue.isEmpty())
{
int p = queue.poll();
visited[p]=true;
way.add(p);
for (Integer x : g[p]) {
if(!visited[x])
queue.add(x);
}
}
}
public static void dfs2(int v,List<Integer> way)
{
Stack<Integer> queue = new Stack<Integer>();
queue.add(v);
while(!queue.isEmpty())
{
int p = queue.pop();
visited[p]=true;
way.add(p);
for (Integer x : g[p]) {
if(!visited[x])
queue.add(x);
}
}
}
public static void dfs(int v, int currM) {
visited[v] = true;
// if(g[v].size()==0 && currM<=m)
// resh++;
int c=0;
for (int i = 0; i < g[v].size(); i++) {
int p = g[v].get(i);
if (!visited[p]) {
if(a[p]==1)
{
if(currM+1<=m)
dfs(p,currM+1);
}
else
dfs(p,0);
}
else{
c++;
}
}
if(c==g[v].size()&&currM<=m)
resh++;
}
public static void Resheto(int n) {
prime[0] = prime[1] = false;
for (int i = 2; i <= n; ++i)
if (prime[i])
if (i * 1l * i <= n)
for (int j = i * i; j <= n; j += i)
prime[j] = false;
}
public static double len(Point a, Point b) {
return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
public static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public static double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public static long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public static int[] readIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public static void printArray(int[] arr) throws IOException {
for (int anArr : arr)
out.print(anArr + " ");
}
public static int[] shuffleArray(int[] arr) {
Random rnd = new Random();
int n = arr.length;
int temp;
int ind;
while (n > 1) {
ind = rnd.nextInt(n--);
temp = arr[ind];
arr[ind] = arr[n];
arr[n] = temp;
}
return arr;
}
}
class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 28d9be376841dba0b518737f339abb78 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Codeforces580C {
public static int leafCount(ArrayList<ArrayList<Integer>> tree, int rootParent, int root, int numCats, int maxCats, boolean[] hasCat)
{
if(numCats > maxCats)
return 0;
if(root != 0 && tree.get(root).size() == 1)
return 1;
ArrayList<Integer> children = tree.get(root);
int sum = 0;
for(int i = 0; i < children.size(); i++)
{
int child = children.get(i);
if(child == rootParent)
continue;
if(hasCat[child])
sum += leafCount(tree, root, child, numCats + 1, maxCats, hasCat);
else
sum += leafCount(tree, root, child, 0, maxCats, hasCat);
}
return sum;
}
public static void main(String[] args) {
try
{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
boolean[] hasCat = new boolean[n];
st = new StringTokenizer(f.readLine());
for(int i = 0; i < n; i++)
{
if(st.nextToken().equals("1"))
hasCat[i] = true;
}
ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < n; i++)
tree.add(new ArrayList<Integer>());
for(int i = 0; i < n - 1; i++)
{
st = new StringTokenizer(f.readLine());
int parent = Integer.parseInt(st.nextToken()) - 1;
int child = Integer.parseInt(st.nextToken()) - 1;
tree.get(parent).add(child);
tree.get(child).add(parent);
}
if(hasCat[0])
System.out.println(leafCount(tree, -1, 0, 1, m, hasCat));
else
System.out.println(leafCount(tree, -1, 0, 0, m, hasCat));
}
catch(IOException e)
{
System.out.println(e);
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 7c27497657c61eb8e8493fc3e189c5a2 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Main {
public static int n,m,x,y,i,result;
public static boolean[] visited,catPresence;
public static ArrayList<Integer>[] adjacencyList;
public static ArrayList<Integer> leaves;
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
String[] parts=br.readLine().split(" ");
n=Integer.parseInt(parts[0]);
m=Integer.parseInt(parts[1]);
//System.out.println("n:"+n);
//System.out.println("m:"+m);
visited= new boolean[n];
catPresence=new boolean[n];
adjacencyList= new ArrayList[n];
//Arrays.fill(adjacencyList,new ArrayList<Integer>());
parts=br.readLine().split(" ");
for( i=0;i<n;i++){
catPresence[i]=(parts[i]).equals("1");
adjacencyList[i]=new ArrayList<Integer>();
}
for( i=0;i<n-1;i++){
parts=br.readLine().split(" ");
x=Integer.parseInt(parts[0])-1;
y=Integer.parseInt(parts[1])-1;
//if(!adjacencyList[x].contains(y))
adjacencyList[x].add(y);
//if(!adjacencyList[y].contains(x))
adjacencyList[y].add(x);
}
leaves=new ArrayList<Integer>();
for( i=1;i<n;i++){
if(adjacencyList[i].size()==1)
{ leaves.add(i);
//System.out.println("ADDED:"+i);
}
}
depthFirstSearch(0,0);
result=0;
for(Integer I:leaves){
if(visited[I])
result++;
}
System.out.println(result);
br.close();
}
public static void depthFirstSearch(int Vertex, int Cats){
if(!catPresence[Vertex])
Cats=0;
else
Cats++;
if(Cats>m)
return;
visited[Vertex]=true;
for(int c:adjacencyList[Vertex])
if(!visited[c])
depthFirstSearch(c,Cats);
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 457a97c8dc9aaa8b4df5743dcee4ce04 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.*;
public class Solution{
static int count=0;
static void calc(int root,List<List<Integer>> adj,int par,int curr,int tag[],int m){
if(tag[root]==1)
curr++;
else{
if(curr>m)
return;
curr=0;
}
if(root!=0 && adj.get(root).size()==1 && curr<=m){
count++;
//System.out.println(root);
}
Iterator<Integer> it=adj.get(root).iterator();
while(it.hasNext()){
int temp=it.next();
if(temp!=par){
calc(temp,adj,root,curr,tag,m);
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n=in.nextInt(),m=in.nextInt();
int tag[]=new int[n];
List<List<Integer>> adj=new ArrayList<List<Integer>>();
for(int i=0;i<n;i++){
tag[i]=in.nextInt();
adj.add(new ArrayList<Integer>());
}
for(int i=0;i<n-1;i++){
int u=in.nextInt(),v=in.nextInt();
adj.get(u-1).add(v-1);
adj.get(v-1).add(u-1);
}
calc(0,adj,-1,0,tag,m);
System.out.println(count);
in.close();
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 52b2b64ef785f3416a927bfdf8167085 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class CF_580C_KefaAndPark
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
StringBuilder out = new StringBuilder("");
String line, lines[];
int n, m, x, y;
boolean flags[];
lines = in.readLine().trim().split("\\s+");
n = Integer.parseInt(lines[0]);
m = Integer.parseInt(lines[1]);
lines = in.readLine().trim().split("\\s+");
flags = new boolean[n];
ArrayList<Integer> graph[] = new ArrayList[n];
for( int i = 0; i < n; i++ ) graph[i] = new ArrayList<Integer>();
for( int i = 0; i< n; i++ )
{
if ( lines[i].equals("1") ) flags[i] = true;
}
for( int i = 0; i < n-1; i++ )
{
lines = in.readLine().trim().split("\\s+");
x = Integer.parseInt(lines[0])-1;
y = Integer.parseInt(lines[1])-1;
graph[x].add(y);
graph[y].add(x);
}
Queue<Integer> q = new LinkedList<Integer>();
Queue<Integer> cats = new LinkedList<Integer>();
boolean visited[] = new boolean[n];
q.add(0);
cats.add(0);
int node, cat;
int count = 0;
while( !q.isEmpty())
{
node = q.poll();
cat = cats.poll();
//System.out.println(node+" "+cat);
if ( visited[node] ) continue;
if ( flags[node] ) cat++;
else cat = 0;
visited[node] = true;
if ( cat > m ) continue;
if ( graph[node].size() == 1 && node != 0) count++;
for( int i = 0; i < graph[node].size(); i++ )
{
q.add(graph[node].get(i));
cats.add( cat );
}
}
System.out.println(count);
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 457799abfbc84cb8a90338709928e5a7 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main {
static IO io;
static HashSet<Integer> set;
static int ans = 0;
static node[] tree;
static int n , m;
public static void main(String args[]) throws Exception {
io = new IO();
io.init();
//------------------------------------------------
n = io.nextInt();
m = io.nextInt();
tree = new node[n];
for( int i = 0 ; i < n ; ++i ){
int temp = io.nextInt();
if( temp == 1 )
tree[i] = new node(true);
else
tree[i] = new node(false);
}
for( int i = 0 ; i < n-1 ; ++i ){
int a = io.nextInt()-1;
int b = io.nextInt()-1;
tree[a].children.add(b);
tree[b].children.add(a);
}
if( tree[0].hasCat)
tree[0].countInclusive = 1;
for( int i : tree[0].children){
bfs(i,0);
}
System.out.println( ans);
//------------------------------------------------
io.destroy();
}
static void bfs(int cur, int parent){
if( tree[cur].hasCat )
tree[cur].countInclusive = tree[parent].countInclusive + 1;
else tree[cur].countInclusive = 0 ;
if( tree[cur].countInclusive > m) return;
if( tree[cur].children.size() == 1 )
ans++;
else
{
for( int i : tree[cur].children){
if( i != parent){
bfs(i,cur);
}
}
}
}
static class pair implements Comparable<pair>{
int money, factor;
pair( int money,int factor){
this.money = money;
this.factor = factor;
}
public int compareTo( pair p ){
if( money < p.money) return -1;
else if( money > p.money ) return +1;
else if( factor < p.factor ) return -1;
else if( factor > p.factor) return +1;
else return 0;
}
}
static class node {
boolean hasCat;
int countInclusive;
boolean failed;
ArrayList<Integer> children;
node(boolean a){
hasCat = a;
countInclusive = 0 ;
failed = false;
children = new ArrayList<Integer>();
}
}
static long gcd( long a , long b ){
if( a == 0 ) return b;
if( b == 0 )return a;
if( a > b ) return gcd( a%b,b);
else return gcd(a,b%a);
}
static class IO{
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void init() {
try {
reader = new BufferedReader(new InputStreamReader(System.in),8*1024);
writer = new PrintWriter(System.out);
} catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
void destroy() {
writer.close();
System.exit(0);
}
void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
void println(Object... objects) {
print(objects);
writer.println();
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 4674799b6ed1ef153b1236334bfd50a6 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
static int n,m,res=0;
static boolean[] cats;
static ArrayList<Integer>[] adj;
static boolean[] v;
static void dfs(int i,int cnt){
v[i]=true;
if(cnt>m)return;
boolean inside=false;
for(int j=0;j<adj[i].size();j++){
int curr = adj[i].get(j);
if(!v[curr]){
inside=true;
if(cats[curr])
dfs(curr,cnt+1);
else
dfs(curr,0);
}
}
if(!inside && cnt<=m){
res++;
}
}
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String[] in;
in = br.readLine().split(" ");
n = Integer.parseInt(in[0]); m = Integer.parseInt(in[1]);
cats = new boolean[n+1];
adj = new ArrayList[n+1];
v = new boolean[n+1];
adj[0] = new ArrayList<Integer>();
in = br.readLine().split(" ");
for(int i=0;i<n;i++){
adj[i+1]=new ArrayList<Integer>();
if(in[i].charAt(0)=='1')
cats[i+1]=true;
}
for(int i=0;i<n-1;i++){
in = br.readLine().split(" ");
int from = Integer.parseInt(in[0]) , to = Integer.parseInt(in[1]);
adj[from].add(to);
adj[to].add(from);
}
int start = 0;
if(cats[1])start=1;
dfs(1,start);
System.out.println(res);
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | be77abbe177b7cb739c7968db888ec30 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
/**
*
* @author Hasan
*/
public class Main {
/**
* @param args the command line arguments
*/
static ArrayList<Integer> adj[];
static int arr[];
static int n,m;
static int sol=0;
static void dfs(int nd,int p,int curr,int add){
if(arr[nd]==1){
curr++;
} else {
curr=0;
}
if(curr>m){
add=0;
}
boolean ok=true;
for(int i=0;i<adj[nd].size();i++){
int ch=adj[nd].get(i);
if(ch==p)continue;
ok=false;
dfs(ch,nd,curr,add);
}
if(ok){
sol+=add;
}
}
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
n=r.nextInt();
m=r.nextInt();
arr=new int[n+10];
adj=new ArrayList[n+10];
for(int i=1;i<=n;i++){
adj[i]=new ArrayList<Integer>();
}
int a,b;
for(int i=1;i<=n;i++){
arr[i]=r.nextInt();
}
for(int i=1;i<n;i++){
a=r.nextInt();
b=r.nextInt();
adj[a].add(b);
adj[b].add(a);
}
dfs(1,1,0,1);
System.out.println(sol);
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 67783248e59442df9b8531eaadc28aff | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class C {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException
{
int n = nextInt();
int m = nextInt();
int[] cat = new int[n];
ArrayList<Integer>[] g = new ArrayList[n];
for (int i = 0; i < n; i++)
{
cat[i] = nextInt();
g[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++)
{
int a = nextInt() - 1;
int b = nextInt() - 1;
g[a].add(b);
g[b].add(a);
}
Queue<Integer> q = new LinkedList<Integer>();
q.add(0);
q.add(-1);
q.add(cat[0]);
int count = 0;
while (!q.isEmpty())
{
int node = q.poll();
int parent = q.poll();
int catsSoFar = q.poll();
if (catsSoFar > m)
continue;
boolean leaf = true;
for (int child : g[node])
if (child != parent)
{
leaf = false;
if (cat[child] == 0)
{
q.add(child);
q.add(node);
q.add(0);
} else if (catsSoFar + 1 <= m)
{
q.add(child);
q.add(node);
q.add(catsSoFar + 1);
}
}
if(leaf)
count++;
}
System.out.println(count);
}
static BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer tokenizer = null;
static long nextLong() throws IOException
{
return Long.parseLong(nextToken());
}
static double nextDouble() throws IOException
{
return Double.parseDouble(nextToken());
}
static int nextInt() throws IOException
{
return Integer.parseInt(nextToken());
}
static String nextToken() throws IOException
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | bd2d6b0dfb9c540513e78c72e3b30f6f | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | //package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class KefaAndPark
{
static boolean visited[];
static Vertex[] graph;
static int maxCats;
public static void main(String[] args)
{
MyScanner scan = new MyScanner();
int N = scan.nextInt();
maxCats = scan.nextInt();
graph = new Vertex[N+1];
graph[0] = new Vertex(0, false);
for (int i = 1; i <= N; i++) {
graph[i] = new Vertex(i, scan.nextInt()==1);
}
for (int i = 0; i < N-1; i++) {
int x = scan.nextInt();
int y = scan.nextInt();
graph[x].adjacencies.add(y);
graph[y].adjacencies.add(x);
}
visited = new boolean[N+1];
dfs(1, 0);
System.out.println(ways);
}
static int ways = 0;
public static void dfs(int v, int catsSoFar)
{
visited[v] = true;
if (graph[v].hasCat) {
catsSoFar++;
} else {
catsSoFar = 0;
}
if (catsSoFar > maxCats) {
return;
}
if (graph[v].adjacencies.size()==1 && v !=1) {
ways++;
return;
}
for(Integer e: graph[v].adjacencies){
if (!visited[e]) {
dfs(e, catsSoFar);
}
}
}
static class Vertex
{
public int id;
public boolean hasCat;
public ArrayList<Integer> adjacencies;
public Vertex(int argId, boolean hasCat) {
id = argId;
adjacencies = new ArrayList<>();
this.hasCat = hasCat;
}
}
//--------------------------------------------------------
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 | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 9a634cdd09320b655df73a137f164930 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Main
{
int n;
int threshold;
int layer[];
boolean visited[];
ArrayList<ArrayList<Integer>> a;
FastScanner in;
PrintWriter out;
public void solve() throws IOException
{
n = in.nextInt();
threshold = in.nextInt();
a = new ArrayList<ArrayList<Integer>>();
visited = new boolean[n];
layer = new int[n];
for (int i = 0; i < layer.length; i++)
{
layer[i] = in.nextInt();
a.add(new ArrayList<Integer>());
}
for (int i = 0; i < n - 1; i++)
{
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
a.get(from).add(to);
a.get(to).add(from);
}
int count = bfs(0);
out.println(count);
}
public int bfs(int start)
{
int count = 0;
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(start);
visited[start] = true;
while (!queue.isEmpty())
{
start = queue.poll();
boolean isLeaf = true;
ArrayList<Integer> connectedTo = a.get(start);
for (int i = 0; i < connectedTo.size(); i++)
{
int to = connectedTo.get(i);
if ( !visited[to] )
{
isLeaf = false;
if ( layer[start] != 0 && layer[to] != 0 )
{
layer[to] = layer[start] + 1;
if ( layer[to] > threshold )
{
continue;
}
}
queue.add(to);
visited[to] = true;
}
}
if ( isLeaf )
{
count++;
}
}
return count;
}
public void run()
{
try
{
in = new FastScanner();
out = new PrintWriter(System.out, true);
solve();
out.flush();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreTokens())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
}
public static void main(String[] arg)
{
new Main().run();
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 01062a3e96ea4468492d27553176bfcb | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | //package problems;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Vector;
public class Problems{
static int[] a = new int[100001], vis = new int[100001];
static ArrayList<Integer>[] G = new ArrayList[100001];
static int n, m, x, y, cnt;
public static void main (String[] args){
Scanner in = new Scanner (System.in);
n = in.nextInt();
m = in.nextInt();
for (int i = 1; i <= n; i++){
a[i] = in.nextInt();
G[i] = new ArrayList<Integer>();
}
for (int i = 1; i < n; i++){
x = in.nextInt();
y = in.nextInt();
G[x].add(y);
G[y].add(x);
}
Problems P = new Problems();
P.DFS (1);
System.out.println(cnt);
}
void DFS (int v){
vis[v] = 1;
for (int i = 0; i < G[v].size(); i++){
int t = G[v].get(i);
if (vis[t] == 0)
if (a[t] > 0){
if (a[v] + a[t] <= m){
a[t] = a[v] + 1;
DFS (t);
}
} else
DFS (t);
}
if (G[v].size() == 1 && v != 1)
cnt++;
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | e6279e0c155b2d18d7d1584f10f73649 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 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.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.*;
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);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Node[] tree = new Node[n + 1];
int m = in.nextInt();
for (int i = 1; i <= n; i++) {
tree[i] = new Node();
tree[i].isCat = (in.nextInt() == 1);
}
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt();
int b = in.nextInt();
tree[a].neighbors.add(tree[b]);
tree[b].neighbors.add(tree[a]);
}
out.println(solve(tree[1], m, m));
}
public int solve(Node c, int m, int mm) {
if (m == 0 && c.isCat)
return 0;
c.visited = true;
boolean isLeaf = true;
int ans = 0;
if (c.isCat) {
for (Node g : c.neighbors) {
if (!g.visited) {
ans += solve(g, m - 1, mm);
isLeaf = false;
}
}
} else {
for (Node g : c.neighbors) {
if (!g.visited) {
ans += solve(g, mm, mm);
isLeaf = false;
}
}
}
return (isLeaf) ? 1 : ans;
}
}
static class Node {
ArrayList<Node> neighbors = new ArrayList<Node>();
boolean isCat;
boolean visited = false;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer st;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 6f475dfba2d0120e7c9b8b336c07f22d | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class C
{
/**
* Scanner class
*
* @author gouthamvidyapradhan
*/
static class MyScanner {
/**
* Buffered reader
*/
private static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
private static StringTokenizer st;
/**
* Read integer
*
* @return
* @throws Exception
*/
public static int readInt() throws Exception {
try {
if (st != null && st.hasMoreTokens()) {
return parseInt(st.nextToken());
}
String str = br.readLine();
if (str != null && !str.trim().equals("")) {
st = new StringTokenizer(str);
return parseInt(st.nextToken());
}
} catch (IOException e) {
close();
return -1;
}
return -1;
}
/**
* Read integer
*
* @return
* @throws Exception
*/
public static long readLong() throws Exception {
try {
if (st != null && st.hasMoreTokens()) {
return Long.parseLong(st.nextToken());
}
String str = br.readLine();
if (str != null && !str.trim().equals("")) {
st = new StringTokenizer(str);
return Long.parseLong(st.nextToken());
}
} catch (IOException e) {
close();
return -1;
}
return -1;
}
/**
* Read line
* @return
* @throws Exception
*/
public static String readLine() throws Exception
{
return br.readLine();
}
/**
* Parse to integer
* @param in
* @return integer value
*/
public static int parseInt(String in)
{
// Check for a sign.
int num = 0, sign = -1, i = 0;
final int len = in.length( );
final char ch = in.charAt( 0 );
if ( ch == '-' )
sign = 1;
else
num = '0' - ch;
// Build the number.
i+=1;
while ( i < len )
num = num*10 + '0' - in.charAt( i++ );
return sign * num;
}
/**
* Close BufferedReader
*
* @throws Exception
*/
public static void close() throws Exception {
br.close();
}
}
private static int M, N, canVisit; //M rows, N columns
private static PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
private static int[] A;
private static boolean[] done;
private static List<List<Integer>> graph;
/**
* Main method
* @param args
*/
public static void main(String[] args) throws Exception
{
N = MyScanner.readInt();
M = MyScanner.readInt();
graph = new ArrayList<>();
done = new boolean[N + 1];
A = new int[N + 1];
canVisit = 0;
for(int i = 0; i <= N; i++)
graph.add(new ArrayList<Integer>());
for(int i = 1; i <= N; i++)
A[i] = MyScanner.readInt();
for(int i = 0; i < N - 1; i++)
{
int from = MyScanner.readInt();
int to = MyScanner.readInt();
graph.get(from).add(to);
graph.get(to).add(from); // make two way connection
}
dfs(0, 1);
pw.println(canVisit);
pw.flush(); pw.close(); MyScanner.close();
}
/**
* Count possible
* @param catCnt
* @param v
*/
private static void dfs(int catCnt, int v)
{
done[v] = true;
if(A[v] == 1)
catCnt++;
else
catCnt = 0;
if(catCnt > M) return;
List<Integer> children = graph.get(v);
if(children.size() == 1)
{
if(done[children.get(0)])
canVisit++;
}
for(int c : children)
{
if(!done[c])
dfs(catCnt, c);
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 2c7471a704306015903819d0563c4c3d | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class ACMSolution {
static class node{
public int color,con;
public int flag;
public ArrayList<Integer> link;
public node(int color){
this.color = color;
this.con = 0;
link = new ArrayList<Integer>();
flag = 0;
}
}
public static void main(String[] args) throws IOException {
//Scanner in = new Scanner(Paths.get("input.txt"));
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
node[] tree = new node[n+1];
for(int i=1; i<=n; i++){
tree[i] = new node(in.nextInt());
}
for(int i=1;i<=n-1;i++){
int x,y;
x = in.nextInt();
y = in.nextInt();
tree[x].link.add(y);
tree[y].link.add(x);
}
if(tree[1].color == 1)
tree[1].con = 1;
Queue<node> q = new LinkedList<node>();
q.add(tree[1]);
tree[1].flag = 1;
int max = 0;
while(!q.isEmpty()){
node now = q.poll();
int length = now.link.size();
for(int i=0;i<length;i++){
int index = now.link.get(i);
if((tree[index].color == 1 && now.con == m) || tree[index].flag == 1)
continue;
else{
int nowLength = tree[index].link.size();
int flagAdd = 0;
for(int j=0;j<nowLength;j++){
if(tree[tree[index].link.get(j)].flag == 0){
flagAdd = 1;
break;
}
}
if(flagAdd == 0)
max++;
else{
if(tree[index].color == 1)
tree[index].con = now.con + 1;
tree[index].flag = 1;
q.add(tree[index]);
}
}
}
}
System.out.println(max);
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 9be9f2b121a8818f5bc5710e63a601bd | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class ACMSolution {
static class node{
public int color,con;
public int flag;
public ArrayList<Integer> link;
public node(int color){
this.color = color;
this.con = 0;
link = new ArrayList<Integer>();
flag = 0;
}
}
public static void main(String[] args) throws IOException {
//Scanner in = new Scanner(Paths.get("input.txt"));
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
node[] tree = new node[n+1];
for(int i=1; i<=n; i++){
tree[i] = new node(in.nextInt());
}
for(int i=1;i<=n-1;i++){
int x,y;
x = in.nextInt();
y = in.nextInt();
tree[x].link.add(y);
tree[y].link.add(x);
}
if(tree[1].color == 1)
tree[1].con = 1;
Queue<node> q = new LinkedList<node>();
q.add(tree[1]);
tree[1].flag = 1;
int max = 0;
while(!q.isEmpty()){
node now = q.poll();
int length = now.link.size();
for(int i=0;i<length;i++){
int index = now.link.get(i);
if((tree[index].color == 1 && now.con == m) || tree[index].flag == 1)
continue;
else{
int nowLength = tree[index].link.size();
int flagAdd = 0;
for(int j=0;j<nowLength;j++){
if(tree[tree[index].link.get(j)].flag == 0){
flagAdd = 1;
break;
}
}
if(flagAdd == 0)
max++;
else{
if(tree[index].color == 1)
tree[index].con = now.con + 1;
tree[index].flag = 1;
q.add(tree[index]);
}
}
}
}
System.out.println(max);
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 1cbf0c7a154bfb281eff8125a277f5be | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.*;
public class KefaAndPark {
static int count = 0;
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int n = Integer.parseInt(stdIn.next());
int k = Integer.parseInt(stdIn.next());
Vertex[] park = new Vertex[n+1];
for(int i=1;i<=n;i++){
int cat = Integer.parseInt(stdIn.next());
park[i] = new Vertex(i,cat);
}
for(int i=1;i<n;i++){
int v = Integer.parseInt(stdIn.next());
int w = Integer.parseInt(stdIn.next());
park[v].child.add(w);
park[w].child.add(v);
}
dfs(park,-1,1,0,k);
System.out.println(count);
}
public static void dfs(Vertex[] park, int par, int v, int curr, int k){
if(park[v].hasCat==1)
curr++;
else
curr=0;
if(curr>k)
return;
boolean flag = true;
for(int i=0;i<park[v].child.size();i++){
int next = park[v].child.get(i);
if(next!=par){
flag = false;
dfs(park,v,next,curr,k);
}
}
if(flag)
count++;
}
}
class Vertex{
int v;
int hasCat;
ArrayList<Integer> child;
public Vertex(int v, int hasCat){
this.v = v;
this.hasCat = hasCat;
this.child = new ArrayList<Integer>();
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 4ce00ff595ebed63d70571c6e1c39d90 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class KefaAndPark {
static int[] maxConsec, curConsec, visited;
static int ans;
static ArrayList<ArrayList<Integer>> adj;
static ArrayList<ArrayList<Integer>> children;
static int cat[];
static int m;
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
adj = new ArrayList<ArrayList<Integer>>();
children= new ArrayList<ArrayList<Integer>>();
for(int i = 0; i<n; i++){
adj.add(new ArrayList<Integer>());
}
for(int i = 0; i<n; i++){
children.add(new ArrayList<Integer>());
}
cat = new int[n];
st = new StringTokenizer(br.readLine());
for(int i=0; i<n; i++){
cat[i] = Integer.parseInt(st.nextToken());
}
int a, b;
for(int i=0; i<n-1; i++){
st = new StringTokenizer(br.readLine());
a = Integer.parseInt(st.nextToken())-1;
b = Integer.parseInt(st.nextToken())-1;
adj.get(a).add(b);
adj.get(b).add(a);
}
ans = 0;
maxConsec = new int[n];
curConsec = new int[n];
curConsec[0] = maxConsec[0] = cat[0];
visited = new int[n];
Arrays.fill(visited, -1);
dfs(0);
// System.out.println(children.toString());
visit(0);
// for(int i=0; i<n; i++){
// System.out.println(i+" "+maxConsec[i]+" "+curConsec[i]);
// }
System.out.println(ans);
}
public static void dfs(int node){
visited[node] = 1;
ArrayList<Integer> list = adj.get(node);
for(int i=0; i<list.size(); i++){
if(visited[list.get(i)] == -1){
children.get(node).add(list.get(i));
dfs(list.get(i));
}
}
}
public static void visit(int node){
ArrayList<Integer> list = children.get(node);
// System.out.println(list);
if( list.isEmpty()){
// System.out.println(" **** "+node);
if(maxConsec[node]<=m)
ans++;
}
int to;
for(int i=0; i<list.size(); i++){
to = list.get(i);
if( cat[node] == 1 && cat[to]==1)
curConsec[to] = curConsec[node]+1;
else
curConsec[to] = cat[to];
maxConsec[to] = Math.max(maxConsec[node], curConsec[to]);
visit(to);
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 267346349ea87bb3435cefa6d076ba55 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import java.util.Map;
import java.util.List;
public class C321_Div2 {
static Map<Integer, List<Integer>> tree = new HashMap<Integer, List<Integer>>();
static Set<Integer> cats = new HashSet<Integer>();
static int maxCats = 0;
static int counter = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
maxCats = m;
for (int i = 1; i <= n; i++) {
int cat = sc.nextInt();
if (cat > 0) {
cats.add(i);
}
}
for (int i = 0; i < n - 1; i++) {
int source = sc.nextInt();
int target = sc.nextInt();
List<Integer> verteces1;
if (!tree.containsKey(source)) {
verteces1 = new LinkedList<Integer>();
tree.put(source, verteces1);
} else {
verteces1 = tree.get(source);
}
verteces1.add(target);
List<Integer> verteces;
if (!tree.containsKey(target)) {
verteces = new LinkedList<Integer>();
tree.put(target, verteces);
} else {
verteces = tree.get(target);
}
verteces.add(source);
}
if (tree.containsKey(1)) {
traverse(tree, 1, m, -1);
}
System.out.println(counter);
}
private static void traverse(Map<Integer, List<Integer>> tree2, int start, int numCats, int parent) {
if (cats.contains(start)) {
numCats--;
if (numCats < 0) {
return;
}
} else {
numCats = maxCats;
}
List<Integer> neighbours = tree.get(start);
if (neighbours == null || (neighbours.size() == 1 && neighbours.get(0) == parent)) {
if (numCats >= 0) {
counter++;
}
return;
}
for (int neighbour : neighbours) {
if (neighbour != parent) {
traverse(tree2, neighbour, numCats, start);
}
}
}
public static class Vertext {
int num;
int cats = 0;
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | e66fb687b0bd178a4c2d7ecc93500f8c | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes |
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "12 3\n" +
"1 0 1 0 1 1 1 1 0 0 0 0\n" +
"6 7\n" +
"12 1\n" +
"9 7\n" +
"1 4\n" +
"10 7\n" +
"7 1\n" +
"11 8\n" +
"5 1\n" +
"3 7\n" +
"5 8\n" +
"4 2\n";
public static ArrayList<Integer>[] adj;
public static int res;
boolean[] cat;
public static int m;
void solve() {
int n = ni();
m = ni();
cat = new boolean[n + 1];
adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
cat[i] = ni() == 1;
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int p = ni() - 1;
int t = ni() - 1;
adj[p].add(t);
adj[t].add(p);
}
dfs(0, -1, 0);
out.println(res);
}
private void dfs(int cur, int prev, int cnt) {
boolean isLeaf = true;
if (cat[cur]) {
cnt++;
if (cnt > m) {
return;
}
} else {
cnt = 0;
}
for (int i = 0; i < adj[cur].size(); i++) {
int next = adj[cur].get(i);
if (next == prev) {
continue;
}
dfs(next, cur, cnt);
isLeaf = false;
}
if (isLeaf) {
res++;
}
}
void run() throws Exception {
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new C().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 boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj) System.out.println(Arrays.deepToString(o));
}
} | Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | a22c76903301d558b52cb7782b61be49 | train_000.jsonl | 1442939400 | Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go. | 256 megabytes | import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
public class P580C {
private void run() {
int n = nextInt();
int m = nextInt();
Map<Integer, Boolean> vertexes = new HashMap<Integer, Boolean>(n); //true if cat
Map<Integer, Set<Integer>> edges = new HashMap<Integer, Set<Integer>>(n); //true if cat
for (Integer i = 1; i <= n; i++) {
int b = nextInt();
vertexes.put(i, b != 0);
}
for (Integer i = 1; i <= n - 1; i++) {
Integer source = nextInt();
Integer target = nextInt();
if (!edges.containsKey(source) && !source.equals(target)) {
edges.put(source, new HashSet<Integer>());
}
if (!edges.containsKey(target) && !source.equals(target)) {
edges.put(target, new HashSet<Integer>());
}
edges.get(source).add(target);
edges.get(target).add(source);
}
int count = countPaths(vertexes, edges, 1, 0, m, new HashSet<Integer>());
System.out.print(count);
}
private int countPaths(Map<Integer, Boolean> vertexes, Map<Integer, Set<Integer>> edges, Integer currentVertex, int catsCount, int maxCatsCount, HashSet<Integer> visited) {
if (visited.contains(currentVertex)) {
return 0;
}
visited.add(currentVertex);
Set<Integer> vertexEdges = new HashSet<Integer>(edges.get(currentVertex));
vertexEdges.removeAll(visited);
int newCatsCount = vertexes.get(currentVertex).booleanValue() ? catsCount + 1 : 0;
if (vertexEdges == null || vertexEdges.size() == 0) { //leaf
if (newCatsCount > maxCatsCount) {
return 0;
} else {
if (currentVertex.intValue() != 1) {
return 1;
} else {
return 0;
}
}
}
if (newCatsCount > maxCatsCount) {
return 0;
}
int count = 0;
for (Integer nextVertex : vertexEdges) {
count = count + countPaths(vertexes, edges, nextVertex, newCatsCount, maxCatsCount, visited);
}
visited.remove(currentVertex);
return count;
}
public boolean isTriangle(int a, int b, int c) {
return
(a + b > c)
&& (a + c > b)
&& (b + c > a);
}
private char nextChar() {
try {
return (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private char[] incrementWord(char[] input, char maxLetter) {
int currentIndex = input.length - 1;
while (currentIndex >= 0 && input[currentIndex] == maxLetter) {
currentIndex--;
}
if (currentIndex < 0) {
return input;
}
input[currentIndex] = (char) (input[currentIndex] + 1);
for (int i = currentIndex + 1; i < input.length; i++) {
input[i] = 'a';
}
return input;
}
private int getFree(Integer currentFree, Map<Integer, Integer> count) {
while (count.containsKey(currentFree)) {
currentFree = currentFree + 1;
}
return currentFree;
}
private double computeArea(double side1, double side2, double side3) {
double p = (side1 + side2 + side3) / 2d;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
private int greaterThan(List<Integer> indexesP2, Integer j) {
for (int i = 0; i < indexesP2.size(); i++) {
Integer number = indexesP2.get(i);
if (number > j) {
return indexesP2.size() - i;
}
}
return 0;
}
public static void main(String[] args) {
P580C notes = new P580C();
notes.run();
notes.close();
}
private Scanner sc;
private P580C() {
this.sc = new Scanner(System.in);
}
private int[] asInteger(String[] values) {
int[] ret = new int[values.length];
for (int i = 0; i < values.length; i++) {
String val = values[i];
ret[i] = Integer.valueOf(val).intValue();
}
return ret;
}
private String nextLine() {
return sc.nextLine();
}
private int nextInt() {
return sc.nextInt();
}
private String readLine() {
if (sc.hasNextLine()) {
return (sc.nextLine());
} else {
return null;
}
}
private void close() {
try {
sc.close();
} catch (Exception e) {
//log
}
}
}
| Java | ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"] | 2 seconds | ["2", "2"] | NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | Java 7 | standard input | [
"dfs and similar",
"trees",
"graphs"
] | 875e7048b7a254992b9f62b9365fcf9b | The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree. | 1,500 | A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats. | standard output | |
PASSED | 7c882db622d559fbf0cc1c2dc4ce57fb | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Scanner sc=new Scanner(System.in);
int t = sc.nextInt();
while (t > 0) {
long n=sc.nextLong();
long k=sc.nextLong();
int ans=0;
if(n%2==0){
n=n+k*2;
System.out.println(n);
ans=1;
}
while(k>0 && ans==0){
n=n+smallestDivisor(n);
k--;
if(n%2==0){
n=n+2*k;
break;
}
}
if(ans==0)
System.out.println(n);
t--;
}
}
static long smallestDivisor(long n)
{
// if divisible by 2
if (n % 2 == 0)
return 2;
// iterate from 3 to sqrt(n)
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0)
return i;
}
return n;
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | a55da6cacdb54b14f58de38403dc34c7 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
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 int no(int n)
{
if(n>=1 && n<=9)
{
return 1 ;
}
return no(n/10) + 1 ;
}
public static long help(long n)
{
for(long i = 3; i <= n ; i++)
{
if(n% i == 0) return i ;
}
return 2 ;
}
public static long sol(long n , long k )
{
if(k == 1)
{
return help(n) + n ;
}
long ans = sol(help(n) + n , k-1 ) ;
return ans ;
}
public static void main(String[] args)
{
FastReader scn = new FastReader();
int t = scn.nextInt() ;
for( int m = 1; m<= t; m++){
long n,k;
n = scn.nextLong() ;
k = scn.nextLong() ;
StringBuilder sb = new StringBuilder() ;
if(n% 2 == 0)
{
sb.append(n+2*k) ;
}
else{
if( k == 1)
{
sb.append(help(n) + n ) ;
}
else{
long ans = help(n) + n ;
sb.append(ans + 2*(k-1) ) ;
}
}
out.println(sb) ;
}
out.flush() ;
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 8349a3eb2f91e870eb7b5b2cd6e95801 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Cf131 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 Cf131(),"Main",1<<27).start();
}
static class Pair{
int nod;
int ucn;
Pair(int nod,int ucn){
this.nod=nod;
this.ucn=ucn;
}
public static Comparator<Pair> wc = new Comparator<Pair>(){
public int compare(Pair e1,Pair e2){
//reverse order
if (e1.ucn < e2.ucn)
return 1; // 1 for swaping.
else if (e1.ucn > e2.ucn)
return -1;
else{
// if(e1.siz>e2.siz)
// return 1;
// else
// return -1;
return 0;
}
}
};
}
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b,a%b);
}
////recursive BFS
public static int bfsr(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,int[] pre){
b[s]=true;
int p = 0;
int t = a[s].size();
for(int i=0;i<t;i++){
int x = a[s].get(i);
if(!b[x]){
dist[x] = dist[s] + 1;
p+= (bfsr(x,a,dist,b,pre)+1);
}
}
pre[s] = p;
return p;
}
//// iterative BFS
public static int bfs(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,PrintWriter w){
b[s]=true;
int siz = 0;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while(q.size()!=0){
int i=q.poll();
// w.println(" #"+i+"# ");
Iterator<Integer> it =a[i].listIterator();
int z=0;
while(it.hasNext()){
z=it.next();
// w.println("#"+i+" "+z);
if(!b[z]){
// w.println("* "+z+" *");
b[z]=true;
dist[z] = dist[i] + 1;
// w.print("*");
// w.println(i+" "+z);
siz++;
// x.add(z);
// w.println("@ "+x.get(x.size()-1)+" @");
q.add(z);
}
}
}
return siz;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
// int defaultValue=0;
// int[] a = new int[15000003];
// for(int i=2;i<a.length;i++){
// boolean f = true;
// for(int j=2;j<=(int)(double)Math.sqrt(i);j++){
// if(i%j==0){a[i]=j;f = false;break;}
// }
// if(f)a[i] = i;
// }
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int k = sc.nextInt();
int ans = n;
while(k>0){
if(ans%2==0){ans+=(2*k);k=0;break;}
else{
boolean f = true;
for(int j=2;j<=(int)(double)Math.sqrt(ans);j++){
if(ans%j==0){ans+=j;f = false;break;}
}
if(f)ans+=ans;
}
k--;
}
w.println(ans);
}
w.flush();
w.close();
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 82247517dd3c7c0955451c785c8cdb6f | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static PrintWriter out;
static FastReader fr;
// make it false if Multiple test case is not in the question
final static boolean multipleTC = true;
// Global Variables
final static int MOD = (int) 1e9 + 7;
final static double INF = Double.POSITIVE_INFINITY;
final static int MAX = (int) 1e4;
static int TestCase = 1;
final ArrayList<Integer> primes = new ArrayList<>();
// for pre processing if needed
void pre() throws Exception {
boolean[] prime = new boolean[MAX];
primes.add(2);
Arrays.fill(prime, true);
prime[2] = true;
for (int i = 2; i < MAX; i += 2) {
prime[i] = false;
}
for (int i = 3; i < MAX; i += 2) {
if (prime[i]) {
for (int j = i * i; j < MAX; j += i) {
prime[j] = false;
}
}
}
for (int i = 3; i < MAX; i++) {
if (prime[i]) {
primes.add(i);
}
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
// input output handled here
private Object solve() throws Exception {
// code
long n = fr.nl(), k = fr.nl();
long ans = 0;
if ((n & 1) == 1) {
long fn = f(n);
ans = (n + fn) + ((k - 1) * 2);
} else {
ans = n + (k * 2);
}
return ans;
}
private long f(long n) {
long res = n;
for (long i = n; i >= 2; i--) {
if (n % i == 0)
res = i;
}
return res;
}
void run() throws Exception {
// long start_time = System.nanoTime();
try {
fr = new FastReader("in0.txt");
out = new PrintWriter("out0.txt");
} catch (Exception e) {
fr = new FastReader();
out = new PrintWriter(System.out);
}
// pre();
StringBuilder print = new StringBuilder("");
int T = (multipleTC) ? fr.ni() : 1;
for (TestCase = 1; TestCase <= T - 1; TestCase++) {
print.append(solve()).append("\n");
}
print.append(solve());
p(print);
// long end_time = System.nanoTime();
// System.out.printf("Running Time in sec : %2.10f", (double) (end_time -
// start_time) * (double) 1e-9);
out.flush();
out.close();
}
static void p(Object o) {
out.print(o);
}
static void pln(Object o) {
out.println(o);
}
static void psp(Object o) {
out.print(o + " ");
}
static void pnf(Object o) {
out.println(o);
out.flush();
}
static void deb(Object... x) {
System.out.print("#" + TestCase + " = ");
for (int i = 0; i < x.length - 1; i++)
System.out.print(x[i] + " , ");
System.out.println(x[x.length - 1]);
}
public <Type> Type also(Type a, Type b) throws Exception {
return a;
}
class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == ' ')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
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();
}
String n() throws Exception {
return fr.next();
}
String nln() throws Exception {
return fr.readLine().trim();
}
int ni() throws Exception {
return fr.nextInt();
}
long nl() throws Exception {
return fr.nextLong();
}
double nd() throws Exception {
return fr.nextDouble();
}
int[] nextIntArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = fr.nextInt();
}
return a;
}
long[] nextLongArray(int n) throws Exception {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = fr.nextLong();
}
return a;
}
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 8795075de6c6ca493b8a68e76fce5eea | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | // Working program with FastReader
import java.io.*;
import java.util.*;
public class codeforces_1350A
{
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 void solve(FastReader ob){
long n=ob.nextLong(),k=ob.nextLong();
long ans=0;
if(n%2==0){
ans+=n+(k*2);
}
else{
for (int i = 3; i<=n ; i++) {
if(n%i==0){
ans+=(n+i);
break;
}
}
ans+=((k-1)*2);
}
System.out.println(ans);
}
public static void main(String[] args)
{
FastReader ob=new FastReader();
int t=ob.nextInt();
for (int i = 0; i <t ; i++) {
solve(ob);
}
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 79339d7b7255dfd51e647bcc2932b102 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static public class InputIterator{
ArrayList<String> inputLine = new ArrayList<String>(1024);
int index = 0;
int max;
InputIterator(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String read;
try{
read = br.readLine();
}catch(IOException e){
read = null;
}
if(read != null){
inputLine.add(read);
}else{
break;
}
}
max = inputLine.size();
}
public boolean hasNext(){return (index < max);}
public String next(){
if(hasNext()){
String returnStr = inputLine.get(index);
index++;
return returnStr;
}else{
throw new IndexOutOfBoundsException("これ以上入力はないよ。");
}
}
}
static InputIterator ii = new InputIterator();
static void myout(Object t){System.out.println(t);}
static void myerr(Object t){System.err.println(t);}
static String next(){return ii.next();}
static int nextInt(){return Integer.parseInt(next());}
static long nextLong(){return Long.parseLong(next());}
static String[] nextStrArray(){return next().split(" ");}
static ArrayList<Integer> nextIntArray(){
ArrayList<Integer> ret = new ArrayList<Integer>();
String[] input = nextStrArray();
for(int i = 0; i < input.length; i++){
ret.add(Integer.parseInt(input[i]));
}
return ret;
}
static ArrayList<Long> nextLongArray(){
ArrayList<Long> ret = new ArrayList<Long>();
String[] input = nextStrArray();
for(int i = 0; i < input.length; i++){
ret.add(Long.parseLong(input[i]));
}
return ret;
}
static char[] nextCharArray(){return mySplit(next());}
static char[] mySplit(String str){return str.toCharArray();}
static String kaigyoToStr(String[] list){return String.join("\n",list);}
static String kaigyoToStr(ArrayList<String> list){return String.join("\n",list);}
static String hanSpToStr(String[] list){return String.join(" ",list);}
static String hanSpToStr(ArrayList<String> list){return String.join(" ",list);}
public static void main(String[] args){
int t = nextInt();
for(int i = 0; i < t; i++){
ArrayList<Long> tmp = nextLongArray();
long N = tmp.get(0);
long K = tmp.get(1);
LinkedList<Long> list = getDivisorList(N);
long last = list.get(1);
N += last;
K--;
list = getDivisorList(N);
N += list.get(1) * K;
myout(N);
}
}
//Method addition frame start
public static LinkedList<Long> getDivisorList(long val){
LinkedList<Long> list = new LinkedList<Long>();
for(long i = 1; i * i <= val; i++){
if(val % i == 0){
list.add(i);
if(i * i != val){
list.add(val / i);
}
}
}
Collections.sort(list, Comparator.naturalOrder());
return list;
}
static boolean isPrime(long val){
if(val <= 1 || (val != 2 && val % 2 == 0)){
return false;
}else if(val == 2){
return true;
}
double root = Math.floor(Math.sqrt(val));
for(long i = 3; i <= root; i += 2){
if(val % i == 0){
return false;
}
}
return true;
}
//Method addition frame end
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 945406fce4f64754261d192bcb3a5698 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
public class WaterMelon {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int cases = Integer.parseInt(reader.nextLine());
for (int i = 0; i < cases; i++) {
String[] input = reader.nextLine().split(" ");
int n = Integer.parseInt(input[0]);
int k = Integer.parseInt(input[1]);
int divisor=divisor(n);
n =n+divisor+(k-1)*2;
System.out.println(n);
}
}
static int divisor(int in) {
int divisor = 1;
int rest = 0;
if (in % 2 == 0) {
divisor = 2;
} else {
do {
divisor=divisor+2;
rest = in % divisor;
} while (rest != 0);
}
return divisor;
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | a7aab3e4cb1f1734ae1d470a8791cc35 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String test_numS=bf.readLine();
int test_num=Integer.parseInt(test_numS);
while(test_num>0){
String NandK=bf.readLine();
String nk[]=NandK.split(" ");
int n=Integer.parseInt(nk[0]);
int k=Integer.parseInt(nk[1]);
solve(n,k);
test_num--;
}
}
public static void solve(int n,int k){
//long out=n;
while (k>0){
if (n%2==0){
n+=2*k;
k=0;
continue;
}else {
for (int i = 3; i <=n ; i+=2) {
if (n%i==0){
n+=i;
k--;
break;
}
}
}
}
System.out.println(n);
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | d81b1ea6ca137da5912c5a241933b74a | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes |
//1350A-未完成
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Orac_and_Factors {
public static void main(String[] args) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String test_numS=bf.readLine();
int test_num=Integer.parseInt(test_numS);
while(test_num>0){
String NandK=bf.readLine();
String nk[]=NandK.split(" ");
int n=Integer.parseInt(nk[0]);
int k=Integer.parseInt(nk[1]);
solve(n,k);
test_num--;
}
}
public static void solve(int n,int k){
while (k>0){
if (n%2==0){
n+=2*k;//很关键,节省很多时间,当该数位偶数时,直接加上2*k,因为加完2后他仍未偶数加2
k=0;
continue;
}else {
for (int i = 3; i <=n ; i+=2) {//为奇数从3开始除,每次加2
if (n%i==0){
n+=i;
k--;
break;
}
}
}
}
System.out.println(n);
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 63ec102890fe3a9599cf00708eafdeb8 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int t = Integer.parseInt(input.nextLine());
String[] numbers;
for(int i = 0;i < t;i++) {
numbers = input.nextLine().split("\\s");
int n = Integer.parseInt(numbers[0]);
int k = Integer.parseInt(numbers[1]);
int divisor = function(n);
n = n + divisor + (k - 1)*2;
System.out.println(n);
}
}
public static int function(int n) {
for(int i = 2;i <= n;i++) {
if(n % i == 0 ){
return i;
}
}
return -1;
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 7adb38e5b42827449bcd2897d12a0b86 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- >0){
int n = sc.nextInt();
int k = sc.nextInt();
for(int i=2 ; i<=n ; i++){
if(n%i == 0){
n=n+i;
break;
}
}
n=n+2*(k-1);
System.out.println(n);
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | d0c828243410499d7cd6fe9dfeecb380 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class Main {
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 class Words {
String word;
int cost;
public Words(String word) {
this.word = word;
}
}
static class Node {
int key;
int edgeweight;
int height;
public Node(int key, int edgeweight) {
this.key = key;
this.edgeweight = edgeweight;
}
}
static class Graph {
int vertices;
ArrayList<ArrayList<Node>> al;
public Graph(int vertices) {
this.vertices = vertices;
al = new ArrayList<>(vertices);
for (int i = 0; i < vertices; i++) {
al.add(new ArrayList<Node>());
}
}
public static void addEdgeUndirected(ArrayList<ArrayList<Node>> al, int source, int destination, int weight) {
al.get(source).add(new Node(destination, weight));
al.get(destination).add(new Node(destination, weight));
}
/* public static int bfs(ArrayList<ArrayList<Node>> al, int v, int root) {
//here root means the starting vertex for bfs
int count = 1;
boolean[] visited = new boolean[v];
Queue<Integer> q = new LinkedList<>();
visited[root] = true;
q.add(root);
while (!q.isEmpty()) {
int u = q.poll();
for (int i = 0; i < al.get(u).size(); i++) {
if (!visited[al.get(u).get(i).key]) {
visited[al.get(u).get(i).key] = true;
q.add(al.get(u).get(i).key);
count++;
}
}
}
return count;
}*/
public static void bfs(ArrayList<ArrayList<Node>> al, int v, int root) {
//here root means the starting vertex for bfs
boolean[] visited = new boolean[v];
Queue<Integer> q = new LinkedList<>();
visited[root] = true;
q.add(root);
while (!q.isEmpty()) {
int u = q.poll();
System.out.print(u + " ");
for (int i = 0; i < al.get(u).size(); i++) {
if (!visited[al.get(u).get(i).key]) {
visited[al.get(u).get(i).key] = true;
q.add(al.get(u).get(i).key);
}
}
}
}
}
static int countDigit(long n) {
return (int) Math.floor(Math.log10(n) + 1);
}
public static void main(String[] args) throws IOException {
Reader r = new Reader();
int t = r.nextInt();
while (t-- > 0) {
int n = r.nextInt();
int k = r.nextInt();
boolean flag = false;
if(n%2==0){
n+=2*k;
}else{
for(int i=3;i<=n;i+=2){
if(n%i==0){
n+=i;
break;
}
}
flag = true;
}
if(flag) n+=(k-1)*2;
System.out.println(n);
}
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | a437fbccc0931c00cba0d15a68969700 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.Scanner;
public class Factors {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int cases = scanner.nextInt();
for (int c = 1; c <= cases; c++) {
solve();
}
}
private static void solve() {
long n = scanner.nextInt();
long k = scanner.nextInt();
long d = n;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
d = i;
break;
}
}
System.out.println(n + d + (k - 1) * Math.min(2, d));
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 3bd33ca350db9005fc20cf6142f5d660 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | /**
* @author egaeus
* @mail [email protected]
* @veredict
* @url
* @category
* @date
**/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import static java.lang.Integer.parseInt;
public class CFA {
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = parseInt(in.readLine());
for (int t = 0; t < T; t++) {
StringTokenizer st = new StringTokenizer(in.readLine());
int N = parseInt(st.nextToken()), K = parseInt(st.nextToken());
int D = f(N);
while (D > 2) {
N += D;
D = f(N);
K--;
}
System.out.println(N + 2 * K);
}
}
static int f(int a) {
for (int i = 2; i <= Math.sqrt(a); i++)
if (a % i == 0)
return i;
return a;
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 69493e1e7861e1f13277ca95f84b70df | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.Scanner;
public class OracAndFactors {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
int b = a.nextInt();
int [] fin = new int [b];
for(int c = 0; c < b; c++) {
int e = a.nextInt();
int g = a.nextInt();
int d=2;
while(e%d != 0) {
d++;
}
e = e + d + ((g-1)*2);
fin[c] = e;
}
for(int c = 0; c < b; c++) {
System.out.println(fin[c]);
}
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | fce6219f84fa06ba79afb646d71e28c7 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i < t; i++){
int n = sc.nextInt();
int k = sc.nextInt();
int current = 0;
if(n % 2 == 0){
current = k * 2 + n;
} else{
int p = 0;
for(int j = n; j >= 2; j--){
if(n % j == 0){
p = j;
}
}
current = 2*(k-1) + p + n;
} /* else if(current%3 == 0){
current = 2*(k-1) + n + 3;
} else if(current%5 == 0){
current = 2*(k-1)+ n + 5;
} else if(current%7 == 0){
current = 2*(k-1)+ n + 7;
} else{
current = 2*(k-1)+n+n;
} */ //bruh
System.out.println(current);
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 2c018319cc65cbe8bfb417090b5c7e6a | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Main implements Runnable {
boolean multiple = true;
void solve() throws Exception {
long n = sc.nextLong();
long k = sc.nextLong();
if (n % 2 != 0) {
boolean bool = false;
for (long i = 3; i <= sqrt(n); i++) {
//System.out.println(len);
if (n % i == 0) {
n += i;
bool = true;
break;
}
}
if (!bool) {
n += n;
}
k --;
}
n += 2*k;
System.out.println(n);
}
@Override
public void run() {
try
{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
if (multiple)
{
int q = sc.nextInt();
for (int i = 0; i < q; i++)
solve();
}
else
solve();
}
catch (Throwable uncaught)
{
Main.uncaught = uncaught;
}
finally
{
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Main(), "", (1 << 26));
thread.start();
thread.join();
if (Main.uncaught != null) {
throw Main.uncaught;
}
}
static Throwable uncaught; BufferedReader in; FastScanner sc; PrintWriter out;
}
class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in)
{
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 2aa328649cc98cf02db023b6670ec435 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.Scanner;
import java.lang.Math;
public class A1350{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int test_cases = sc.nextInt();
int n,k,res=0,min;
while(test_cases > 0){
n = sc.nextInt();
//System.out.println("N is: " + n);
k = sc.nextInt();
//System.out.println("K is: " + k);
//System.out.println("I is:" + i);
min = min_div(n);
//System.out.println("Min is: " + min);
res = min + n + 2*(k-1);
//System.out.println("Res is: " + res);
n = res;
//System.out.println("N is: " + n);
System.out.println(res);
test_cases--;
}
}
static int min_div(int n){
int sqrt = (int) Math.sqrt(n);
int i;
for(i = 2; i <= sqrt; i++){
if(n % i == 0){
break;
}
}
if(i > sqrt) i = n;
return i;
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 646f4e763a8d759da5dab9260230449e | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | /**
* @author vivek
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
private static void solveTC(int __) {
/* For Google */
// ans.append("Case #").append(__).append(": ");
//code start
int n = scn.nextInt();
int k = scn.nextInt();
if (n%2!=0){
k--;
n+=(smallestFactor(n));
}
print(n+2*k);
//code end
ans.append("\n");
}
private static int smallestFactor(int n) {
for (int i = 2; i <= Math.sqrt(n)+1; i++) {
if (n%i==0){
return i;
}
}
return n;
}
private static int gcd(int i, int j) {
return (j == 0) ? i : gcd(j, i % j);
}
static void print(Object obj) {
ans.append(obj.toString());
}
public static void main(String[] args) {
scn = new Scanner();
ans = new StringBuilder();
int t = scn.nextInt();
// int t = 1;
for (int i = 1; i <= t; i++) {
solveTC(i);
}
System.out.print(ans);
}
static Scanner scn;
static StringBuilder ans;
//Fast Scanner
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
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;
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
Integer[] nextIntegerArray(int n) {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
String[] nextStringArray() {
return nextLine().split(" ");
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = next();
}
return array;
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | ef5db6696992120ba3b66935e483d30c | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
public class Orac
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
while(t-->0)
{
long n=scan.nextInt();
long k=scan.nextInt();
for(int i=2;i<=n;i++)
{
if(n%i==0)
{
n=n+i;
break;
}
}
n=n+2*(k-1);
System.out.println(n);
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 51998996a3fc493da2c74fc8ec19ea05 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class file
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static INPUT sc = new INPUT(br);
static int INF = Integer.MAX_VALUE,NEG_INF = Integer.MIN_VALUE,SEM_INF = INF / 2,count = 0,MOD = 1000000007,ops = 0;
static long MAX_INF = Long.MAX_VALUE;
static BigInteger B = new BigInteger("1");
//static Scanner sc = new Scanner(System.in);
public static void main (String[] args) throws Exception
{
try{
preComp();
int t = sc.getInt(br.readLine());
while(t-- > 0)
{
testCase();
}
out.flush();
}catch(Exception e){
System.out.println("Exception Occured!");
e.printStackTrace();
}
}
public static void testCase() throws Exception
{
int n = sc.nextInt();int k = sc.nextInt();
if(n % 2 == 0)
n += (2 * k);
else{
n += getSmall(n);
n += (2 * (k - 1));
}
writeln(n);
}
public static int getSmall(int n)
{
for(int x = 2;x < n + 1;x++)
if(n % x == 0)
return x;
return n;
}
public static void preComp()
{
}
public static void writeln() throws Exception
{
out.write("\n");
}
public static void write(Object o) throws Exception
{
out.write(String.valueOf(o));
}
public static void writeln(Object o) throws Exception
{
out.write(String.valueOf(o) + "\n");
}
public static void println()
{
System.out.println();
}
public static void print(Object o)
{
System.out.print(String.valueOf(o));
}
public static void println(Object o)
{
System.out.println(String.valueOf(o));
}
}
class INPUT
{
BufferedReader br;
StringTokenizer st;
public INPUT(BufferedReader br)
{
this.br = br;
}
/*RAW INPUTS*/
public String next() throws Exception
{
if(st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws Exception
{
return Integer.parseInt(next());
}
public long nextLong() throws Exception
{
return Long.parseLong(next());
}
public String trimLine() throws Exception
{
try{
return br.readLine().trim();
}catch (Exception e){
System.out.println("Exception Occured: " + e.getMessage());
e.printStackTrace();
return null;
}
}
public String nextLine() throws Exception
{
try{
return br.readLine();
}catch (Exception e){
System.out.println("Exception Occured: " + e.getMessage());
e.printStackTrace();
return null;
}
}
public double nextDouble() throws Exception
{
return Double.parseDouble(next());
}
public float nextFloat() throws Exception
{
return Float.parseFloat(next());
}
public int [] getIntArray( String s)
{
String input[] = s.split(" ");
int res[] = new int[input.length];
for(int x = 0;x < res.length;x++)
res[x] = getInt(input[x]);
return res;
}
public long [] getLongArray( String s)
{
String input[] = s.split(" ");
long res[] = new long[input.length];
for(int x = 0;x < res.length;x++)
res[x] = getLong(input[x]);
return res;
}
public double [] getDoubleArray( String s)
{
String input[] = s.split(" ");
double res[] = new double[input.length];
for(int x = 0;x < res.length;x++)
res[x] = getDouble(input[x]);
return res;
}
public int[][] getIntMatrix(String s,int r,int c)
{
int i = 0;int mat[][] = new int[r][c];
String st[] = s.split(" ");
for(int x = 0;x < r;x++)
for(int y =0 ;y < c;y++)
mat[x][y] = Integer.parseInt(st[i++]);
return mat;
}
public long[][] getlongMatrix(String s,int r,int c)
{
int i = 0;long mat[][] = new long[r][c];
String st[] = s.split(" ");
for(int x = 0;x < r;x++)
for(int y =0 ;y < c;y++)
mat[x][y] = Long.parseLong(st[i++]);
return mat;
}
public int getInt(String s)
{
return Integer.parseInt(s);
}
public long getLong(String s)
{
return Long.parseLong(s);
}
public float getFloat(String s)
{
return Float.parseFloat(s);
}
public double getDouble(String s)
{
return Double.parseDouble(s);
}
}
| Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 894a6bf902449b4b76a8d9221a6ee232 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.util.Scanner;
// Working program with FastReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Solution {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader s=new FastReader();
int q=s.nextInt();
while(q-->0)
{
int num=s.nextInt();
int operations=s.nextInt();
if(num%2==0)
{
System.out.println(num+2*(operations));
}
else{
int fact=0;
for(fact=2;fact<=num;fact++)
{
if(num%fact==0) break;
}
System.out.println(num+fact+2*(operations-1));
}
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 87a9102337b9ff0d8296230deb28a72d | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.io.*;
import java.util.*;
public class GFG {
static int div(int n){
int a=(int) Math.sqrt(n);
for(int i=2;i<=a;i++){
if(n%i==0){
return i;
}
}
return n;
}
public static void main (String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
for(int l=0;l<t;l++){
int n;
int k;
String[] input=br.readLine().split(" ");
n=Integer.parseInt(input[0]);
k=Integer.parseInt(input[1]);
int divisor=div(n);
n=n+divisor;
n=n+(k-1)*2;
System.out.println(n);
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | b735a0fca07ea4069b25ca35a9ef7713 | train_000.jsonl | 1589286900 | Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times. | 256 megabytes | import java.util.*;
import java.io.*;
public class HelloWorld{
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 fn (long n){
if (n%2 == 0){
return 2;
}else{
for (int i = 3;i*i<=n;i=i+2){
if (n%i ==0){
return i;
}
}
}
return n;
}
public static void main(String []args) throws java.lang.Exception{
Reader sc = new Reader();
int test = sc.nextInt();
while (test>0){
long n = sc.nextLong();
long k = sc.nextLong();
long ans = 0;
if (n%2 ==0){
n = n+2;
}else{
n = fn(n)+n;
}
n += (k-1)*2;
System.out.println(n);
test--;
}
}
} | Java | ["3\n5 1\n8 2\n3 4"] | 2 seconds | ["10\n12\n12"] | NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$. | Java 11 | standard input | [
"math"
] | 9fd9bc0a037b2948d60ac2bd5d57740f | The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$. | 900 | Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac. | standard output | |
PASSED | 5c9de8e016f33a510115d0341cd0f366 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.io.*;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.*;
public class Solu {
static StringBuffer str = new StringBuffer();
static InputReader in = new InputReader(System.in);
static int mm=1000000007;
public static void main(String[] args) {
int i,j,it,t;
int n=in.nextInt();
long a[]=new long[n];
long hk=0;
long kj=0;
for(i=0;i<n;i++){
a[i]=in.nextLong();
hk+=a[i];
}
int k=in.nextInt();
long b[]=new long[k];
for(i=0;i<k;i++){
b[i]=in.nextLong();
kj+=b[i];
}
long ss1=a[0];
long ss2=b[0];
int x=1;
int y=1;
ArrayList<Long> z=new ArrayList<>();
ArrayList<Long> w=new ArrayList<>();
while(x<n && y<k){
if(ss1==ss2 &&ss1!=0){
z.add(ss1);
w.add(ss2);
ss1=ss2=0;
}
else{
if(ss1>ss2){
ss2+=b[y];
y+=1;
}else{
ss1+=a[x];
x+=1;
}
}
if(x>=n || y>=k)
break;
}
if(x<n){
long kl=0;
for(i=x;i<n;i++){
kl+=a[i];
}
ss1+=kl;
}
if(y<k){
long kl=0;
for(i=y;i<k;i++){
kl+=b[i];
}
ss2+=kl;
}
if(ss1==ss2 &&ss1!=0){
z.add(ss1);
w.add(ss2);
ss1=ss2=0;
}
long gg=0;
long hh=0;
for(i=0;i<z.size();i++){
gg+=z.get(i);
}
for(i=0;i<w.size();i++){
hh+=w.get(i);
}
if(gg!=hh|| z.size()!=w.size() || gg!=hk || hh!=kj){
System.out.println(-1);
}else{
System.out.println(z.size());
}
}
static long gcd(long a, long b){
return (b==0)?a:gcd(b,a%b);
}
static int gcdi(int a, int b){
return (b==0)?a:gcdi(b,a%b);
}
public static void ap(String st){
str.append(st);
}
public static void pn() {
System.out.println(str);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new UnknownError();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0) {
read();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | c828a7af20e73c9d4caed2ad1ccceb51 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.util.Scanner;
public class D_50{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] A = new long[n];
for (int i = 0 ; i < n ; i++) A[i] = sc.nextLong();
int m = sc.nextInt();
long[] B = new long[m];
for (int i = 0 ; i< m ; i++) B[i] = sc.nextInt();
int A_idx = 0; int B_idx = 0;
int counter= 0;
long first = A[A_idx]; long second = B[B_idx];
while(A_idx<n && B_idx<m){
if (first == second){
if (A_idx==n-1 || B_idx == m-1){
counter++;
A_idx++;
B_idx++;
break;
}
else{
counter++;
A_idx++; first = A[A_idx];
B_idx++; second = B[B_idx];
}
}
else if(first < second){
A_idx++;
if (A_idx<n)
first += A[A_idx];
else
break;
}
else if(second < first)
{
B_idx++;
if (B_idx < m)
second += B[B_idx];
else
break;
}
}
if (A_idx==n && B_idx==m)
System.out.println(counter);
else
System.out.println(-1);
}
} | Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 7c89228d35a6b980849eef4a924f87e3 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | /*
javac d.java && java d
*/
import java.io.*;
import java.util.*;
public class d {
public static void main(String[] args) { new d(); }
FS in = new FS();
PrintWriter out = new PrintWriter(System.out);
int n, m;
int[] a, b;
long[] sa, sb;
d() {
n = in.nextInt();
a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
m = in.nextInt();
b = new int[m];
for (int i = 0; i < m; i++)
b[i] = in.nextInt();
boolean imp = false;
int p = 0, q = 0, l = 0;
long s = 0, t = 0;
while (p < n && q < m) {
s = a[p];
t = b[q];
if (s == t) {
l++;
p++;
q++;
}
else {
int np = p + 1;
int nq = q + 1;
while (np <= n && nq <= m && s != t) {
if (s < t && np < n) s += a[np++];
else if (nq < m) t += b[nq++];
else break;
}
imp |= s != t;
p = np;
q = nq;
l++;
}
}
imp |= ((p == n) ^ (q == m));
if (imp) out.println(-1);
else out.println(l);
out.close();
}
int abs(int x) { return x < 0 ? -x : x; }
long abs(long x) { return x < 0 ? -x : x; }
double abs(double x) { return x < 0 ? -x : x; }
int min(int x, int y) { return x < y ? x : y; }
int max(int x, int y) { return x > y ? x : y; }
long min(long x, long y) { return x < y ? x : y; }
long max(long x, long y) { return x > y ? x : y; }
double min(double x, double y) { return x < y ? x : y; }
double max(double x, double y) { return x > y ? x : y; }
int gcd(int x, int y) { while (y > 0) { x = y^(x^(y = x)); y %= x; } return x; }
long gcd(long x, long y) { while (y > 0) { x = y^(x^(y = x)); y %= x; } return x; }
long lcm(int x, int y) { return ((long) x / gcd(x, y)) * y; }
long lcm(long x, long y) { return (x / gcd(x, y)) * y; }
void sort(int[] arr) {
int sz = arr.length, j;
Random r = new Random();
for (int i = 0; i < sz; i++) {
j = r.nextInt(i + 1);
arr[i] = arr[j]^(arr[i]^(arr[j] = arr[i]));
} Arrays.sort(arr);
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (Exception e) {}
} return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
}
}
| Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 5030536d286e2a14830fbd200a4b6830 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
int n1 = in.nextInt();
int[] a = new int[n1];
for (int i=0;i<n1;i++) a[i] = in.nextInt();
int n2 = in.nextInt();
int[] b = new int[n2];
for (int i=0;i<n2;i++) b[i] = in.nextInt();
Task tsk = new Task();
System.out.println(tsk.solve(a, b));
}
static class Task{
public int solve(int[] a, int[] b){
int cnt = 0;
int p1 = 1, p2 = 1;
long s1 = a[0], s2 = b[0];
while (p1 < a.length || p2 < b.length) {
if (s1 < s2) {
if (p1 == a.length) break;
s1 += a[p1++];
}
else if (s1 > s2) {
if (p2 == b.length) break;
s2 += b[p2++];
}
else {
if (s1 != 0) cnt++;
if (p1 < a.length) s1 += a[p1++];
if (p2 < b.length) s2 += b[p2++];
}
}
return p1 == a.length && p2 == b.length && s1 == s2? cnt + (s1 > 0?1:0): -1;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 768fdc6302eb83347007ec14bc665c84 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.nextInt();
long[]a = new long[n];
for (int i =0;i<n;i++)
a[i]=in.nextLong();
int m = in.nextInt();
long[]b = new long[m];
for (int i =0;i<m;i++)
b[i]=in.nextLong();
boolean check= true;
int p0=0;
int p1=0;
long sum1=0;
long sum2=0;
long length1=n;
long length2=m;
while (p0<n||p1<m)
{
if (sum1==0)
{
sum1+=(long)a[p0];
sum2+=(long)b[p1];
p0++;
p1++;
continue;
}
if (sum1>sum2)
{
if (p1>=m)
{
check=false;
break;
}
sum2+=(long)b[p1];
p1++;
length2--;
}
else if (sum1<sum2)
{
if (p0>=n)
{
check=false;
break;
}
sum1+=(long)a[p0];
p0++;
length1--;
}
else if (sum1==sum2)
{
if ((p0>=n&&p1<m)||(p0<n&&p1>=m))
{
check=false;
break;
}
sum1=(long)a[p0];
sum2=(long)b[p1];
p0++;
p1++;
}
}
out.printLine(length1!=length2||!check||sum1!=sum2?-1:length1);
out.flush();
}
}
class pair implements Comparable
{
int key;
int value;
public pair(Object key, Object value) {
this.key = (int)key;
this.value=(int)value;
}
@Override
public int compareTo(Object o) {
pair temp =(pair)o;
return key-temp.key;
}
}
class Graph {
int n;
ArrayList<Integer>[] adjList;
public Graph(int n) {
this.n = n;
adjList = new ArrayList[n];
for (int i = 0; i < n; i++)
adjList[i] = new ArrayList<>();
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
} | Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 3c70b3d9a3f26858e731d7a6ec43a3d0 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.util.*;
import java.io.*;
public class d {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
}
int m = in.nextInt();
int[] b = new int[m];
for (int i = 0; i < m; ++i) {
b[i] = in.nextInt();
}
int ai = 0, bi = 0;
int result = 0;
long aSum = 0, bSum = 0;
while (ai < n && bi < m) {
++result;
aSum = a[ai++];
bSum = b[bi++];
while (aSum != bSum) {
if (aSum < bSum && ai < n) {
aSum += a[ai++];
} else if (aSum > bSum && bi < m) {
bSum += b[bi++];
} else {
break;
}
}
}
if (ai < n) {
for (int i = ai; i < n; ++i) {
aSum += a[ai];
}
}
if (bi < m) {
for (int i = bi; i < m; ++i) {
bSum += b[bi];
}
}
if (aSum != bSum) {
result = -1;
}
out.println(result);
out.flush();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 678adcf4adfd414d75c05f7400537129 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces1036D {
public static void main(String[] args) {
MyScanner scanner = new MyScanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
int m = scanner.nextInt();
int[] b = new int[m];
for(int i = 0; i < m; i++) {
b[i] = scanner.nextInt();
}
int i = 0;
int j = 0;
long sumA = a[0];
long sumB = b[0];
int ans = 0;
while(i < n && j < m) {
if(sumA == sumB) {
ans++;
i++;
j++;
if(i < n) {
sumA = a[i];
}
if(j < m) {
sumB = b[j];
}
}
else if(sumA < sumB) {
i++;
if(i < n) {
sumA += a[i];
}
}
else {
j++;
if(j < m) {
sumB += b[j];
}
}
}
if(i < n || j < m) {
ans = -1;
}
System.out.println(ans);
}
}
class MyScanner {
private BufferedReader reader;
private StringTokenizer tokens;
public MyScanner(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
}
public String next() {
while(tokens == null || !tokens.hasMoreElements()) {
try {
tokens = new StringTokenizer(reader.readLine());
} catch(IOException error) {
error.printStackTrace();
}
}
return tokens.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
} | Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 91925fb0ef81ce23be7c78474dc51878 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static ArrayList<ArrayList<Integer>> list;
static HashSet<Integer> hs;
static ArrayList<Integer> tmp;
//int n=Integer.parseInt(br.readLine());
//int n=Integer.parseInt(st.nextToken());
//StringTokenizer st = new StringTokenizer(br.readLine());
public static void main (String[] args) throws java.lang.Exception
{
int n=Integer.parseInt(br.readLine());
long A[] = new long[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
A[i] = Long.parseLong(st.nextToken());
int m=Integer.parseInt(br.readLine());
long B[] = new long[m];
st = new StringTokenizer(br.readLine());
for(int i=0;i<m;i++)
B[i] = Long.parseLong(st.nextToken());
long sA=0,sB=0;
for(int i=0;i<n;i++)
sA+=A[i];
for(int i=0;i<m;i++)
sB+=B[i];
if(sA!=sB)
System.out.println("-1");
else
{
long tA=0,tB=0,c=0;
int i=0,j=0;
while(i<n && j<m)
{
tA+=A[i++];
tB+=B[j++];
if(tA==tB)
{
c++;
tA=tB=0;
}
else
{
while(tA!=tB)
{
if(tA<tB)
{
tA+=A[i++];
}
else
{
tB+=B[j++];
}
}
c++;
tA=tB=0;
}
}
System.out.println(c);
}
}
}
| Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 1923cedb887666fd45d85d024526ead0 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.HashMap;
import java.util.PriorityQueue;
public class templ implements Runnable {
class pair
{
int v,val;
pair(int f,int s)
{
v=f;
val=s;
}
}
public static int M=1000000007;
static int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
void merge1(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i]<=R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void sort1(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort1(arr, l, m);
sort1(arr , m+1, r);
merge1(arr, l, m, r);
}
}
void merge3(int arr[],int arr1[],int arr2[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
int L2[]=new int[n1];
int R2[]=new int[n2];
//long L3[]=new long[n1];
//long R3[]=new long[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
L2[i]=arr2[l+i];
//L3[i]=arr3[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
R2[j]=arr2[m+1+j];
//R3[j]=arr3[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
//arr3[k]=L3[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
//arr3[k]=R3[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
//arr3[k]=L3[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
//arr3[k]=R3[j];
j++;
k++;
}
}
void sort3(int arr[],int arr1[],int arr2[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort3(arr,arr1,arr2, l, m);
sort3(arr ,arr1,arr2, m+1, r);
merge3(arr,arr1,arr2,l, m, r);
}
}
void merge2(int arr[],int arr1[],int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
j++;
k++;
}
}
void sort2(int arr[],int arr1[],int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort2(arr,arr1, l, m);
sort2(arr ,arr1, m+1, r);
merge2(arr,arr1,l, m, r);
}
}
void merge4(int arr[],int arr1[],int arr2[],int arr3[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
int L2[]=new int[n1];
int R2[]=new int[n2];
int L3[]=new int[n1];
int R3[]=new int[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
L2[i]=arr2[l+i];
L3[i]=arr3[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
R2[j]=arr2[m+1+j];
R3[j]=arr3[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
arr3[k]=L3[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
arr3[k]=R3[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
arr3[k]=L3[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
arr3[k]=R3[j];
j++;
k++;
}
}
void sort4(int arr[],int arr1[],int arr2[],int arr3[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort4(arr,arr1,arr2,arr3, l, m);
sort4(arr ,arr1,arr2,arr3, m+1, r);
merge4(arr,arr1,arr2,arr3,l, m, r);
}
}
public int justsmall(int a[],int l,int r,int x)
{
int p=-1;
while(l<=r)
{
int mid=(l+r)/2;
if(a[mid]<=x)
{
p=mid;
l=mid+1;
}
else
r=mid-1;
}
return p;
}
public int justlarge(int a[],int l,int r,int x)
{
int p=0;
while(l<=r)
{
int mid=(l+r)/2;
if(a[mid]<x)
{
l=mid+1;
}
else
{
p=mid;
r = mid - 1;
}
}
return p;
}
long gcd(long x,long y)
{
if(x%y==0)
return y;
else
return(gcd(y,x%y));
}
int fact(int n)
{
int ans=1;
for(int i=1;i<=n;i++)
ans*=i;
return ans;
}
long bintoint(String s)
{
long a=0;
int l=s.length();
int k=0;
for(int i=l-1;i>=0;i--)
{
char c=s.charAt(i);
if(c=='1')
{
a=a+(long)Math.pow(2,k);
}
k++;
}
return a;
}
String inttobin(long x)
{
String s="";
while(x!=0)
{
long k=x%2;
if(k==1)
s="1"+s;
else
s="0"+s;
x=x/2;
}
return s;
}
public static void main(String args[])throws Exception
{
new Thread(null,new templ(),"templ",1<<26).start();
}
public void run() {
try {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=in.ni();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=in.ni();
int m=in.ni();
int b[]=new int[m];
for(int i=0;i<m;i++)
b[i]=in.ni();
int i=0,j=0;
int x=0;
long sum1=0,sum2=0;
int l=0;
while(i<n&&j<m)
{
sum1=a[i];
sum2=b[j];
i++;
j++;
while(sum1!=sum2)
{
if(i==n&&j==m)
break;
if(sum1<sum2)
{
if(i==n)
break;
sum1=sum1+a[i];
i++;
}
if(sum2<sum1)
{
if(j==m)
break;
sum2=sum2+b[j];
j++;
}
}
if(sum1==sum2)
{
l++;
}
if(i==n||j==m)
break;
}
if(i==n&&j==m&&sum1==sum2&&l!=0)
out.println(l);
else
out.println("-1");
out.close();
}
catch(Exception e){
return;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
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 nl() {
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] = ni();
}
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\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 999df59e00d064d39bb28bbadbd1c5e4 | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt();
long[] an = new long[n+1];
for(int i=1 ;i<=n ;i++) an[i] = in.nextLong();
int m = in.nextInt();
long[] am = new long[m+1];
for(int i=1 ;i<=m ;i++) am[i] = in.nextLong();
int i=n,j=m;
int ans=0;
while(i!=0 && j!=0){
if(an[i]<am[j]){
an[i-1]+=an[i];
i--;
ans++;
}else if(an[i]>am[j]){
am[j-1]+=am[j];
j--;
}else{
i--;
j--;
}
}
System.out.println((an[i]==0 && am[j]==0 ) ? (n-ans) : -1);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | 4925a0c2d7fc86fc5601ce962407d72c | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 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 dhairya
*/
public class test {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
D solver = new D();
solver.solve(1, in, out);
out.close();
}
static class D {
public void solve(int testNumber,InputReader in, OutputWriter out) {
int n = in.nextInt();
long a[] = new long[n];
for (int i = 0; i < n; i++) {
long t = in.nextLong();
if (i == 0)
a[i] = t;
else
a[i] = a[i - 1] + t;
}
int m = in.nextInt();
long b[] = new long[m];
for (int i = 0; i < m; i++) {
long t = in.nextLong();
if (i == 0)
b[i] = t;
else
b[i] = b[i - 1] + t;
}
int i=0;
int j=0;
int ans=0;
while(i<n && j<m){
if(a[i]==b[j]){
ans++;
i++;
j++;
}
else if(a[i]<b[j]){
i++;
}
else{
j++;
}
}
if(a[n-1]==b[m-1]){
out.println(ans);
}
else{
out.println(-1);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
} | Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | b545f819bf01790e17ef7b92303ba0cc | train_000.jsonl | 1536330900 | Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal. | 256 megabytes | // package Practice2.CF1036;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class CF1036D {
public static void main(String[] args) throws Exception{
Reader s = new Reader(/*System.in*/);
int n = s.nextInt();
// int[] arr = new int[n];
ArrayList<Integer> arr = new ArrayList<>();
// int[] brr = new int[m];
ArrayList<Integer> brr = new ArrayList<>();
long sum = 0;
for (int i = 0; i < n; i++) {
arr.add(s.nextInt());
sum += arr.get(i);
}
int m = s.nextInt();
for (int i = 0; i < m; i++) {
brr.add(s.nextInt());
sum -= brr.get(i);
}
if (sum != 0) {
System.out.println(-1);
return;
}
int ans = 0;
int i = 0;
int j = 0;
while (i < n && j < m) {
long sum1 = arr.get(i++);
long sum2 = brr.get(j++);
while (sum1 != sum2) {
if (sum1 < sum2) {
sum1 += arr.get(i++);
} else {
sum2 += brr.get(j++);
}
}
ans++;
}
System.out.println(ans);
// int count = arr.in
}
private 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();
}
}
} | Java | ["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"] | 1 second | ["3", "-1", "3"] | null | Java 8 | standard input | [
"two pointers",
"greedy"
] | 8c36ab13ca1a4155cf97d0803aba11a3 | The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ — the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ — elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ — the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$. | 1,600 | Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1". | standard output | |
PASSED | ead86b68f32ee79216bf480ccdfbbad2 | train_000.jsonl | 1332516600 | A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need. | 256 megabytes | import java.util.List;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author codeKNIGHT
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n=in.nextInt(),i,k=in.nextInt();
ArrayList<Integer> a=new ArrayList<Integer>();
//int a[]=new int[n+1];
for(i=0;i<n;i++)
a.add(in.nextInt());
Collections.sort(a);
int pos=(n+1)/2,c=1;
if(a.get(pos-1)==k)
{
out.println(0);
return;
}
a.add(k);
Collections.sort(a);
n++;
pos=(n+1)/2;
if(a.get(pos-1)>=k)
{
int d=(n+1)/2,z=-1;
for(i=0;i<n;i++)
{
if(a.get(i)==k)
z=i;
}
pos=z+1;
while (d!=pos)
{
pos++;
n++;
d=(n+1)/2;
c++;
}
}
else
{
int d=(n+1)/2,z=n;
for(i=n-1;i>=0;i--)
if(a.get(i)==k)
z=i;
pos=z+1;
while (d!=pos)
{
n++;
d=(n+1)/2;
c++;
}
}
out.println(c);
}
}
| Java | ["3 10\n10 20 30", "3 4\n1 2 3"] | 2 seconds | ["1", "4"] | NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4. | Java 7 | standard input | [
"sortings",
"greedy",
"math"
] | 1a73bda2b9c2038d6ddf39918b90da61 | The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different. | 1,500 | Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.