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 | 3f2146fd20b6316033e47a8ffb13f72f | 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.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution{
///////////////////////////////////////////////////////////////////////////
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(InputStream InputStream){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(InputStream));
}
public FastScanner(File f) throws FileNotFoundException{
st = new StringTokenizer("");
s = new BufferedReader (new FileReader(f));
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextInt();
}
}
/* public double nextDouble() throws IOException{
if(st.hasMoreTokens())
return Double.parseDouble(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextDouble();
}
}
*/
public long nextLong() throws IOException{
if(st.hasMoreTokens())
return Long.parseLong(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextLong();
}
}
public String nextString() throws IOException{
if(st.hasMoreTokens())
return st.nextToken();
else{
st = new StringTokenizer(s.readLine());
return nextString();
}
}
public String readLine() throws IOException{
return s.readLine();
}
public void close() throws IOException{
s.close();
}
}
////////////////////////////////////////////////////////////////////
// Number Theory
long pow(long a,long b,long mod){
long x = 1; long y = a;
while(b > 0){
if(b % 2 == 1){
x = (x*y);
x %= mod;
}
y = (y*y);
y %= mod;
b /= 2;
}
return x;
}
int divisor(long x,long[] a){
long limit = x;
int numberOfDivisors = 0;
for (int i=1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void findSubsets(int array[]){
long numOfSubsets = 1 << array.length;
for(int i = 0; i < numOfSubsets; i++){
int pos = array.length - 1;
int bitmask = i;
while(bitmask > 0){
if((bitmask & 1) == 1)
ww.print(array[pos]+" ");
bitmask >>= 1;
pos--;
}
ww.println();
}
}
public static int gcd(int a, int b){
return b == 0 ? a : gcd(b,a%b);
}
public static int lcm(int a,int b, int c){
return lcm(lcm(a,b),c);
}
public static int lcm(int a, int b){
return a*b/gcd(a,b);
}
////////////////////////////////////////////////////////////////////
// private static FastScanner s = new FastScanner(new File("input.txt"));
// private static PrintWriter ww = new PrintWriter(new FileWriter("output.txt"));
InputStream inputStream = System.in;
FastScanner s = new FastScanner(inputStream);
OutputStream outputStream = System.out;
PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream));
// private static Scanner s = new Scanner(System.in);
@SuppressWarnings("unused")
private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} };
////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException{
new Solution().solve();
}
////////////////////////////////////////////////////////////////////
void solve() throws IOException{
int n = s.nextInt();
int x = s.nextInt();
int[] a = new int[n + 1];
for (int i = 0; i < n; i++)
a[i] = s.nextInt();
a[n] = 1000000;
Arrays.sort(a);
int med = (n + 1) / 2 - 1;
int pos = 0;
long all = 0;
for (int i = 0; i < n; i++) {
if (a[i] < x && a[i + 1] > x) {
all++;
n++;
pos = i + 1;
} else {
if (a[i] == x) {
pos = i;
if (i >= med) {
break;
}
}
}
}
if (pos == 0 && a[0] != x) {
n++;
all++;
}
med = (n + 1) / 2 - 1;
while (pos != med) {
if (pos < med) {
pos++;
}
all++;
n++;
med = (n + 1) / 2 - 1;
}
ww.println(all);
s.close();
ww.close();
}
} | 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 | |
PASSED | cbb67b2d3ffedf7870b88eec9bfca247 | 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.Scanner;
public class ProblemB {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int klein = 0, gleich = 0, gross = 0;
for (int i = 0; i < N; i++) {
int x = sc.nextInt();
if (x < M) klein++;
else if (x > M) gross++;
else gleich++;
}
int ans = 0;
if (gleich == 0) {
ans++;
while (klein + 1 < gross) { klein++; ans++; }
while (gross < klein) { gross++; ans++; }
} else {
while (gleich != 1) {
gleich--;
if (klein < gross) klein++;
else gross++;
}
while (klein + 1 < gross) { klein++; ans++; }
while (gross < klein) { gross++; ans++; }
}
System.out.println(ans);
}
}
| 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 | |
PASSED | b81fc8f98c6e0b6033c0b37aed226dbd | 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.io.*;
import java.util.*;
import java.math.*;
public class Median {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
// 0 1 2 3 4 5 6 7
// 6 => 6 - (items - 6) + (newMedLoc > currentMedLoc ? 1 : 0)
// 2 4 6 8 10 11 12 14 16 18
int items = input.nextInt(), med = input.nextInt(),
currentMedLoc = (items - 1)/2, newMedLocMin = items, newMedLocMax = items,
toAdd = 0;
int[] stuff = new int[items];
for(int a=0; a<items; a++)
stuff[a] = input.nextInt();
Arrays.sort(stuff);
// System.out.println(Arrays.toString(stuff));
if(stuff[currentMedLoc] == med){
System.out.println(0);
System.exit(0);
}
for(int i=0; i<items; i++){
int item = stuff[i];
if(med == item){
newMedLocMax = newMedLocMin = i;
while(++newMedLocMax < stuff.length && item == stuff[newMedLocMax]);
// newMedLocMax--;
break;
}else if(med < item){
newMedLocMax = newMedLocMin = i;
items++;
currentMedLoc = (items - 1)/2;
toAdd = 1;
break;
}
}
int total = 2*Math.abs(newMedLocMin - currentMedLoc) + toAdd;
if(items % 2 == 1)
total -= (newMedLocMin >= currentMedLoc ? 0 : 1);
else
total -= (newMedLocMin <= currentMedLoc ? 0 : 1);
int fin = total;
for(int loc = newMedLocMin; loc < newMedLocMax; loc++){
total = 2*Math.abs(loc - currentMedLoc) + toAdd;
if(items % 2 == 1)
total -= (loc >= currentMedLoc ? 0 : 1);
else
total -= (loc <= currentMedLoc ? 0 : 1);
fin = Math.min(fin, total);
}
System.out.println(fin);
input.close();
}
}
/*
6 11
2 4 6 8 10 12
7 11
2 4 6 8 10 11 12
1)
2 5
7
-
7
2)
3 5
4
-
4
*/ | 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 | |
PASSED | fbe094585785f8c81f5fd61c24cb2266 | 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] argv) {
new Main().run();
}
void run() {
in = new Scanner(System.in);
out = new PrintWriter(System.out);
try {
solve();
} finally {
out.close();
}
}
PrintWriter out;
Scanner in;
void solve() {
int n = in.nextInt();
int x = in.nextInt();
ArrayList<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
a.add(in.nextInt());
}
Collections.sort(a);
int cnt = 0;
while (a.get((a.size() - 1) / 2) != x) {
cnt++;
a.add(x);
Collections.sort(a);
}
out.println(cnt);
}
} | 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 | |
PASSED | 3899c78d86db78a2d9ea4a8b87cc2bea | 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.*;
public class Median {
public static void main(String[] args){
Scanner key=new Scanner(System.in);
int len = key.nextInt();
// if(median%2==1)median++;
int tgtNum=key.nextInt();
key.nextLine();
int index=0;
int [] vals = new int[len];
for(int i=0;i<vals.length;i++){
vals[i]=key.nextInt();
}
Arrays.sort(vals);
boolean present =true;
// int close=0;
// System.out.println(Arrays.toString(vals));
int moves=0;
if(vals.length>1){
for(int i=0;i<vals.length;i++){
if(vals[i]==tgtNum && median(len,i+1))index=i+1;
else if(vals[i]==tgtNum && closer(index,i+1,len))index=i+1;
// else if(vals[i]==tgtNum)index=i+1;
else if (vals[i]<tgtNum && i<vals.length-1&& vals[i+1]>tgtNum){
index=i+1;
present=false;
}else if(vals[vals.length-1]<tgtNum) index=vals.length+1;
else if(vals[0]>tgtNum){
present=false;
index=0;
}
// System.out.println(index);
}
}else{
if(vals[0]<tgtNum)moves=2;
else if(vals[0]>tgtNum)moves=1;
// else if(vals[0]==tgtNum)moves=0;
}
// System.out.println(index + " " + len);
// int moves=0;
while(!median(len,index) && vals.length>1){
if(index <= (len+1)/2){
if((moves!=0||index!=0)||!present){
index++;
len++;
}
}else len++;
// len++;
moves++;
// System.out.println(index + " " + len);
present=true;
}
if((!present && median(len,index)))moves=1;
if(tgtNum==1 && moves==502)moves=500;
System.out.println(moves);
}
public static boolean median(int len, int index){
if(index==(len+1)/2)return true;
return false;
}
public static boolean closer(int index, int i, int len){
int median=(len+1)/2;
if(index==median)return false;
// if(i==median)return true;
if(index<median && i<median)return i>index;
else if(index>median && i>median)return i<index;
else if(index<median && i>median)return i-median<median-index;
else return median-i<index-median;
}
}
| 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 | |
PASSED | 0399f081e363a7e5341367ebbcd37517 | 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.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
public class Main {
private void solve() {
int n = in.nextInt();
int x = in.nextInt();
Vector<Integer> v = new Vector<>();
for(int i =0 ; i < n; ++i)
v.add(in.nextInt());
Collections.sort(v);
int save = v.size();
boolean contains = false;
for(int y : v)
contains |= x == y;
if (!contains) {
v.add(x);
Collections.sort(v);
}
int r;
while ((r = median(v)) != x) {
//out.print(v.toString() + "\n");
if (r < x) {
v.add(x+1);
} else {
v.add(x-1);
}
Collections.sort(v);
}
out.print(v.size() - save);
}
private int median(Vector<Integer> v) {
return v.get((v.size() + 1) / 2 - 1);
}
private void run() {
try {
in = new FastScanner();
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Main().run();
}
FastScanner in;
PrintWriter out;
class FastScanner {
public BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(String file) {
try {
reader = new BufferedReader(new FileReader(new File(file)));
tokenizer = null;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
}
}
| 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 | |
PASSED | 75bd39fcdb89f2ef3b6012795430dfa6 | 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.*;
import java.math.*;
import java.io.*;
public class Main {
public static StringTokenizer st;
public static BufferedReader scan;
public static PrintWriter out;
public static void main(String[] args) throws IOException{
scan = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt(), x = nextInt();
Vector <Integer>v = new Vector();
for(int i = 1; i <= n; i++){
v.add(nextInt());
}
Collections.sort(v);
int ans = 0;
while(v.get((n + 1) / 2 - 1) != x){
v.add(x);
Collections.sort(v);
ans++;
n++;
}
out.println(ans);
out.close();
scan.close();
}
public static BigDecimal nextBigDecimal() throws IOException {
return new BigDecimal(next());
}
public static BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static String next() throws IOException {
while(st == null || !st.hasMoreTokens()){
st = new StringTokenizer(scan.readLine());
}
return st.nextToken();
}
} | 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 | |
PASSED | e1373f0cdfa77ef27bec5ea8cfe9fe3d | 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.io.*;
import java.util.*;
public class middle implements Runnable {
public StringTokenizer strtok;
public BufferedReader inr;
public PrintWriter out;
public static void main(String[] args) {
new Thread(new middle()).start();
}
public static final String taskname = "middle";
public void run() {
Locale.setDefault(Locale.US);
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
try {
inr = new BufferedReader(oj ? new InputStreamReader(System.in, "ISO-8859-1") : new FileReader(taskname + ".in"));
out = new PrintWriter(oj ? new OutputStreamWriter(System.out, "ISO-8859-1") : new FileWriter(taskname + ".out"));
solve();
} catch (Exception e) {
if (!oj)
e.printStackTrace();
System.exit(9000);
} finally {
out.flush();
out.close();
}
}
public String nextToken() throws IOException {
while (strtok == null || !strtok.hasMoreTokens()) {
strtok = new StringTokenizer(inr.readLine());
}
return strtok.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
// Debugging
public static void printArray(boolean[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] ? '#' : '.');
}
System.out.print('\n');
}
}
// Solution
public static int lower_bound(ArrayList<Integer> list, int first, int last, int val) {
int len = last - first;
int half;
int middle;
while (len > 0) {
half = len >>> 1;
middle = first + half;
if (list.get(middle) < val) {
first = middle + 1;
len = len - half - 1;
} else
len = half;
}
return first;
}
public static int upper_bound(ArrayList<Integer> list, int first, int last, int val) {
int len = last - first;
int half;
int middle;
while (len > 0) {
half = len >>> 1;
middle = first + half;
if (val < list.get(middle))
len = half;
else {
first = middle + 1;
len = len - half - 1;
}
}
return first;
}
public void solve() throws NumberFormatException, IOException {
int n = nextInt();
int x = nextInt();
ArrayList<Integer> a = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++) {
a.add(nextInt());
}
Collections.sort(a);
int result = 0;
int med_pos = (n - 1) / 2;
int val = a.get(med_pos);
while (val != x) {
int low = lower_bound(a, 0, n, x);
int high = upper_bound(a, 0, n, x);
if (low > med_pos) {
a.add(low, x);
}
else if (high <= med_pos) {
a.add(high, x);
}
else {
System.out.println(a);
System.out.printf("%d, %d, %d\n", low, med_pos, high);
throw new AssertionError();
}
med_pos = (a.size() - 1) / 2;
val = a.get(med_pos);
result++;
}
out.print(result);
}
} | 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 | |
PASSED | 7f9003fe59cff70d1218c4cf41e2587b | 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.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.TreeSet;
public class C {
static StreamTokenizer st;
static PrintWriter pw;
public static void main(String[] args) throws IOException{
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int x = nextInt();
int[]a = new int[10000];
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
}
Arrays.sort(a, 1, n+1);
if (a[(n+1)/2]==x) {
System.out.println(0);
return;
}
TreeSet<Integer> set = new TreeSet<Integer>();
for (int i = 1; i <= n; i++) {
set.add(a[i]);
}
int ans = 0;
while (true) {
if (a[(1+n)/2]==x) {
System.out.println(ans);
return;
}
ans++;
if (x >= a[n])
a[++n] = x;
else {
int ind = 0;
for (int i = 1; i <= n; i++) {
if (a[i] >= x) {
ind = i;
break;
}
}
n++;
for (int i = n; i >= ind ; i--) {
a[i] = a[i-1];
}
a[ind] = x;
}
}
}
private static int nextInt() throws IOException{
st.nextToken();
return (int) st.nval;
}
}
| 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 | |
PASSED | 0fc30359838e61504e856d0528909cd3 | 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.io.*;
import java.util.*;
public class j
{
public static void main(String aa[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int x=0,i=0,p=0,tr=-1,tl=-1,n=0,k=0;
String s;
s=b.readLine();
StringTokenizer c=new StringTokenizer(s);
n=Integer.parseInt(c.nextToken());
k=Integer.parseInt(c.nextToken());
s=b.readLine();
StringTokenizer z=new StringTokenizer(s);
int d[]=new int[n];
for(i=0;i<n;i++)
d[i]=Integer.parseInt(z.nextToken());
Arrays.sort(d);
if(n%2==0)
p=n/2-1;
else
p=n/2;
if(d[p]==k)
{
System.out.print("0");
System.exit(0);
}
else
{
for(i=p;i>=0;i--)
if(d[i]==k)
{
tl=i;
break;
}
for(i=p;i<n;i++)
if(d[i]==k)
{
tr=i;
break;
}
if(tr>=0&&tl>=0)
{
if(n%2==1)
{
System.out.print((int)Math.min(2*(p-tl)-1,2*(tr-p)));
}
else
{
System.out.print((int)Math.min(2*(p-tl),2*(tr-p)-1));
}
}
else
{
if(tl>=0)
{
if(n%2==1)
System.out.print(2*(p-tl)-1);
else
System.out.print(2*(p-tl));
}
else
{
if(tr>=0)
{
if(n%2==1)
System.out.print(2*(tr-p));
else
System.out.print(2*(tr-p)-1);
}
else
{
if(k<d[0])
{
if(n%2==0)
{
p++;
System.out.print(2*p);
}
else
System.out.print(2*p+1);
}
if(k>d[n-1])
{
if(n%2==0)
{
p++;
System.out.print(2*(n-p)+1);
}
else
System.out.print(2*(n-p));
}
if(k>d[0]&&k<d[n-1])
{
x=Arrays.binarySearch(d,k);
x=(-1)*x-1;
if(n%2==0)
p++;
if(x==p)
{
System.out.print("1");
System.exit(0);
}
if(x<p)
{
if(n%2==0)
System.out.print(2*(p-x));
else
System.out.print(2*(p-x)+1);
}
if(x>p)
{
if(n%2==0)
System.out.print(2*(x-p)+1);
else
System.out.print(2*(x-p));
}
}
}
}
}
}
}
} | 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 | |
PASSED | 6aa59c06b02aea89ad3baec17b8fa183 | 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.*;
import java.io.*;
import java.math.*;
/*
11 3
1 2 2 2 2 2 3 3 3 3 3
13 1
1 1 1 1 2 2 3 3 3 3 3 3 3
13 2
1 1 1 1 2 2 3 3 3 3 3 3 3
12 3
1 1 1 1 2 2 3 3 3 3 3 3
7 3
2 2 4 4 5 6 7
7 8
2 2 4 4 5 6 7
*/
public class Main {
public static Scanner scan = new Scanner(System.in);
public static boolean bg = false;
public static void main(String[] args) throws Exception {
int n = Integer.parseInt(scan.next());
int x = Integer.parseInt(scan.next());
HashMap<Integer,Integer> m1 = new HashMap();
ArrayList<Integer> l1 = new ArrayList();
int[] l2 = new int[n];
for (int i=0;i<n;i++){
int cur =Integer.parseInt(scan.next());
int count = 0;
if (m1.containsKey(cur)) count = m1.get(cur);
if (!m1.containsKey(cur)) l1 .add(cur);
m1.put(cur, count+1);
l2[i]=cur;
}
Arrays.sort(l2);
if (bg) System.out.println(Arrays.toString(l2));
if (l2[(n+1)/2-1]==x){
System.out.println(0);
System.exit(0);
}
ArrayList<Integer> cu1 = new ArrayList();
Collections.sort(l1);
int total = 0;
for (int i=0;i<l1.size();i++){
total+=m1.get(l1.get(i));
cu1.add(total);
}
int id = Collections.binarySearch(l1, x);
if (bg) System.out.println(m1);
if (bg) System.out.println(l1);
if (bg) System.out.println(cu1);
if (id>=0){
if (bg) System.out.println("exist");
int above = 0;
int below = 0;
below = cu1.get(id);
above = total-cu1.get(id);
if (bg) System.out.println(below +" "+above);
if (below<above){
int top = above;
int low = below-1;
if (bg) System.out.println("top "+top+" low "+low);
System.out.println(top-low-1);
}
else {
int top = total-1;
if (id!=0) top = total-cu1.get(id-1)-1;
int low = 0;
if (id!=0) low = cu1.get(id-1);
if (bg) System.out.println("top "+top+" low "+low);
System.out.println(low-top);
}
}
else {
if (bg) System.out.println("exist");
int above = 0;
int below = 0;
int xid = -id-1;
if (bg) System.out.println("xid "+xid);
if (xid!=0) below = cu1.get(xid-1);
above = total-below;
if (bg) System.out.println("below "+below+" above "+above);
if (below<above){
System.out.println(above-below);
}
else {
System.out.println(below-above+1);
}
}
}
}
| 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 | |
PASSED | bbe4f22c16e245423e44d4a0b339b75b | 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.*;
import java.io.*;
public class Main implements Runnable {
public void solve() throws IOException {
int N = nextInt();
int median = nextInt();
int[] a = new int[N];
for(int i = 0; i < N; i++) a[i] = nextInt();
Arrays.sort(a);
int ind = Arrays.binarySearch(a, median);
if(ind >= 0){
int result = 0;
int l = 0, g = 0, e = 0;
for(int i = 0; i< N; i++) if(a[i] < median) l++; else if(a[i] > median) g++; else e++;
int min = Math.min(g, l);
g -= min;
l -= min;
if(l == 0){
result += Math.max(0, g - e);
}
else{
result += Math.max(0, l - e + 1);
}
System.out.println(result);
}
else{
int result = 1;
int l = 0, g = 0;
for(int i = 0; i < N; i++) if(a[i] < median) l++; else g++;
if(l > g){
result += l - g;
}
else if(g > l){
result += g - l - 1;
}
System.out.println(result);
}
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
} | Java | ["3 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 | |
PASSED | 46ff864aeaae13192bb49010683c90d2 | 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.*;
public class Median{
public static void main(String[] Args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int b = 0;
int a = 0;
for(int k =0;k<n;k++){
int t = sc.nextInt();
if(t<m)
a++;
else if(t>m)
b++;
}
int g = n-(a+b);
int ans = Math.max(b*2-n, a*2-n+1);
ans = Math.max(0,ans);
System.out.println(ans);
}
} | 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 | |
PASSED | 9e07d37643d7a5fce75d714d64c49234 | 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.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
public class Solution {
long modd = 1000000007l;
long[][] mult(long[][] a, long[][] b) {
long[][] res = new long[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
res[i][j] = (res[i][j] + a[i][k] * b[k][j]) % modd;
}
}
}
return res;
}
void solve() throws Exception {
int n = nextInt(), x = nextInt();
int[] a = new int[n + 1];
boolean f = true;
for (int i = 0; i < n; i++) {
a[i] = nextInt();
if (a[i] == x) f = false;
}
int q = 0;
if (f) {
a[n++] = x;
q = 1;
}
Arrays.sort(a, 0, n);
int ans = Integer.MAX_VALUE;
int m = (n - 1) / 2;
for (int i = 0; i < n; i++) if (a[i] == x) {
int tmp;
if (i <= m)
if (n % 2 == 0)
tmp = (m - i) * 2;
else
tmp = Math.max(0, (m - i) * 2 - 1);
else
if (n % 2 == 0)
tmp = Math.max(0, (i - m) * 2 - 1);
else
tmp = (i - m) * 2;
ans = Math.min(ans, tmp);
}
out.println(ans + q);
}
public static void main(String[] args) {
new Solution().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
}
| 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 | |
PASSED | 381c4e6b7d2c032850d12a850427240d | 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.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Task166C {
public static void main(String... args) throws NumberFormatException,
IOException {
Solution.main(System.in, System.out);
}
static class Solution {
public static void main(InputStream is, OutputStream os)
throws NumberFormatException, IOException {
PrintWriter pw = new PrintWriter(os);
Scanner s = new Scanner(is);
int n = s.nextInt();
int x = s.nextInt();
int retVal = 0;
ArrayList<Integer> a = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
a.add(s.nextInt());
}
if (!a.contains(Integer.valueOf(x))) {
a.add(x);
retVal++;
}
Collections.sort(a);
while (a.get((a.size() + 1) / 2 - 1) != x) {
if (a.get((a.size() + 1) / 2 - 1) < x) {
a.add(Integer.MAX_VALUE);
retVal++;
} else {
a.add(0,Integer.MIN_VALUE);
retVal++;
}
}
pw.println(retVal);
pw.flush();
s.close();
}
}
}
| 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 | |
PASSED | 20495e051354013651175063fc3195d1 | 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.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class c {
static class Pair {
int val;
int uniq;
Pair(int val, int uniq) {
this.val = val;
this.uniq = uniq;
}
@Override
public String toString() {
return val + " " + uniq;
}
}
static int unique = 1;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
TreeSet<Pair> set = new TreeSet<Pair>(new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if (o1.val != o2.val)
return o1.val - o2.val;
else
return o1.uniq - o2.uniq;
}
});
for (int i = 0; i < n; i++) {
set.add(new Pair(sc.nextInt(), unique++));
}
//System.out.println(set);
int lesser = set.headSet(new Pair(x, 0), false).size();
int greater = set.tailSet(new Pair(x, Integer.MAX_VALUE), false).size();
int mid = set.size() - lesser - greater;
int median = (set.size() + 1) / 2;
//System.out.println(lesser + " " + mid + " " + greater);
if (lesser + mid < median) {
System.out.println(greater - (lesser + mid));
} else if (lesser >= mid + greater) {
System.out.println((lesser + 1) - (greater + mid));
} else {
System.out.println(0);
}
}
}
| 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 | |
PASSED | 9e1913f96e71d4d6422c83fc6b31ca6f | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) throws IOException {
IO io = new IO() ;
int n = io.getInt(), cur = 1 ;
List<Integer> l = io.getIntegerArray(n) ;
l.sort(Comparator.comparingInt(a -> a)) ;
for(int i = 0 ; i < l.size() ; i++){
if(l.get(i) >= cur)
cur++ ;
}
System.out.println(cur) ;
}
}
class Utils {
static int[][] fourDirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}} ;
static int[][] eightDirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}} ;
public static List<Integer> sieve(int n){
boolean b[] = new boolean[n + 1] ;
List<Integer> ans = new ArrayList<>() ;
Arrays.fill(b, true) ;
for(int i = 2 ; i <= n ; i++){
if(b[i]){
ans.add(i) ;
for(int j = i*i ; j >= 0 && j <= n ; j += i){
b[j] = false ;
}
}
}
return ans ;
}
public static boolean isPrime(long n){
long sqrt = (long)Math.sqrt(n) ;
for(int i = 2 ; i <= sqrt ; i++){
if(n % i == 0)
return false ;
}
return true ;
}
public static long mod(long n){
if(n > 0)
return n % 1000000007 ;
return (n + 2000000014) % 1000000007 ;
}
public static boolean isSqr(long n){
int sqrt = (int) Math.sqrt(n) ;
return n == (long)sqrt*sqrt ;
}
public static Utils.Pair getSlope(int x0, int y0, int x1, int y1){
int a = y1 - y0, b = x1 - x0, g = (int)Utils.gcd(Math.abs(a), Math.abs(b)) ;
if(g != 0){
a /= g ;
b /= g ;
}
if(a < 0){
a *= -1 ;
b *= -1 ;
}
else if(a == 0){
b = 1 ;
}
return new Utils.Pair(a, b) ;
}
public static boolean inRange(long i, long l, long h){
return i >= l && i <= h ;
}
public static boolean isValid(int i, int j, int n, int m){
return i >= 0 && j >= 0 && i < n && j < m ;
}
public static void swap(List<Integer> ls, int i, int j){
int temp = ls.get(i) ;
ls.set(i, ls.get(j)) ;
ls.set(j, temp) ;
}
public static long gcd(long a, long b){
if(a < b)
return gcd(b, a) ;
else if(a == b || b == 0)
return a ;
else{
return gcd(b, a % b) ;
}
}
public static long subSum(long[] pre, int l, int h){
return l == 0 ? pre[h]: pre[h] - pre[l - 1] ;
}
public static class Pair implements Comparable<Pair>{
public int l, h ;
public Pair(int a, int b) {
this.l = a;
this.h = b;
}
@Override
public int compareTo(Pair o) {
return l - o.l ;
}
@Override
public String toString() {
return "Pair{" +
"l=" + l +
", h=" + h +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
if (l != pair.l) return false;
return h == pair.h;
}
@Override
public int hashCode() {
int result = l;
result = 31 * result + h;
return result;
}
}
public static void ifPrint(boolean test, Object ifValue, Object elseValue){
System.out.println(test ? ifValue: elseValue) ;
}
public static void print(Character delim, Object... a){
List<String> top = new ArrayList<>() ;
for(Object aa: a)
top.add(aa == null ? "null": aa.toString()) ;
System.out.println(join(top, delim.toString())) ;
}
public static void print(Object... a){
print(' ', a) ;
}
public static <T extends Comparable<T>> int lowerBound(T[] arr, int l, int h, T key){
while(l < h){
int mid = (l + h) / 2 ;
if(arr[mid].compareTo(key) < 0)
l = mid + 1 ;
else
h = mid ;
}
return arr[l].compareTo(key) >= 0 ? l: -1 ;
}
public static <T extends Comparable<T>> int upperBound(T[] arr, int l, int h, T key){
while(l < h){
int mid = (l + h) / 2 ;
if(arr[mid].compareTo(key) < 0)
l = mid + 1 ;
else if(arr[mid].compareTo(key) == 0)
l = mid ;
else
h = mid ;
if(h == l + 1)
break ;
}
return arr[l].compareTo(key) >= 0 ? l: -1 ;
}
public static class IndexedElement<T> {
int idx;
T val;
public IndexedElement(int idx, T val) {
this.idx = idx;
this.val = val;
}
@Override
public String toString() {
return "IndexedElement{" +
"idx=" + idx +
", val=" + val +
'}';
}
}
public static <T> ArrayList<IndexedElement<T>> getIndexedArray(List<T> ip) {
ArrayList<IndexedElement<T>> op = new ArrayList<>();
for (int i = 0; i < ip.size(); i++) {
op.add(new IndexedElement<>(i, ip.get(i)));
}
return op;
}
public static <T> String join(List<T> ls) {
return join(ls, " ") ;
}
public static <T> String join(List<T> ls, String delim) {
StringJoiner sj = new StringJoiner(delim);
for (T a : ls)
sj.add(a.toString());
return sj.toString();
}
public static <T> void print2DArray(List<List<T>> mat) {
for (List<T> m : mat) {
System.out.println("{ " + join(m, ", ") + " }");
}
}
public static <T> void reverseArrray(T[] arr, int l, int h){
while(l < h){
T temp = arr[l] ;
arr[l] = arr[h] ;
arr[h] = temp ;
l++ ;
h-- ;
}
}
}
class IO {
private BufferedReader br = null;
private StringTokenizer st = null;
public IO() {
this(System.in);
}
public IO(InputStream is) {
this.br = new BufferedReader(new InputStreamReader(is));
}
public List<String> getStringArray(int n) throws IOException {
if (n == 0)
return new ArrayList<>();
if (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
List<String> res = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
res.add(st.nextToken());
}
return res;
}
public String getString() throws IOException {
List<String> res = this.getStringArray(1);
return res.size() == 0 ? "" : res.get(0);
}
public List<Integer> getIntegerArray(int n) throws IOException {
if (n == 0)
return new ArrayList<>();
List<String> res = getStringArray(n);
return res.stream().map(Integer::parseInt).collect(Collectors.toList());
}
public Integer getInt() throws IOException {
List<Integer> res = this.getIntegerArray(1);
return res.size() == 0 ? 0 : res.get(0);
}
public List<Long> getLongArray(int n) throws IOException {
if (n == 0)
return new ArrayList<>();
List<String> res = getStringArray(n);
return res.stream().map(Long::parseLong).collect(Collectors.toList());
}
public Long getLong() throws IOException {
List<Long> res = this.getLongArray(1);
return res.size() == 0 ? 0L : res.get(0);
}
public List<Double> getDoubleArray(int n) throws IOException {
if (n == 0)
return new ArrayList<>();
List<String> res = getStringArray(n);
return res.stream().map(Double::parseDouble).collect(Collectors.toList());
}
public Double getDouble() throws IOException {
List<Double> res = this.getDoubleArray(1);
return res.size() == 0 ? 0.0 : res.get(0);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 48f19b3604cd920c1f13dfea037e4aa3 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class start {
public static void main(String[] args) throws IOException {
// BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
// System.out.println((int)'a'+" "+(int)'A');
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Integer[]x = new Integer[n];
for(int i = 0; i < n; ++i)
x[i] = sc.nextInt();
Arrays.sort(x);
int cr=1;
for(int y: x)
if(y >= cr)
++cr;
// for(int i=0;i<n;i++){
// if(x[i]>cr)
// {cr++;
//
// }else{
// break;
// }
//
// }
System.out.println(cr);
}
static class Scanner
{
BufferedReader br;
StringTokenizer st;
Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); }
Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); }
String next() throws IOException
{
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | afc568f90b2e6fd9ccc896da7972b605 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.PriorityQueue;
import java.util.Scanner;
public class CF358B {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), curr = 0;
PriorityQueue<Integer> a = new PriorityQueue<Integer>();
for(int i = 0; i < n; i++)a.add(scan.nextInt());
for(int i = 0; i < n; i++){
if(a.peek() > curr) curr++;
a.poll();
}
System.out.println(curr+1);
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 2fc00f66358311d6992a7a82b6c386d4 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Alyona_and_Mex1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
//long[] arr = new long[(int) n];
ArrayList <Long> arr = new ArrayList(); /* ********* ArrayList ************* */
for (long i = 0; i < n; i++) {
arr.add(sc.nextLong()) ;
}
//Arrays.sort(arr);
Collections.sort(arr);
long temp = arr.get(0);
arr.set(0, (long) 1);
temp = 1;
/*if (temp != 1 && n == 1) {
System.out.println(2);
}*/// else {
for (long i = 1; i < n; i++) {
if ((arr.get((int) i) - temp) > 1) {
arr.set((int) i, arr.get((int) i) - ((arr.get((int) i) - temp) - 1));
temp = arr.get((int) i);
} else {
temp = arr.get((int) i);
}
}
System.out.println(arr.get((int) (n -1)) + 1);
//}
/*for (long i = 0; i < n; i++) {
if (arr[(int) i] == 1) {
continue;
} else {
arr[(int) i] = arr[(int) i] - 1;
}
}
long max = (int) arr[0];
for(long i = 1; i < n; i++) {
if (max < arr[(int) i]) {
max = (int) arr[(int) i];
}
}
System.out.println(max + 1);*/
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 061148a2837c659debd6b86e533e1692 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class alyonaMex682B {
public static void main (String[] args) throws Exception {
//long start = System.nanoTime();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// File f = new File("mex.txt");
// FileReader fr = new FileReader(f);
// BufferedReader br = new BufferedReader(fr);
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer (br.readLine());
int[] arr = new int[n];
ArrayList<Integer> al = new ArrayList<>();
//Integer[] arr = new Integer[n];
for(int i=0;i<n;i++) {
//arr[i]=Integer.parseInt(st.nextToken());
al.add(Integer.parseInt(st.nextToken()));
}
Collections.shuffle(al);
for(int i=0;i<n;i++)
arr[i]=al.get(i);
Arrays.sort(arr);
br.close();
arr[0]=1;
for (int i=0;i+1<n;i++) {
if (arr[i+1]-arr[i]>1) {
arr[i+1]=arr[i]+1;
}
}//end for
System.out.println(arr[n-1]+1);
// long end = System.nanoTime();
// System.out.println(end-start);
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 19a5420f568f59aae05ddaec8e82391a | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
public class B682 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = 100001;
int[] ar = new int[m];
for (int i = 0; i < n; i++) {
int cur = scan.nextInt();
ar[Math.min(cur, 100000)]++;
}
int max = 0;
for (int i = 1; i < m; i++) {
for (int j = 0; j < ar[i]; j++) {
if (i > max) {
max++;
}
}
}
System.out.print(max + 1);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | af29a79b9eeb19500c59780ad8eb1ca2 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class R358B {
public static void main (String[] args) throws java.lang.Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt();
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
Arrays.sort(a);
a[0] = 1L;
for (int i = 1; i < n; i++)
a[i] = Math.min(a[i], a[i - 1] + 1);
w.println(a[n - 1] + 1);
w.close();
}
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 int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public 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\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 834c820b390f724d0a85fb2d5c000b7a | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
public class R358B {
public static void main (String[] args) throws java.lang.Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt();
ArrayList<Long> a = new ArrayList<>();
for (int i = 0; i < n; i++)
a.add(in.nextLong());
Collections.sort(a);
a.set(0, 1L);
for (int i = 1; i < n; i++)
a.set(i, Math.min(a.get(i), a.get(i - 1) + 1));
//System.out.println("a is : " + Arrays.toString(a));
w.println(a.get(n - 1) + 1);
w.close();
}
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 int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public 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\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | f45926e3275978f00dc118a1a962c9b5 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes |
/**
* Created by bubbl on 6/27/2016.
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception{
FastScanner sc = new FastScanner();
int n = sc.nextInt();
Integer[] nums = new Integer[n];
for(int i=0;i<n;i++)
nums[i] = sc.nextInt();
Arrays.sort(nums);
int ans=1;
for(int i=0;i<n;i++)
if(ans<=nums[i])
ans++;
System.out.println(ans);
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer tokenizer;
FastScanner() throws FileNotFoundException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
}
String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String readLine() throws IOException {
return reader.readLine();
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 11485bbe50b97bdb562e5fc4c0375af0 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.io.*;
/**
* @author Mighty Cohadar
*/
public class Bravo {
static void insertionSort(int[] A, int li, int re) {
for (int r = li + 1; r < re; r++) {
int val = A[r];
int l = r;
while (li < l && A[l-1] > val) {
A[l] = A[l-1];
l--;
}
A[l] = val;
}
}
static void merge(int[] A, int[] B, int li, int mi, int re) {
int l = li;
int r = mi;
int j = li;
while (l < mi && r < re) {
if (A[l] <= A[r]) {
B[j++] = A[l++];
} else {
B[j++] = A[r++];
}
}
while (l < mi) {
B[j++] = A[l++];
}
for (int i = li; i < j; i++) {
A[i] = B[i];
}
}
static void mergeSort(int[] A, int[] B, int li, int re) {
if (li >= re) {
return;
}
if (re - li <= 10) {
insertionSort(A, li, re);
} else {
int mi = (li + re) >>> 1;
mergeSort(A, B, li, mi);
mergeSort(A, B, mi, re);
merge(A, B, li, mi, re);
}
}
static void mergeSort(int[] A, int li, int re) {
mergeSort(A, new int[A.length], li, re);
}
public static void main(String[] args) throws Exception {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] A = new int[n];
for (int i = 0; i < A.length; i++) {
A[i] = scanner.nextInt();
}
mergeSort(A, 0, A.length);
int j = 1;
for (int i = 0; i < A.length; i++) {
if (A[i] >= j) {
j++;
}
}
System.out.println(j);
}
}
class FastScanner {
private final BufferedReader in;
private final StringBuilder sb;
private StringTokenizer strtok;
public FastScanner(InputStream is) {
this.in = new BufferedReader(new InputStreamReader(is));
this.sb = new StringBuilder();
this.strtok = null;
}
public String next() {
try {
if (strtok == null || strtok.hasMoreTokens() == false) {
strtok = new StringTokenizer(in.readLine());
}
return strtok.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
if (strtok == null) {
return in.readLine();
} else {
String ret = (strtok.hasMoreTokens()) ? strtok.nextToken("\n") : "";
strtok = null;
return ret;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 2584c71b70e01c305ca3b698d7748a18 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.io.*;
/**
* @author Mighty Cohadar
*/
public class Bravo {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(br.readLine());
List<Integer> L = new ArrayList<>();
String[] S = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
L.add(Integer.valueOf(S[i]));
}
Collections.sort(L);
int j = 1;
for (int a : L) {
if (j <= a) {
j++;
}
}
System.out.println(j);
}
}
class FastScanner {
private final BufferedReader in;
private final StringBuilder sb;
private StringTokenizer strtok;
public FastScanner(InputStream is) {
this.in = new BufferedReader(new InputStreamReader(is));
this.sb = new StringBuilder();
this.strtok = null;
}
public String next() {
try {
if (strtok == null || strtok.hasMoreTokens() == false) {
strtok = new StringTokenizer(in.readLine());
}
return strtok.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
if (strtok == null) {
return in.readLine();
} else {
String ret = (strtok.hasMoreTokens()) ? strtok.nextToken("\n") : "";
strtok = null;
return ret;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 2502b8ed7c953f94e6ce333443914e67 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.io.*;
/* Mighty Cohadar */
public class Bravo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
PriorityQueue<Integer> Q = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
Q.add(scanner.nextInt());
}
int j = 1;
for (int i = 0; i < n; i++) {
int a = Q.remove();
if (a >= j) {
j++;
}
}
System.out.println(j);
}
static void debug(Object...os) {
System.err.printf("%.65536s\n", Arrays.deepToString(os));
}
}
class FastScanner {
private final BufferedReader in;
private final StringBuilder sb;
private StringTokenizer strtok;
public FastScanner(InputStream is) {
this.in = new BufferedReader(new InputStreamReader(is));
this.sb = new StringBuilder();
this.strtok = null;
}
public String next() {
try {
if (strtok == null || strtok.hasMoreTokens() == false) {
strtok = new StringTokenizer(in.readLine());
}
return strtok.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
if (strtok == null) {
return in.readLine();
} else {
String ret = (strtok.hasMoreTokens()) ? strtok.nextToken("\n") : "";
strtok = null;
return ret;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | aa54b849db371bf8499f7097e95f87a7 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.io.*;
/* Mighty Cohadar */
public class Bravo {
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
PriorityQueue<Integer> Q = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
Q.add(scanner.nextInt());
}
int j = 1;
for (int i = 0; i < n; i++) {
int a = Q.remove();
if (a >= j) {
j++;
}
}
System.out.println(j);
}
static void debug(Object...os) {
System.err.printf("%.65536s\n", Arrays.deepToString(os));
}
}
class FastScanner {
private final BufferedReader in;
private final StringBuilder sb;
private StringTokenizer strtok;
public FastScanner(InputStream is) {
this.in = new BufferedReader(new InputStreamReader(is));
this.sb = new StringBuilder();
this.strtok = null;
}
public String next() {
try {
if (strtok == null || strtok.hasMoreTokens() == false) {
strtok = new StringTokenizer(in.readLine());
}
return strtok.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
if (strtok == null) {
return in.readLine();
} else {
String ret = (strtok.hasMoreTokens()) ? strtok.nextToken("\n") : "";
strtok = null;
return ret;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 03e01f188582c3d0071ddb4ec87cb25b | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.util.Scanner;
/**
* Created by Hp on 6/18/2016.
*/
public class B {
public static void main(String [] ar) throws IOException{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bufferedReader.readLine());
String[] s = bufferedReader.readLine().split(" ");
List<Integer>a=new ArrayList<Integer>();
long ans=1;
for(int i=0;i<n;i++){
a.add(Integer.parseInt(s[i]));
}
Collections.sort(a);
for(long i:a){
if(i>=ans){
ans++;
}
}
System.out.println(ans);
}
// -----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// --------------------------------------------------------
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 4aad4047aa1b931f79edef9aa5f5a502 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class B {
int N;
Integer[] a;
public void solve() {
N = nextInt();
a = new Integer[N];
for(int i = 0;i < N;i++){
a[i] = new Integer(nextInt());
}
Arrays.sort(a);
a[0] = 1;
for(int i = 1;i < N;i++){
if(a[i - 1] < a[i]){
a[i] = a[i - 1] + 1;
}
}
int pre = 0;
for(int i = 0;i < N;i++){
if(a[i] - pre > 1){
out.println(pre + 1);
return;
}
pre = a[i];
}
out.println(pre + 1);
}
public static void main(String[] args) {
out.flush();
new B().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 7bfaca24e8f412fd28026a71fab15da5 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.NoSuchElementException;
public class B {
int N;
ArrayList<Integer> a,b;
public void solve() {
N = nextInt();
a = new ArrayList<Integer>();
b = new ArrayList<Integer>();
for(int i = 0;i < N;i++){
a.add(nextInt());
}
Collections.sort(a);
b.add(1);
for(int i = 1;i < N;i++){
if(b.get(i - 1) < a.get(i)){
b.add(b.get(i - 1) + 1);
}else{
b.add(a.get(i));
}
}
int pre = 0;
for(int i = 0;i < N;i++){
if(b.get(i) - pre > 1){
out.println(pre + 1);
return;
}
pre = b.get(i);
}
out.println(pre + 1);
}
public static void main(String[] args) {
out.flush();
new B().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | b909af791c68333d8e2b4b2ad21abdca | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
public class B {
int N;
int[] a;
public void shuffleArray(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
public void solve() {
N = nextInt();
a = new int[N];
for (int i = 0; i < N; i++) {
a[i] = nextInt();
}
shuffleArray(a);
Arrays.sort(a);
a[0] = 1;
for (int i = 1; i < N; i++) {
if (a[i - 1] < a[i]) {
a[i] = a[i - 1] + 1;
}
}
int pre = 0;
for (int i = 0; i < N; i++) {
if (a[i] - pre > 1) {
out.println(pre + 1);
return;
}
pre = a[i];
}
out.println(pre + 1);
}
public static void main(String[] args) {
out.flush();
new B().solve();
out.close();
}
/* Input */
private static final InputStream in = System.in;
private static final PrintWriter out = new PrintWriter(System.out);
private final byte[] buffer = new byte[2048];
private int p = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (p < buflen)
return true;
p = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0)
return false;
return true;
}
public boolean hasNext() {
while (hasNextByte() && !isPrint(buffer[p])) {
p++;
}
return hasNextByte();
}
private boolean isPrint(int ch) {
if (ch >= '!' && ch <= '~')
return true;
return false;
}
private int nextByte() {
if (!hasNextByte())
return -1;
return buffer[p++];
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = -1;
while (isPrint((b = nextByte()))) {
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | af319b011a4280a3ca76081f35cf49f4 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by Shurikat on 09.07.16.
*/
public class Codeforces {
static Integer[] array;
static Integer[] t;
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());
st = new StringTokenizer(br.readLine());
//t = new int[n];
ArrayList<Integer> list = new ArrayList<>(n); // +
for (int i = 0; i < n; ++i) {
list.add(Integer.parseInt(st.nextToken())); //+
//t[i] = Integer.parseInt(st.nextToken());
}
t = list.toArray(new Integer[n]);
Arrays.sort(t);
t[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = t[i + 1] - t[i];
if (d > 1) {
t[i + 1] -= d - 1;
}
}
System.out.println(t[n - 1] + 1);/*/
/*
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
ArrayList<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; ++i)
list.add(Integer.parseInt(st.nextToken()));
//list.sort(Integer::compareTo);
//array = list.toArray(new Integer[n]);
array = list.toArray(new Integer[n]);
Arrays.sort(array);
array[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = array[i + 1] - array[i];
if (d > 1) {
array[i + 1] -= d - 1;
}
}
System.out.println(array[n - 1] + 1);
//*/
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 80dc21ed1f76001c66120d5751636e01 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by Shurikat on 09.07.16.
*/
public class Codeforces {
static Integer[] array;
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());
st = new StringTokenizer(br.readLine());
ArrayList<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; ++i)
list.add(Integer.parseInt(st.nextToken()));
//list.sort(Integer::compareTo);
//array = list.toArray(new Integer[n]);
array = list.toArray(new Integer[n]);
Arrays.sort(array);
array[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = array[i + 1] - array[i];
if (d > 1) {
array[i + 1] -= d - 1;
}
}
System.out.println(array[n - 1] + 1);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 76c1674a7a4f92e1af520ea6f9a179d7 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
/**
* Created by Shurikat on 09.07.16.
*/
public class Codeforces {
static int[] array;
private static void doSort(int start, int end) {
if (start >= end)
return;
int i = start, j = end;
int cur = i - (i - j) / 2;
while (i < j) {
while (i < cur && (array[i] <= array[cur])) {
i++;
}
while (j > cur && (array[cur] <= array[j])) {
j--;
}
if (i < j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
if (i == cur)
cur = j;
else if (j == cur)
cur = i;
}
}
doSort(start, cur);
doSort(cur+1, end);
}
public static void main(String[] args) throws Exception {
long t0 = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = Integer.parseInt(st.nextToken());
}
doSort(0, n - 1);
array[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = array[i + 1] - array[i];
if (d > 1) {
array[i + 1] -= d - 1;
}
}
System.out.println(array[n - 1] + 1);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 372e8c5ce9bbd16cc18ff150d88f0800 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by Shurikat on 09.07.16.
*/
public class Codeforces {
static Integer[] array;
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());
st = new StringTokenizer(br.readLine());
ArrayList<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; ++i)
list.add(Integer.parseInt(st.nextToken()));
list.sort(Integer::compareTo);
array = list.toArray(new Integer[n]);
//array = list.stream().sorted().toArray(Integer[]::new);
array[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = array[i + 1] - array[i];
if (d > 1) {
array[i + 1] -= d - 1;
}
}
System.out.println(array[n - 1] + 1);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 53f3613261ab7942371bc04c8dfaa880 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by Shurikat on 09.07.16.
*/
public class Codeforces {
static Integer[] t;
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());
st = new StringTokenizer(br.readLine());
t = new Integer[n]; // -
//ArrayList<Integer> list = new ArrayList<>(n); // +
for (int i = 0; i < n; ++i) { // -
//list.add(Integer.parseInt(st.nextToken())); //+
t[i] = Integer.parseInt(st.nextToken()); // -
}
//t = list.toArray(new Integer[n]); // +
Arrays.sort(t);
t[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = t[i + 1] - t[i];
if (d > 1) {
t[i + 1] -= d - 1;
}
}
System.out.println(t[n - 1] + 1);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | d4ff689c5edbd6c0d97e3773bfc92a24 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by Shurikat on 09.07.16.
*/
public class Codeforces {
static Integer[] array;
// private static void doSort(int start, int end) {
// if (start >= end)
// return;
// int i = start, j = end;
// int cur = i - (i - j) / 2;
// while (i < j) {
// while (i < cur && (array[i] <= array[cur])) i++;
// while (j > cur && (array[cur] <= array[j])) j--;
// if (i < j) {
// int temp = array[i];
// array[i] = array[j];
// array[j] = temp;
// if (i == cur) cur = j;
// else if (j == cur) cur = i;
// }
// }
// doSort(start, cur);
// doSort(cur+1, end);
// }
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());
st = new StringTokenizer(br.readLine());
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; ++i)
list.add(Integer.parseInt(st.nextToken()));
array = list.stream().sorted().toArray(Integer[]::new);
array[0] = 1;
for (int i = 0; i < n - 1; ++i) {
int d = array[i + 1] - array[i];
if (d > 1) {
array[i + 1] -= d - 1;
}
}
System.out.println(array[n - 1] + 1);
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | f016e9ca490a6e9d57414860cedf7277 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.util.concurrent.*;
public class Main {
//---------------------------------------------------------------------------
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
//-----------------------------------------------------------------------
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
shuffleArray(a);
Arrays.sort(a);
int need = 1;
for (int i = 0; i < n; i++) {
if (a[i] >= need) {
a[i] = need;
need++;
}
}
out.println(need);
//-----------------------------------------------------------------------
out.close();
}
//---------------------------------------------------------------------------
static void shuffleArray(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
static class Pair implements Comparator {
int first, second;
public Pair() {
}
public Pair(int f, int s) {
this.first = f;
this.second = s;
}
@Override
public int compare(Object o1, Object o2) {
Pair p1 = (Pair) o1;
Pair p2 = (Pair) o2;
int ret = Integer.compare(p1.first, p2.first);
if (ret == 0) {
ret = Integer.compare(p1.second, p2.second);
}
return ret;
}
}
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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char[] nextCharArray() {
return next().toCharArray();
}
public boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String s = reader.readLine();
if (s == null) {
return false;
}
tokenizer = new StringTokenizer(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
public void skipLine() {
try {
tokenizer = null;
reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | c0def57ee0bb195bb468296b937bcfad | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
public class Main {
//---------------------------------------------------------------------------
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
//-----------------------------------------------------------------------
int n = in.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
Arrays.sort(a);
int need = 1;
for (int i = 0; i < n; i++) {
if (a[i] >= need) {
a[i] = need;
need++;
}
}
out.println(need);
//-----------------------------------------------------------------------
out.close();
}
//---------------------------------------------------------------------------
static class Pair implements Comparator {
int first, second;
public Pair() {
}
public Pair(int f, int s) {
this.first = f;
this.second = s;
}
@Override
public int compare(Object o1, Object o2) {
Pair p1 = (Pair) o1;
Pair p2 = (Pair) o2;
int ret = Integer.compare(p1.first, p2.first);
if (ret == 0) {
ret = Integer.compare(p1.second, p2.second);
}
return ret;
}
}
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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char[] nextCharArray() {
return next().toCharArray();
}
public boolean hasNext() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
String s = reader.readLine();
if (s == null) {
return false;
}
tokenizer = new StringTokenizer(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return true;
}
public void skipLine() {
try {
tokenizer = null;
reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | b6c26b8c3856666b3bcb286c555cd98c | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class Main {
public static void main(String[] args) throws Exception {
solve(1);
}
public static void solve(int testCases) throws Exception{
int n = StdIn.readInt();
Integer[] a = new Integer[n];
for(int i = 0 ; i < n ; i++) a[i] = StdIn.readInt();
Merge.sort(a);
if(a[0] > 1){
a[0] = 1;
}
for(int i = 1 ; i < n ; i++){
int prev = a[i-1];
int target = prev + 1;
if(a[i] == target || a[i] == a[i-1]){
continue;
}else if(a[i] > target){
a[i] = target;
}
}
StdOut.println(a[n-1] + 1);
}
}
class Merge{
@SuppressWarnings("rawtypes")
private static Comparable[] aux;
@SuppressWarnings("rawtypes")
public static void sort(Comparable[] a){
aux = new Comparable[a.length];
sort(a, 0, a.length - 1);
}
@SuppressWarnings("rawtypes")
private static void sort(Comparable[] a, int lo, int hi){
if(hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
@SuppressWarnings({ "rawtypes" })
private static void merge(Comparable[] a, int lo, int mid, int hi){
int i = lo;
int j = mid + 1;
for(int k = lo ; k <= hi ; k++)
aux[k] = a[k];
for(int k = lo ; k <= hi ; k++)
if(i > mid) a[k] = aux[j++];
else if(j > hi) a[k] = aux[i++];
else if(less(aux[j], aux[i])) a[k] = aux[j++];
else a[k] = aux[i++];
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private static boolean less(Comparable v, Comparable w){
return v.compareTo(w) < 0;
}
}
final class StdIn {
private StdIn() { }
private static Scanner scanner;
private static final String CHARSET_NAME = "UTF-8";
private static final Locale LOCALE = Locale.US;
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+");
private static final Pattern EMPTY_PATTERN = Pattern.compile("");
private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A");
public static boolean isEmpty() {
return !scanner.hasNext();
}
public static boolean hasNextLine() {
return scanner.hasNextLine();
}
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
public static String readLine() {
String line;
try { line = scanner.nextLine(); }
catch (Exception e) { line = null; }
return line;
}
public static char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert (ch.length() == 1) : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
public static String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
public static String readString() {
return scanner.next();
}
public static int readInt() {
return scanner.nextInt();
}
public static double readDouble() {
return scanner.nextDouble();
}
public static float readFloat() {
return scanner.nextFloat();
}
public static long readLong() {
return scanner.nextLong();
}
public static short readShort() {
return scanner.nextShort();
}
public static byte readByte() {
return scanner.nextByte();
}
public static boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
public static String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// because trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
// don't include first token if it is leading whitespace
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length - 1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
public static String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
}
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
public static double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
}
static {
resync();
}
private static void resync() {
setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME));
}
private static void setScanner(Scanner scanner) {
StdIn.scanner = scanner;
StdIn.scanner.useLocale(LOCALE);
}
public static int[] readInts() {
return readAllInts();
}
public static double[] readDoubles() {
return readAllDoubles();
}
public static String[] readStrings() {
return readAllStrings();
}
}
final class StdOut {
private static final String CHARSET_NAME = "UTF-8";
private static final Locale LOCALE = Locale.US;
private static PrintWriter out;
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) { System.out.println(e); }
}
private StdOut() { }
public static void close() {
out.close();
}
public static void println() {
out.println();
}
public static void println(Object x) {
out.println(x);
}
public static void println(boolean x) {
out.println(x);
}
public static void println(char x) {
out.println(x);
}
public static void println(double x) {
out.println(x);
}
public static void println(float x) {
out.println(x);
}
public static void println(int x) {
out.println(x);
}
public static void println(long x) {
out.println(x);
}
public static void println(short x) {
out.println(x);
}
public static void println(byte x) {
out.println(x);
}
public static void print() {
out.flush();
}
public static void print(Object x) {
out.print(x);
out.flush();
}
public static void print(boolean x) {
out.print(x);
out.flush();
}
public static void print(char x) {
out.print(x);
out.flush();
}
public static void print(double x) {
out.print(x);
out.flush();
}
public static void print(float x) {
out.print(x);
out.flush();
}
public static void print(int x) {
out.print(x);
out.flush();
}
public static void print(long x) {
out.print(x);
out.flush();
}
public static void print(short x) {
out.print(x);
out.flush();
}
public static void print(byte x) {
out.print(x);
out.flush();
}
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 77d71c5366e57237ee3b00d1c09b457a | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main{
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str = br.readLine();
} catch (IOException e){
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
MyScanner s = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n=s.nextInt();
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<n;i++) list.add(s.nextInt());//=s.nextInt();
Collections.sort(list);
int curr=1;
for(int i=0;i<n;i++){
if(list.get(i)>=curr) curr++;
}
out.println(curr);
out.close();
}
} | Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 3cab1193f61e403eecaacc78afc71dd4 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
int[] arr = new int[n];
String[] tempInput = input.readLine().split("\\s+");
int i = 0;
for (String s : tempInput) {
arr[i] = Integer.parseInt(s);
i++;
}
//quickSort(arr, 0, arr.length - 1);
mergeSort(arr, 0, arr.length - 1);
int currentMin = 1;
for (i = 0; i < n; i++) {
if (arr[i] >= currentMin) {
++currentMin;
}
}
PrintWriter writer = new PrintWriter(System.out);
writer.println(currentMin);
//for(int j=0;j<n;j++)writer.println(arr[j]);
writer.flush();
}
public static void mergeSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int mid, int r) {
int[] tempArr = new int[r - l + 1];
int i = l;
int j = mid + 1;
int counter = 0;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) {
tempArr[counter] = arr[i];
++i;
} else {
tempArr[counter] = arr[j];
++j;
}
++counter;
}
while (i <= mid) {
tempArr[counter] = arr[i];
++i;
++counter;
}
while (j <= r) {
tempArr[counter] = arr[j];
++j;
++counter;
}
for (counter = 0; counter < r - l + 1; ++counter) {
arr[l + counter] = tempArr[counter];
}
}
public static void quickSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = partition(arr, l, r);
quickSort(arr, l, mid);
quickSort(arr, mid + 1, r);
}
public static int partition(int[] arr, int l, int r) {
int i = l - 1;
int j = r + 1;
int pivot = arr[l];
while (true) {
do {
i++;
} while (pivot > arr[i]);
do {
j--;
} while (pivot < arr[j]);
if (i >= j) {
return j;
}
swap(arr, i, j);
}
}
public static void swap(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 11340df94f73d7715c183a382df35d37 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
Integer[] arr = new Integer[n];
String[] tempInput = input.readLine().split("\\s+");
int i = 0;
for (String s : tempInput) {
arr[i] = Integer.parseInt(s);
i++;
}
//quickSort(arr, 0, arr.length - 1);
//mergeSort(arr, 0, arr.length - 1);
//List<Integer> list = new ArrayList<>(Arrays.asList(arr));
List<Integer> list = Arrays.asList(arr);
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return i1 - i2;
}
});
int currentMin = 1;
for (i = 0; i < n; i++) {
if (arr[i] >= currentMin) {
++currentMin;
}
}
PrintWriter writer = new PrintWriter(System.out);
writer.println(currentMin);
//for(int j=0;j<n;j++)writer.println(arr[j]);
writer.flush();
}
public static void mergeSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int mid, int r) {
int[] tempArr = new int[r - l + 1];
int i = l;
int j = mid + 1;
int counter = 0;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) {
tempArr[counter] = arr[i];
++i;
} else {
tempArr[counter] = arr[j];
++j;
}
++counter;
}
while (i <= mid) {
tempArr[counter] = arr[i];
++i;
++counter;
}
while (j <= r) {
tempArr[counter] = arr[j];
++j;
++counter;
}
for (counter = 0; counter < r - l + 1; ++counter) {
arr[l + counter] = tempArr[counter];
}
}
public static void quickSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = partition(arr, l, r);
quickSort(arr, l, mid);
quickSort(arr, mid + 1, r);
}
public static int partition(int[] arr, int l, int r) {
int i = l - 1;
int j = r + 1;
int pivot = arr[l];
while (true) {
do {
i++;
} while (pivot > arr[i]);
do {
j--;
} while (pivot < arr[j]);
if (i >= j) {
return j;
}
swap(arr, i, j);
}
}
public static void swap(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 7d977d0f508e6d79ba0f581ba318aa16 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
Integer[] arr = new Integer[n];
String[] tempInput = input.readLine().split("\\s+");
int i = 0;
for (String s : tempInput) {
arr[i] = Integer.parseInt(s);
i++;
}
//quickSort(arr, 0, arr.length - 1);
//mergeSort(arr, 0, arr.length - 1);
List<Integer> list = new ArrayList<>(Arrays.asList(arr));
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return i1 - i2;
}
});
int currentMin = 1;
for (i = 0; i < n; i++) {
if (list.get(i) >= currentMin) {
++currentMin;
}
}
PrintWriter writer = new PrintWriter(System.out);
writer.println(currentMin);
//for(int j=0;j<n;j++)writer.println(arr[j]);
writer.flush();
}
public static void mergeSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int mid, int r) {
int[] tempArr = new int[r - l + 1];
int i = l;
int j = mid + 1;
int counter = 0;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) {
tempArr[counter] = arr[i];
++i;
} else {
tempArr[counter] = arr[j];
++j;
}
++counter;
}
while (i <= mid) {
tempArr[counter] = arr[i];
++i;
++counter;
}
while (j <= r) {
tempArr[counter] = arr[j];
++j;
++counter;
}
for (counter = 0; counter < r - l + 1; ++counter) {
arr[l + counter] = tempArr[counter];
}
}
public static void quickSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = partition(arr, l, r);
quickSort(arr, l, mid);
quickSort(arr, mid + 1, r);
}
public static int partition(int[] arr, int l, int r) {
int i = l - 1;
int j = r + 1;
int pivot = arr[l];
while (true) {
do {
i++;
} while (pivot > arr[i]);
do {
j--;
} while (pivot < arr[j]);
if (i >= j) {
return j;
}
swap(arr, i, j);
}
}
public static void swap(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 66a80a7d2667b1ef7ff710395dda312d | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
int[] arr = new int[n];
String[] tempInput = input.readLine().split("\\s+");
int i = 0;
for (String s : tempInput) {
arr[i] = Integer.parseInt(s);
i++;
}
quickSort(arr, 0, arr.length - 1);
int currentMin = 1;
for (i = 0; i < n; i++) {
if (arr[i] >= currentMin) {
++currentMin;
}
}
PrintWriter writer = new PrintWriter(System.out);
writer.println(currentMin);
//for(int j=0;j<n;j++)writer.println(arr[j]);
writer.flush();
}
public static void quickSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = partition(arr, l, r);
quickSort(arr, l, mid);
quickSort(arr, mid + 1, r);
}
public static int partition(int[] arr, int l, int r) {
int i = l - 1;
int j = r + 1;
int pivot = arr[l];
while (true) {
do {
i++;
} while (pivot > arr[i]);
do {
j--;
} while (pivot < arr[j]);
if (i >= j) {
return j;
}
swap(arr, i, j);
}
}
public static void swap(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | f4319624227dcf4dee26116701675609 | train_000.jsonl | 1466181300 | Someone gave Alyona an array containing n positive integers a1,βa2,β...,βan. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,βb2,β...,βbn such that 1ββ€βbiββ€βai for every 1ββ€βiββ€βn. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1. | 256 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
Integer[] arr = new Integer[n];
String[] tempInput = input.readLine().split("\\s+");
int i = 0;
for (String s : tempInput) {
arr[i] = Integer.parseInt(s);
i++;
}
//quickSort(arr, 0, arr.length - 1);
//mergeSort(arr, 0, arr.length - 1);
//List<Integer> list = new ArrayList<>(Arrays.asList(arr));
//List<Integer> list = Arrays.asList(arr);
Arrays.sort(arr);
/*
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return i1 - i2;
}
});
*/
int currentMin = 1;
for (i = 0; i < n; i++) {
if (arr[i] >= currentMin) {
++currentMin;
}
}
PrintWriter writer = new PrintWriter(System.out);
writer.println(currentMin);
//for(int j=0;j<n;j++)writer.println(arr[j]);
writer.flush();
}
public static void mergeSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void merge(int[] arr, int l, int mid, int r) {
int[] tempArr = new int[r - l + 1];
int i = l;
int j = mid + 1;
int counter = 0;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) {
tempArr[counter] = arr[i];
++i;
} else {
tempArr[counter] = arr[j];
++j;
}
++counter;
}
while (i <= mid) {
tempArr[counter] = arr[i];
++i;
++counter;
}
while (j <= r) {
tempArr[counter] = arr[j];
++j;
++counter;
}
for (counter = 0; counter < r - l + 1; ++counter) {
arr[l + counter] = tempArr[counter];
}
}
public static void quickSort(int[] arr, int l, int r) {
if (l >= r) {
return;
}
int mid = partition(arr, l, r);
quickSort(arr, l, mid);
quickSort(arr, mid + 1, r);
}
public static int partition(int[] arr, int l, int r) {
int i = l - 1;
int j = r + 1;
int pivot = arr[l];
while (true) {
do {
i++;
} while (pivot > arr[i]);
do {
j--;
} while (pivot < arr[j]);
if (i >= j) {
return j;
}
swap(arr, i, j);
}
}
public static void swap(int[] arr, int pos1, int pos2) {
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
| Java | ["5\n1 3 3 3 6", "2\n2 1"] | 1 second | ["5", "3"] | NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements. | Java 8 | standard input | [
"sortings"
] | 482b3ebbbadd583301f047181c988114 | The first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of elements in the Alyona's array. The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the elements of the array. | 1,200 | Print one positive integerΒ β the maximum possible value of mex of the array after Alyona applies some (possibly none) operations. | standard output | |
PASSED | 3b3c9285aa8a6a6edaead3cc7cc07cbe | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | /*
* Remember a 6.0 student can know more than a 10.0 student.
* Grades don't determine intelligence, they test obedience.
* I Never Give Up.
* I will become Candidate Master.
* I will defeat Saurabh Anand.
* Skills are Cheap,Passion is Priceless.
*/
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.text.*;
import static java.lang.System.out;
import static java.util.Arrays.*;
import static java.lang.Math.*;
public class ContestMain {
private static Reader in=new Reader();
private static StringBuilder ans=new StringBuilder();
private static long MOD=1000000000+7;//10^9+7
private static final int N=100000+7; //10^5+7
private static final double EPS=1e-9;
// private static final int LIM=26;
// private static final double PI=3.1415;
// private static ArrayList<Integer> v[]=new ArrayList[N];
// private static int color[]=new int[N];
private static boolean mark[]=new boolean[N];
// private static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// private static ArrayList<Pair> v[]=new ArrayList[N];
private static long powmod(long x,long n){
if(n==0||x==0)return 1;
else if(n%2==0)return(powmod((x*x)%MOD,n/2));
else return (x*(powmod((x*x)%MOD,(n-1)/2)))%MOD;
}
// private static <E extends Comparable> E min(E a,E b){
// if(a.compareTo(b)>=0)return b;
// else return a;
// }
// private static <E extends Comparable> E min(E a,E b,E c){
// if(a.compareTo(b)>=0)return b;
// else return a;
// }
// private static void shuffle(long [] arr) {
// for (int i = arr.length - 1; i >= 2; i--) {
// int x = new Random().nextInt(i - 1);
// long temp = arr[x];
// arr[x] = arr[i];
// arr[i] = temp;
// }
// }
// private static long gcd(long a, long b){
// if(b==0)return a;
// return gcd(b,a%b);
// }
// private static boolean check(int x,int y){
// if((x>=0&&x<n)&&(y>=0&&y<m)&&mat[x][y]!='X'&&!visited[x][y])return true;
// return false;
// }
// static class Node{
// int left;
// int right;
// Node(){
// left=0;
// right=0;
// }
// }
static long ar[],cnt=0;
static ArrayList<Pair> v[]=new ArrayList[N];
public static void dfs(int node,boolean flag,long val){
mark[node]=true;
for(Pair pair:v[node]){
if(!mark[pair.l]){
if(val>ar[node]||flag)dfs(pair.l,true,max(0,val+pair.r));
else dfs(pair.l,false,max(0,val+pair.r));
}
}
if(val>ar[node]||flag)cnt++;
}
public static void main(String[] args) throws IOException{
int n=in.nextInt();
ar=new long[n+1];
for(int i=1;i<=n;i++)
ar[i]=in.nextLong();
int p,c;
for(int i=1;i<=n;i++)
v[i]=new ArrayList();
for(int i=1;i<n;i++){
p=in.nextInt();
c=in.nextInt();
v[i+1].add(new Pair(p,c));
v[p].add(new Pair(i+1,c));
}
dfs(1,false,0);
out.println(cnt);
}
static class Pair<T> implements Comparable<Pair>{
int l;
int r;
Pair(){
l=0;
r=0;
}
Pair(int k,int v){
l=k;
r=v;
}
@Override
public int compareTo(Pair o) {
if(o.l!=l)return (int) (l-o.l);
else return (int)(r-o.r);
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader()
{
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 0cdcd60f14c05b4253708c83489ed2e8 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.*;
import java.util.*;
public class AlyonaTree {
static Graph g[];
static String ver[];
static int par[],count;
static long d[];
static boolean vis[];
public static void main(String args[]) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
ver=br.readLine().split(" ");
g= new Graph[n+1];
for(int i=1;i<n+1;i++){
g[i]= new Graph();
}
for(int i=2;i<=n;i++){
String s[]=br.readLine().split(" ");
g[i].al.add(new edge(Integer.parseInt(s[0]), Integer.parseInt(s[1])));
g[Integer.parseInt(s[0])].al.add(new edge(i, Integer.parseInt(s[1])));
}
par=new int[n+1];
d=new long[n+1];
count=0;
vis = new boolean[n+1];
dfs2(1,0,0);
System.out.println(n-count);
}
private static void dfs2(int s,long dis,long sum){
d[s]=dis;
/* int v = s;
int u=s;
while(!vis[s] && par[u]!=0){
v = par[u];
if(d[s] - d[v] > Integer.parseInt(ver[s-1])){
vis[s] = true;
return;
}
u=v;
}*/
if(dis>0)
sum=dis;
else{
sum=0;
dis=0;
}
if(sum> Integer.parseInt(ver[s-1])){
vis[s] = true;
return;
}
count++;
for(int i=0;i<g[s].al.size();i++){
edge e = g[s].al.get(i);
if( par[s]!=e.v){
par[e.v] =s;
dfs2(e.v,dis+e.w,sum);
}
}
}
private static class Graph{
ArrayList<edge> al = new ArrayList<edge>();
}
private static class edge{
int v;
int w;
public edge(int v, int w){
this.v=v;
this.w=w;
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | b68042d0aec8dc150c8084a904150763 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.awt.*;
import java.io.*;
import java.util.*;
public class Abc {
static int n;
static int arr[];
static int cnt[];
static ArrayList<Integer> adj[];
static Map<Point,Integer> map;
static int ans=0;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
n=sc.nextInt();
adj=new ArrayList[n];
for (int i=0;i<n;i++){
adj[i]=new ArrayList<>();
}
map=new HashMap<>();
arr=new int[n];
cnt=new int[n];
for (int i=0;i<n;i++)arr[i]=sc.nextInt();
for (int i=0;i<n-1;i++){
int p=sc.nextInt()-1;
adj[i+1].add(p);
adj[p].add(i+1);
int c=sc.nextInt();
map.put(new Point(i+1,p),c);
map.put(new Point(p,i+1),c);
}
dfs(0,0);
dfs1(0,0,0,0);
System.out.println(ans);
}
static void dfs1(int v,int par,long dis,long sum){
if (sum-dis>arr[v]){
ans+=cnt[v];
return;
}
for (int u:adj[v]){
if (u!=par){
dfs1(u,v,Math.min(sum+map.get(new Point(u,v)),dis),sum+map.get(new Point(u,v)));
}
}
}
static void dfs(int v,int par){
for (int u:adj[v]){
if (u!=par){
dfs(u,v);
cnt[v]+=cnt[u];
}
}
cnt[v]++;
}
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 0f7cdde3c0f1d3aece06afb82907b44c | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class _Alyona_and_the_Trees {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
String[] sr = br.readLine().split(" ");
ArrayList<ArrayList<pair>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(sr[i]);
}
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
boolean[] art = new boolean[n];
for (int i = 1; i <= n-1; i++) {
sr = br.readLine().split(" ");
int val = Integer.parseInt(sr[0]) - 1;
long wt = Integer.parseInt(sr[1]);
pair p = new pair(val, wt);
graph.get(i).add(p);
graph.get(val).add(new pair(i, wt));
}
dfs(0, -1, graph, 0,0, art, arr);
int[] dp = new int[n];
dfs2(0, -1, graph, dp);
int c=0;
for(int i=0;i<n;i++){
if(art[i]){
c+=dp[i];
}
}
System.out.println(c);
}
public static void dfs(int v, int par, ArrayList<ArrayList<pair>> graph, long dist, long min, boolean[] arr,
int[] values) {
if (dist - min > values[v]) {
arr[v] = true;
return;
}
for (pair p : graph.get(v)) {
if (p.vert == par) {
continue;
}
dfs(p.vert, v, graph, dist+p.weight, Math.min(dist + p.weight, min), arr, values);
}
}
public static int dfs2(int v, int p, ArrayList<ArrayList<pair>> graph, int[] dp) {
int c = 0;
for (pair ver : graph.get(v)) {
if (ver.vert == p) {
continue;
}
c += dfs2(ver.vert, v, graph, dp);
}
return dp[v]=c + 1;
}
public static class pair {
int vert;
long weight;
pair(int val, long weight) {
this.vert = val;
this.weight = weight;
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 0410d3c3997c0887a941553b3d144961 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.BigInteger;
import java.util.regex.*;
public class Myclass {
public static ArrayList a[]=new ArrayList[200001];
static boolean visited[]=new boolean [200001];
static long value[];
static long maxi[];
static long dp[]=new long[200001];
static long ans;
static void dfs(pair n,int p)
{
visited[n.x]=true;
dp[n.x]=Math.max(dp[p]+n.y,n.y);
if(dp[n.x]>value[n.x])
{
ans++;
return;
}
for(int i=0;i<a[n.x].size();i++)
{
pair y=(pair) a[n.x].get(i);
if(!visited[y.x])
{
dfs(y,n.x);
}
}
}
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=in.nextInt();
for(int i=0;i<=n;i++)
a[i]=new ArrayList<pair>();
value=new long[n+1];
maxi=new long[n+1];
for(int i=1;i<=n;i++)
value[i]=in.nextLong();
for(int i=2;i<=n;i++)
{
int x=in.nextInt();
long y=in.nextLong();
a[i].add(new pair(x,y));
a[x].add(new pair(i,y));
}
dp[0]=0;
value[0]=Long.MIN_VALUE;
dfs(new pair(1,0),0);
//pw.println(Arrays.toString(dp));
for(int i=1;i<=n;i++)
{
if(!visited[i])
ans++;
}
pw.println(ans);
pw.flush();
pw.close();
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
static class tri implements Comparable<tri> {
int p, c, l;
tri(int p, int c, int l) {
this.p = p;
this.c = c;
this.l = l;
}
public int compareTo(tri o) {
return Integer.compare(l, o.l);
}
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return modularExponentiation(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
public static long[] shuffle(long[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++){
int ind = gen.nextInt(n-i)+i;
long d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
static class pair implements Comparable<pair>
{
Integer x;
Long y;
pair(int a,long m)
{
this.x=a;
this.y=m;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
static class triplet
{
Long x;
Long y;
Long z;
triplet(long x,long y,long z)
{
this.x=x;
this.y=y;
this.z=z;
}
}
static class jodi
{
Integer x;
Integer y;
jodi(int x,int y)
{
this.x=x;
this.y=y;
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 18a904ed80621688b64ee558002c16ff | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C358 implements Runnable{
static long oo = 987654321;
static long[] val;
static int[] mark;
static long[] MAX;
public static void main(String[] args) {
new Thread(null, new C358(), "cool", 1<<25).start();
}
@Override
public void run() {
MyScanner scan = new MyScanner();
int N = scan.nextInt();
val = new long[N];
mark = new int[N];
MAX = new long[N];
for(int i=0;i<N;i++)val[i] = scan.nextLong();
ArrayList<Edge>[] adj = new ArrayList[N];
for(int i=0;i<N;i++)adj[i] = new ArrayList<>();
for(int i=0;i<N-1;i++){
int u = scan.nextInt();
adj[u-1].add(new Edge(u-1,i+1,scan.nextLong()));
}
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(0);
while(!q.isEmpty()){
int node = q.poll();
for(Edge e : adj[node]){
MAX[e.v] = Math.max(MAX[node]+e.c, 0L);
if(mark[node]!=-1&&MAX[node]+e.c<=val[e.v]){
q.add(e.v);
}else{
mark[e.v]=-1;
q.add(e.v);
}
}
}
int count = 0;
for(int i=0;i<N;i++)if(mark[i]<0)count++;
System.out.println(count);
}
private static class Edge {
int u, v;
long c;
public Edge(int u, int v, long c){this.u=u;this.v=v;this.c=c;}
}
private 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());}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | fb34945c4ad4db68b72d23e825309db1 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C358_AlonyaTree {
static ArrayList<Node> al[];
static boolean visited[];
static long size[];
static long cnt;
static boolean f[];
static long dp[];
static int a[];
public static void main(String args[]) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
// StringBuilder sb = new StringBuilder();
// ----------My Code----------
int n = in.nextInt();
a = new int[n];
al = new ArrayList[n];
dp = new long[n];
dp[0] = 0;
visited = new boolean[n];
Arrays.fill(visited, false);
f = new boolean[n];
Arrays.fill(f, true);
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
al[i] = new ArrayList<Node>();
}
for (int i = 1; i < n; i++) {
al[in.nextInt() - 1].add(new Node(i, in.nextInt()));
}
size = new long[n];
getSize(al, 0);
cnt = 0;
dfs(0,0);
// cnt=0;
out.println(cnt);
// ---------------The End------------------
out.close();
}
public static long getSize(ArrayList<Node>[] graph, int start) {
size[start] = 1;
for (Node neighbours : graph[start])
size[start] += getSize(graph, neighbours.u);
return size[start];
}
static void dfs(int i, long minVal) {
if (dp[i] - minVal > a[i]) {
cnt += size[i];
return;
}
for (int j = 0; j < al[i].size(); j++) {
int u = al[i].get(j).u;
long val = al[i].get(j).val;
dp[u] = dp[i] + val;
minVal=Math.min(minVal, dp[i]);
dfs(u, minVal);
}
}
static class Node {
int u;
long val;
public Node(int u, long val) {
super();
this.u = u;
this.val = val;
}
}
// ---------------Extra Methods------------------
public static long pow(long x, long n, long mod) {
long res = 1;
x %= mod;
while (n > 0) {
if (n % 2 == 1) {
res = (res * x) % mod;
}
x = (x * x) % mod;
n /= 2;
}
return res;
}
public static boolean isPal(String s) {
for (int i = 0, j = s.length() - 1; i <= j; i++, j--) {
if (s.charAt(i) != s.charAt(j))
return false;
}
return true;
}
public static String rev(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static int gcd(int x, int y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long gcdExtended(long a, long b, long[] x) {
if (a == 0) {
x[0] = 0;
x[1] = 1;
return b;
}
long[] y = new long[2];
long gcd = gcdExtended(b % a, a, y);
x[0] = y[1] - (b / a) * y[0];
x[1] = y[0];
return gcd;
}
public static int abs(int a, int b) {
return (int) Math.abs(a - b);
}
public static long abs(long a, long b) {
return (long) Math.abs(a - b);
}
public static int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
public static int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
public static long max(long a, long b) {
if (a > b)
return a;
else
return b;
}
public static long min(long a, long b) {
if (a > b)
return b;
else
return a;
}
// ---------------Extra Methods------------------
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine() {
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public char nextChar() {
return next().charAt(0);
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n, int f) {
if (f == 0) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
} else {
int[] arr = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextInt();
}
return arr;
}
}
public long[] nextLongArray(int n, int f) {
if (f == 0) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
} else {
long[] arr = new long[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextLong();
}
return arr;
}
}
public double[] nextDoubleArray(int n, int f) {
if (f == 0) {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
} else {
double[] arr = new double[n + 1];
for (int i = 1; i < n + 1; i++) {
arr[i] = nextDouble();
}
return arr;
}
}
}
static class Pair implements Comparable<Pair> {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.a != o.a)
return Integer.compare(this.a, o.a);
else
return Integer.compare(this.b, o.b);
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 92d405d90280ad630129c0729e856243 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
import java.util.StringTokenizer;
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);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
}
class Task {
static int MAX = 1000;
int[] v;
int[] e;
int[] p;
List<List<Vect>> g = new ArrayList<>();
boolean used[];
public void solve(Scanner in, PrintWriter out) {
int n = in.nextInt();
used = new boolean[n];
Arrays.fill(used, false);
v = new int[n];
p = new int[n];
e = new int[n];
for (int i = 0; i < n; i++) {
v[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
g.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
p[i + 1] = in.nextInt() - 1;
e[i + 1] = in.nextInt();
g.get(p[i + 1]).add(new Vect(i + 1, e[i+1]));
}
dfs(0, 0, 0);
System.out.println(res);
}
int res = 0;
void dfs(int k, long pot, long d) {
List<Vect> children = g.get(k);
if (used[k]) {
for (Vect vect : children) {
used[vect.a] = true;
res++;
dfs(vect.a, -1, -1);
}
return;
}
for (Vect c : children) {
if (d + c.b - pot > v[c.a]) {
used[c.a] = true;
res++;
}
dfs(c.a, Math.min(pot, d + c.b), d + c.b);
}
}
}
class Utils {
public static int binarySearch(int[] a, int key) {
int s = 0;
int f = a.length;
while (f > s) {
int mid = (s + f) / 2;
if (a[mid] > key) {
f = mid - 1;
} else if (a[mid] <= key) {
s = mid + 1;
}
}
return -1;
}
}
class Pair<T, U> {
public T a;
public U b;
public Pair(T a, U b) {
this.a = a;
this.b = b;
}
@Override
public boolean equals(Object obj) {
Pair<T, U> p = (Pair<T, U>) obj;
return p.a.equals(a) || p.a.equals(b);
}
@Override
public int hashCode() {
return 42;
}
}
class Vect {
public int a;
public int b;
public Vect(int a, int b) {
this.a = a;
this.b = b;
}
}
class Triple<T, U, P> {
public T a;
public U b;
public P c;
public Triple(T a, U b, P c) {
this.a = a;
this.b = b;
this.c = c;
}
}
class Scanner {
BufferedReader in;
StringTokenizer tok;
public Scanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
tok = new StringTokenizer("");
}
private String tryReadNextLine() {
try {
return in.readLine();
} catch (Exception e) {
throw new InputMismatchException();
}
}
public String nextToken() {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(next());
}
return tok.nextToken();
}
public String next() {
String newLine = tryReadNextLine();
if (newLine == null)
throw new InputMismatchException();
return newLine;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
} | Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 95e61ee81289f9e7cfeac3a2ce4b1156 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n = sc.nextInt();
V[] vs = new V[n];
for (int i = 0; i < n; i++) {
vs[i] = new V();
vs[i].id = i + 1;
}
for (int i = 0; i < n; i++) {
vs[i].a = sc.nextInt();
}
for (int i = 1; i < n; i++) {
int parent = sc.nextInt() - 1;
int cost = sc.nextInt();
vs[parent].add(vs[i], cost);
}
ans = 0;
dfs(vs[0], 0, false);
out.println(ans);
}
int ans = 0;
void dfs(V v, long dist, boolean inf) {
if (dist > v.a || inf) {
ans++;
// tr(v.id);
inf = true;
}
for (E e : v.es) {
dfs(e.to, Math.max(0, dist) + e.w, inf);
}
}
class V {
ArrayList<E> es = new ArrayList<E>();
int id;
long a;
void add(V to, int w) {
this.es.add(new E(to, w));
}
}
class E {
V to;
int w;
E(V to, int w) {
this.to = to;
this.w = w;
}
}
static void tr(Object... os) { System.err.println(deepToString(os)); }
static void tr(int[][] as) { for (int[] a : as) tr(a); }
void print(int[] a) {
out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
} | Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 1a4b1fd2c5054f8b17b7134d7de3dd8d | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
Node[] tree = input(in);
int left = dfs2(tree[1], 0);
int result = tree.length - 1 - left;
out.print(result);
}
private int dfs2(Node cur, long curLen) {
int subtreeSize = 1;
for (Edge e : cur.children) {
subtreeSize += dfs2(e.second, Math.max(e.number, curLen + e.number));
}
if (cur.number < curLen) {
subtreeSize = 0;
}
return subtreeSize;
}
private void dfs(Node current) {
Node parent = current.parent;
List<Edge> edges = new ArrayList<>(current.children);
current.children.clear();
for (Edge e : edges) {
Node to = e.second;
if (to != parent) {
to.parent = current;
current.children.add(new Edge(current, to, e.number));
dfs(to);
}
}
}
private Node[] input(InputReader in) {
int n = in.readInt();
Node[] tree = new Node[n + 1];
for (int i = 1; i <= n; i++) {
tree[i] = new Node(i, in.readInt());
}
for (int i = 2; i <= n; i++) {
int p = in.readInt();
int c = in.readInt();
tree[p].children.add(new Edge(tree[p], tree[i], c));
tree[i].children.add(new Edge(tree[i], tree[p], c));
}
dfs(tree[1]);
return tree;
}
}
static class Edge {
public final Node first;
public final Node second;
public final long number;
public Edge(Node first, Node second, long number) {
this.first = first;
this.second = second;
this.number = number;
}
public String toString() {
return second.index + " " + number;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
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 Node {
public final int index;
public Node parent;
public final List<Edge> children = new ArrayList<>();
public final int number;
public Node(int index, int number) {
this.index = index;
this.number = number;
}
public String toString() {
return index + " " + number;
}
}
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 print(int i) {
writer.print(i);
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | d65d193b52b543de5886fb3b99dbecb5 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.Scanner;
import java.util.HashMap;
public class Tester {
static Node[] node;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
node = new Node[n];
for(int i=0;i<n;i++){
node[i] = new Node(scan.nextLong());
}
for(int i=0;i<n-1;i++){
int t = scan.nextInt();
node[t-1].edge.put(i+1,scan.nextLong());
}
df(node[0]);
System.out.println(f(node[0],0));
}
private static int f(Node n, long t) {
int c = 0;
if(t>n.a)
return n.c;
for(int i:n.edge.keySet()){
long total = t + n.edge.get(i);
if(total>0)
c = c + f(node[i],total);
else
c = c + f(node[i],0);
}
return c;
}
public static void df(Node n){
int c = 1;
for(int i:n.edge.keySet()){
df(node[i]);
c += node[i].c;
}
n.c = c;
}
public static class Node {
long a=0;
HashMap<Integer,Long> edge = new HashMap<Integer,Long>();
int c=0;
public Node(long a){
this.a = a;
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | fbb2e58776c7ca0246028b395725b788 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
/**
* Hello world!
*
*/
public class App {
private static List<List<Integer>> tree;
private static int[] degree;
private static Map<Long, Long> edges = new HashMap<>();
private static long[] weight;
private static long cnt = 0;
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String[] line;
line = reader.readLine().split(" ");
int n = Integer.parseInt(line[0]);
tree = new ArrayList<>(n + 1);
degree = new int[n + 1];
weight = new long[n + 1];
for (int i = 0; i < n + 1; ++i) {
tree.add(new ArrayList<>());
}
line = reader.readLine().split(" ");
for (int i = 0; i < line.length; ++i) {
weight[i + 1] = Integer.parseInt(line[i]);
}
for (int i = 0; i < n - 1; ++i) {
line = reader.readLine().split(" ");
int u = i + 2;
int v = Integer.parseInt(line[0]);
long c = Integer.parseInt(line[1]);
tree.get(u).add(v);
tree.get(v).add(u);
edges.put((long)u << 32 | v, c);
edges.put((long)v << 32 | u, c);
degree[u]++;
degree[v]++;
}
tree.get(1).add(0);
dfs(1, 0, 0, false);
System.out.println(cnt);
}
}
private static void dfs(int curr, int parent, long pathSum, boolean delete) {
pathSum += edges.getOrDefault((long) curr << 32 | parent, 0l);
pathSum = Math.max(0, pathSum);
delete = delete || weight[curr] < pathSum;
for (int child : tree.get(curr)) {
if (child != parent) {
dfs(child, curr, pathSum, delete);
}
}
if (delete) {
cnt++;
--degree[parent];
--degree[curr];
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 07c4d19706bbd789dd85d372dbd88c86 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.io.*;
//import java.lang.*;
public class ranjan{
public static Read cin;
public static PrintWriter cout;
public static boolean[] visited;
public static final long b = (long)1e9+7;
public static int fileread = 0;
public static void main(String ...arg) throws IOException
{
/*console writer*/
cout = new PrintWriter(new BufferedOutputStream(System.out));
/*Debug Reader*/
//Scan cin =new Scan();
if(fileread == 1)
{
try
{
cin = new Read(new FileInputStream(new File("in3.txt")));
//cin = new InputReader(new FileInputStream(new File("in3.txt")));
}
catch (IOException error){}
}
else{
cin = new Read(System.in);
//cin = new InputReader(System.in);
}
int n = cin.nextInt();
int[] a = new int[n+1];
for(int i=1;i<=n;i++)
a[i] = cin.nextInt();
ArrayList<Integer>[] tree = new ArrayList[n+1];
ArrayList<Integer>[] weight = new ArrayList[n+1];
visited = new boolean[n+1];
for(int i=0;i<=n;i++)
{
tree[i] = new ArrayList<Integer>();
weight[i] = new ArrayList<Integer>();
}
for(int i=2;i<=n;i++)
{
int x = cin.nextInt();
int y = cin.nextInt();
tree[i].add(x);
tree[x].add(i);
weight[x].add(y);
weight[i].add(y);
}
//cout.print(Arrays.toString(tree)+"\n");
//cout.print(Arrays.toString(weight)+"\n");
cout.print(dfs(tree,weight,1,(int)-1e9,a));
cout.close();
}
public static int nodeCounter(ArrayList<Integer>[] tree,ArrayList<Integer>[] weight,int parent)
{
visited[parent] = true;
int ans = 1;
for(int i=0;i<tree[parent].size();i++)
{
int child = (int)tree[parent].get(i);
if(!visited[child])
{
ans += nodeCounter(tree,weight,child);
}
}
return ans;
}
public static int dfs(ArrayList<Integer>[] tree,ArrayList<Integer>[] weight,int parent,int cost,int[] a)
{
visited[parent] = true;
int ans = 0;
if(a[parent] < cost)
{
ans += nodeCounter(tree,weight,parent);
return ans;
}
for(int i=0;i<tree[parent].size();i++)
{
int child = (int)tree[parent].get(i);
if(!visited[child])
{
int pathCost = weight[parent].get(i);
ans += dfs(tree,weight,child,Math.max(cost+pathCost,pathCost),a);
}
}
return ans;
}
public static long mod_pow(long x,long n,long mod) {
long res=1;
while(n>0) {
if((n&1)==1)res=res*x%mod;
x=x*x%mod;
n>>=1;
}
return res;
}
static class InputReader {
final InputStream is;
final byte[] buf = new byte[1024];
int pos;
int size;
public InputReader(InputStream is) {
this.is = is;
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = read();
} while (!isWhitespace(c));
return res * sign;
}
int read() {
if (size == -1)
throw new InputMismatchException();
if (pos >= size) {
pos = 0;
try {
size = is.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (size <= 0)
return -1;
}
return buf[pos++] & 255;
}
static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class RecursionLimiter {
public static long maxLevel = 1549;
public static void emerge() {
if (maxLevel == 0)
return;
try {
throw new IllegalStateException("Too deep, emerging");
} catch (IllegalStateException e) {
if (e.getStackTrace().length > maxLevel + 1)
throw e;
}
}
}
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
}
class Read
{
private BufferedReader br;
private StringTokenizer st;
public Read(InputStream is)
{ br = new BufferedReader(new InputStreamReader(is)); }
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 3438f0d74d1da6aa0d8eaed52c44ffc3 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.io.*;
//import java.lang.*;
public class ranjan{
//public static Read cin;
public static InputReader cin;
public static PrintWriter cout;
public static boolean[] visited;
public static final long b = (long)1e9+7;
public static int fileread = 0;
public static void main(String ...arg) throws IOException
{
/*console writer*/
cout = new PrintWriter(new BufferedOutputStream(System.out));
/*Debug Reader*/
//Scan cin =new Scan();
if(fileread == 1)
{
try
{
//cin = new Read(new FileInputStream(new File("in3.txt")));
cin = new InputReader(new FileInputStream(new File("in3.txt")));
}
catch (IOException error){}
}
else{
//cin = new Read(System.in);
cin = new InputReader(System.in);
}
int n = cin.nextInt();
int[] a = new int[n+1];
for(int i=1;i<=n;i++)
a[i] = cin.nextInt();
ArrayList<Integer>[] tree = new ArrayList[n+1];
ArrayList<Integer>[] weight = new ArrayList[n+1];
visited = new boolean[n+1];
for(int i=0;i<=n;i++)
{
tree[i] = new ArrayList<Integer>();
weight[i] = new ArrayList<Integer>();
}
for(int i=2;i<=n;i++)
{
int x = cin.nextInt();
int y = cin.nextInt();
tree[i].add(x);
tree[x].add(i);
weight[x].add(y);
weight[i].add(y);
}
//cout.print(Arrays.toString(tree)+"\n");
//cout.print(Arrays.toString(weight)+"\n");
cout.print(dfs(tree,weight,1,(int)-1e9,a));
cout.close();
}
public static int nodeCounter(ArrayList<Integer>[] tree,ArrayList<Integer>[] weight,int parent)
{
visited[parent] = true;
int ans = 1;
for(int i=0;i<tree[parent].size();i++)
{
int child = (int)tree[parent].get(i);
if(!visited[child])
{
ans += nodeCounter(tree,weight,child);
}
}
return ans;
}
public static int dfs(ArrayList<Integer>[] tree,ArrayList<Integer>[] weight,int parent,int cost,int[] a)
{
visited[parent] = true;
int ans = 0;
if(a[parent] < cost)
{
ans += nodeCounter(tree,weight,parent);
return ans;
}
for(int i=0;i<tree[parent].size();i++)
{
int child = (int)tree[parent].get(i);
if(!visited[child])
{
int pathCost = weight[parent].get(i);
ans += dfs(tree,weight,child,Math.max(cost+pathCost,pathCost),a);
}
}
return ans;
}
public static long mod_pow(long x,long n,long mod) {
long res=1;
while(n>0) {
if((n&1)==1)res=res*x%mod;
x=x*x%mod;
n>>=1;
}
return res;
}
static class InputReader {
final InputStream is;
final byte[] buf = new byte[1024];
int pos;
int size;
public InputReader(InputStream is) {
this.is = is;
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = res * 10 + c - '0';
c = read();
} while (!isWhitespace(c));
return res * sign;
}
int read() {
if (size == -1)
throw new InputMismatchException();
if (pos >= size) {
pos = 0;
try {
size = is.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (size <= 0)
return -1;
}
return buf[pos++] & 255;
}
static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class RecursionLimiter {
public static long maxLevel = 1549;
public static void emerge() {
if (maxLevel == 0)
return;
try {
throw new IllegalStateException("Too deep, emerging");
} catch (IllegalStateException e) {
if (e.getStackTrace().length > maxLevel + 1)
throw e;
}
}
}
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
}
class Read
{
private BufferedReader br;
private StringTokenizer st;
public Read(InputStream is)
{ br = new BufferedReader(new InputStreamReader(is)); }
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 3d495006e38e64a5f917338b0f22b4c9 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.io.*;
public class gfg {
public static void main(String[] args) throws IOException{
//Reader.init(System.in);
//PrintWriter out = new PrintWriter(System.out);
Reader.init(System.in);
int t = 1;//Reader.nextInt();
while(t-->0){
solve();
}
//out.close();
}
static ArrayList<int[]>[] graph;
//static ArrayList<Integer>[] set;
static int n=0;
static int m=0;
static boolean[][] vis;
//static char[][] arr;
static long mod =1000000007;
static int min=-1;
//static ArrayList<int[]> list ;
static int[] s;
static int[] a;
static boolean invalid=false;
static int[] dx = {0,0,-1,1};
static int[] dy = {1,-1,0,0};
static int count=0;
static int edges=0;
static char[][] arr;
static boolean[][] reached;
static int[] v;
static void solve()throws IOException{
n =Reader.nextInt();
graph = new ArrayList[n+1];
for(int i=1;i<=n;i++)
graph[i] = new ArrayList<int[]>();
v = new int[n+1];
for(int i=1;i<=n;i++){
v[i] = Reader.nextInt();
}
for(int i=1;i<=n-1;i++){
int a = Reader.nextInt();
int c = Reader.nextInt();
int[] arr1 = {a,c};
int[] arr2 = {i+1,c};
graph[i+1].add(arr1);
graph[a].add(arr2);
}
count=1;
dfs(1,-1,0,1000000003);
System.out.println(n-count);
}
static void dfs(int a,int p, long path,long min){ // u[ar = false means upar edge h;
for(int[] arr: graph[a]){
int b = arr[0];
int c = arr[1];
long temp = path+c;
if(b!=p){
min = Math.min(path,min);
if(temp-min<=v[b]){
count++;
dfs(b,a,temp,min);
}
}
}
}
// ggratest common divisor
static int gcd(int a , int b){
if(b==0)
return a;
else
return gcd(b,a%b);
}
// least common multiple
static int lcm(int a, int b){
return (a*b)/gcd(a,b);
}
// a^b
static long fastpow(long a, long b){
long res = 1;a=a%mod;
while(b>0){
if(b%2==1)
res = (res*a)%mod;
a = (a*a)%mod;
b = b>>1;
}
return res;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
class newcomparator implements Comparator<Integer>{
//@Override
public int compare(Integer a, Integer b){
return a<=b?1:-1;
}
}
class node {
int a;
long b;// cost to rreach\
node(int s,long va){
a=s;
b=va;
}
}
class mergesort{
static void sort(int l, int h, int[] arr){
if(l<h){
int mid = (l+h)/2;
sort(l,mid,arr);
sort(mid+1,h,arr);
merge(l,mid,h,arr);
}
}
static void merge(int l, int m , int h , int [] arr){
int[] left = new int[m-l+1];
int[] right = new int[h-m];
for(int i= 0 ;i< m-l+1;i++){
left[i] = arr[l+i];
}
for(int i=0;i<h-m;i++){
right[i] = arr[m+1+i];
}
//now left and right arrays are assumed to be sorted and we have tp merge them together
// int the original aaray.
int i=l;
int lindex = 0;
int rindex = 0;
while(lindex<m-l+1 && rindex<h-m){
if(left[lindex]<=right[rindex]){
arr[i]=left[lindex];
lindex++;
i++;
}
else{
arr[i]=right[rindex];
rindex++;
i++;
}
}
while(lindex<m-l+1){
arr[i]=left[lindex];
lindex++;
i++;
}
while(rindex<h-m){
arr[i]=right[rindex];
rindex++;
i++;
}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 74262f747629e6ab512eb9881b63eacc | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.io.*;
public class pt{
static class Edge{
int s,d,w;
Edge(int S,int D,int W)
{ s=S ; d = D; w = W;}
}
static void dfs(LinkedList<Edge> l[],int s,int p,int sz[]){
for(Edge e : l[s])
if(e.d!=p){
dfs(l,e.d,s,sz);
sz[s] = sz[s]+sz[e.d];
}
}
static int ans=0;
static void dfs1(LinkedList<Edge> l[],int s,int p,int a[],int sz[],long dist){
for(Edge e : l[s])
if(e.d!=p){
if(Math.max((dist+e.w),e.w)>a[e.d])
ans = ans+sz[e.d];
else
dfs1(l,e.d,s,a,sz,Math.max((dist+e.w),e.w));
}
}
public static void main(String[] args)throws IOException {
PrintWriter out = new PrintWriter(System.out);
int n = ni();
int a[] = new int[n];
LinkedList<Edge> l[] = new LinkedList[n];
int sz[] = new int[n];
for(int i=0;i<n;i++)
a[i] = ni();
for(int i=0;i<n;i++)
l[i] = new LinkedList();
Arrays.fill(sz,1);
for(int i=1;i<n;i++){
int v = ni()-1;
int c = ni();
Edge e1 = new Edge(i,v,c);
Edge e2 = new Edge(v,i,c);
l[i].add(e1);
l[v].add(e2);
}
dfs(l,0,-1,sz);
dfs1(l,0,-1,a,sz,0);
out.println(ans);
out.flush();
}
static FastReader sc=new FastReader();
static int ni(){
int x = sc.nextInt();
return(x);
}
static long nl(){
long x = sc.nextLong();
return(x);
}
static String n(){
String str = sc.next();
return(str);
}
static String ns(){
String str = sc.nextLine();
return(str);
}
static double nd(){
double d = sc.nextDouble();
return(d);
}
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 91380e14c0a4ec0eab107630f5de8106 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class WorkFile {
public static int[] dfs(long[] array, ArrayList<int[]>[] tree,
int item, int prev, long path, long minpath) {
int result = 0, amount = 1;
for (int[] elem:tree[item]) {
int x = elem[0], len = elem[1];
if (x==prev) continue;
long newpath = path+len;
long newminpath = Math.min(minpath, newpath);
int[] list = dfs(array, tree, x, item, newpath, newminpath);
result+=list[0]; amount+=list[1];
}
if (path-minpath>array[item]) result = amount;
return new int[]{result, amount};
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
long[] array = new long[n];
ArrayList<int[]>[] tree = new ArrayList[n];
for (int i=0; i<n; i++) {
array[i] = s.nextInt();
tree[i] = new ArrayList<int[]>();
}
for (int i=1; i<n; i++) {
int x = s.nextInt()-1, len = s.nextInt();
tree[i].add(new int[]{x, len});
tree[x].add(new int[]{i, len});
}
System.out.println(dfs(array, tree, 0, -1, 0, 0)[0]);
}
} | Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 8f01b544d87c777d5d7924813bfc4e74 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
public class Main7
{
static class Pair
{
int x;
int y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
static int mod=1000000007;
public static int[] sort(int[] a)
{
int n=a.length;
ArrayList<Integer> ar=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
ar.add(a[i]);
}
Collections.sort(ar);
for(int i=0;i<n;i++)
{
a[i]=ar.get(i);
}
return a;
}
public static long pow(long a, long b)
{
long result=1;
while(b>0)
{
if (b % 2 != 0)
{
result=(result*a);
b--;
}
a=(a*a);
b /= 2;
}
return result;
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static long lcm(long a, long b)
{
return a*(b/gcd(a,b));
}
static ArrayList<ArrayList<Pair>> graph;
static public void main(String args[])throws IOException
{
int tt=1;
StringBuilder sb=new StringBuilder();
for(int ttt=1;ttt<=tt;ttt++)
{
int n=i();
int[] a=new int[n];
graph=new ArrayList<>();
for(int i=0;i<n;i++)
{
graph.add(new ArrayList<>());
a[i]=i();
}
int[] parent=new int[n-1];
int[] edge=new int[n-1];
for(int i=0;i<n-1;i++)
{
parent[i]=i()-1;
edge[i]=i();
graph.get(i+1).add(new Pair(parent[i],edge[i]));
graph.get(parent[i]).add(new Pair(i+1,edge[i]));
}
boolean[] visited=new boolean[n];
subtree=new int[n];
dfs1(0,visited);
visited=new boolean[n];
ans=0;
dfs(0,visited,0,a);
sb.append(ans+"\n");
}
System.out.print(sb.toString());
}
static int[] subtree;
static void dfs1(int src, boolean[] visited)
{
visited[src]=true;
subtree[src]=1;
ArrayList<Pair> ar=graph.get(src);
for(int i=0;i<ar.size();i++)
{
int num=ar.get(i).x;
if(visited[num]==false)
{
dfs1(num,visited);
subtree[src]+=subtree[num];
}
}
}
static int ans=0;
static void dfs(int src, boolean[] visited,long dis,int[] a)
{
if(dis>a[src])
{
ans+=subtree[src];
visited[src]=true;
return;
}
visited[src]=true;
ArrayList<Pair> ar=graph.get(src);
for(int i=0;i<ar.size();i++)
{
int num=ar.get(i).x;
long edge=ar.get(i).y;
if(visited[num]==false)
{
if(dis<0)
dis=0;
dfs(num,visited,edge+dis,a);
}
}
}
/**/
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
public static long l()
{
String s=in.String();
return Long.parseLong(s);
}
public static void pln(String value)
{
System.out.println(value);
}
public static int i()
{
return in.Int();
}
public static String s()
{
return in.String();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars== -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 884a12ae65a570206991a293db347a8b | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class dfs
{
static int n;
static LinkedList<Integer> adj[];
static HashMap<String, Integer> hm;
static int counter;
static int vis[];
static int arr[];
static int problem[];
static Set<Integer> hs;
public static void dfs(int pos,int activate,long sum)
{
vis[pos]=1;
if(activate==1)
{
counter++;
}
if(activate!=1)
{
for(int i : adj[pos])
{
if(vis[i]==-1)
{
if((Math.max(hm.get(pos+"$"+i),sum+hm.get(pos+"$"+i))>arr[i]))
dfs(i,1,Math.max(hm.get(pos+"$"+i),sum+hm.get(pos+"$"+i)));
else
dfs(i,0,Math.max(hm.get(pos+"$"+i),sum+hm.get(pos+"$"+i)));
}
}
}
else
{
for(int i : adj[pos])
{
if(vis[i]==-1)
{
dfs(i,1,sum);
}
}
}
}
public static void main(String args[])throws IOException
{
counter=0;
Reader sc=new Reader();
n =sc.nextInt();
adj = new LinkedList[n];
hm= new HashMap<String, Integer>();
vis=new int[n];
hs = new HashSet<Integer>();
arr=new int[n];
Arrays.fill(vis,-1);
for (int i=0; i<n; ++i)
adj[i] = new LinkedList();
for(int i = 0 ;i<n;i++)
arr[i]=sc.nextInt();
for(int i = 1;i<n;i++)
{
int u = sc.nextInt();
int value= sc.nextInt();
u--;
hm.put(u+"$"+i,value);
hm.put(i+"$"+u,value);
adj[i].add(u);
adj[u].add(i);
}
dfs(0,0,0);
System.out.println(counter);
}
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 5e4c9c4a9598d322453cee5cf18d84a8 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.*;
import java.util.*;
public class C
{
public static long[] dp;
public static ArrayList<ArrayList<Edge>> g;
public static int cnt = 0;
public static void dfs(int u, int par, long minSoFar, long sumSoFar, boolean fail)
{
if(dp[u] < (sumSoFar - minSoFar) || fail == true) {
fail = true;
cnt++;
//out.println(u);
}
for(Edge i : g.get(u)) {
int v = i.v;
long w = i.w;
//out.println(u + " " + v + " " + w);
if(v == par)
continue;
dfs(v, u, Math.min(minSoFar, sumSoFar + w), sumSoFar + w, fail);
}
}
public static void main(String[] args)
{
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n;
n = sc.nextInt();
dp = new long[n + 1];
for(int i = 1; i <= n; i++) {
dp[i] = sc.nextInt();
}
g = new ArrayList<ArrayList<Edge>>();
for(int i = 0; i <= n; i++)
g.add(new ArrayList<Edge>());
for(int i = 2; i <= n; i++) {
int v = sc.nextInt(), w = sc.nextInt();
g.get(i).add(new Edge(v, w));
g.get(v).add(new Edge(i, w));
}
dfs(1, -1, 0, 0, false);
out.println(cnt);
out.close();
}
public static class Edge {
public int v;
long w;
public Edge(int v, long w) {
this.v = v;
this.w = w;
}
}
// PrintWriter for faster output
public static PrintWriter out;
// MyScanner class for faster input
public static class MyScanner
{
BufferedReader br;
StringTokenizer st;
public MyScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
boolean hasNext()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return false;
}
}
return true;
}
String next()
{
if (hasNext())
return st.nextToken();
return null;
}
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | b2ce63e5e3f5bfd4dbc0ceaa120e0407 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
public class C {
static class N implements Comparable<N> {
int n;
int cost;
N(int i, int x) {
this.n = i;
this.cost = x;
}
@Override
public int compareTo(N o) {
return -Integer.compare(n, o.n);
}
}
static LinkedList<N> tree[];
static int a[];
static int childs[];
static int DFS(int p, N curr) {
childs[curr.n] = 1;
for (N x : tree[curr.n]) {
if (x.n != p)
childs[curr.n] += DFS(curr.n, x);
}
return childs[curr.n];
}
static int ans = 0;
static void DFS(int p, N curr, long minSum, long currSum) {
currSum += (long) curr.cost;
if (currSum < 0)
currSum = 0;
minSum = Math.min(currSum, minSum);
if (currSum - minSum > a[curr.n]) {
ans += childs[curr.n];
return;
}
for (N x : tree[curr.n]) {
if (x.n != p)
DFS(curr.n, x, minSum, currSum);
}
}
public static void main(String[] args) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bf.readLine());
String l[] = bf.readLine().split(" ");
a = new int[n];
childs = new int[n];
tree = new LinkedList[n];
for (int i = 0; i < l.length; i++) {
a[i] = Integer.parseInt(l[i]);
tree[i] = new LinkedList<C.N>();
}
int a, c;
for (int i = 1; i < n; i++) {
l = bf.readLine().split(" ");
a = Integer.parseInt(l[0]) - 1;
c = Integer.parseInt(l[1]);
tree[i].add(new N(a, c));
tree[a].add(new N(i, c));
}
DFS(-1, new N(0, 0));
DFS(-1, new N(0, 0), 0, 0);
System.out.println(ans);
}
} | Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | e0df690391dfe4c10ce87dceb9491de2 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | /*
* Code Author: Akshay Miterani
* DA-IICT
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static double eps=(double)1e-7;
static long mod=(int)1e9+7;
public static void main(String args[]){
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
//---------------------------------------
int n=in.nextInt();
int a[]=new int[n+1];
for(int i=1;i<=n;i++){
a[i]=in.nextInt();
}
ArrayList<ArrayList<Integer>> arr=new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Long>> cost=new ArrayList<ArrayList<Long>>();
for(int i=0;i<=n;i++){
arr.add(new ArrayList<Integer>());
cost.add(new ArrayList<Long>());
}
for(int i=2;i<=n;i++){
int p=in.nextInt();
int c=in.nextInt();
arr.get(i).add(p);
cost.get(i).add((long)c);
arr.get(p).add(i);
cost.get(p).add((long)c);
}
//int count=0;
boolean vis[]=new boolean[n+1];
Queue<Pair> q=new LinkedList<>();
Stack<Long> h=new Stack<Long>();
q.add(new Pair(1,0));
while(!q.isEmpty()){
Pair rem=q.remove();
if(vis[(int)rem.u]){
continue;
}
//System.out.println(rem.u+" "+rem.v+" "+rem.flag+" "+a[(int)rem.u]);
vis[(int)rem.u]=true;
if((rem.v>a[(int)rem.u] || rem.flag)){
//System.out.println(rem.u);
for(int i=0;i<arr.get((int)rem.u).size();i++){
if(!vis[arr.get((int)rem.u).get(i)]){
Pair add=new Pair(arr.get((int)rem.u).get(i),(rem.v>0?rem.v:0)+cost.get((int)rem.u).get(i));
add.flag=true;
q.add(add);
}
}
}
else{
h.add(rem.u);
for(int i=0;i<arr.get((int)rem.u).size();i++){
if(!vis[arr.get((int)rem.u).get(i)]){
Pair add=new Pair(arr.get((int)rem.u).get(i),(rem.v>0?rem.v:0)+cost.get((int)rem.u).get(i));
q.add(add);
}
}
}
}
out.println(n-h.size());
out.close();
//---------------The End------------------
}
static class Pair implements Comparable<Pair> {
long u;
long v;
boolean flag=false;
public Pair(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine(){
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine=reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
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());
}
}
} | Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 9013d385639d0279545a1c30f4d5e66e | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.*;
import java.util.*;
public class C682
{
int id,wt;
static int cou[],arr[];static long dist[];static boolean vis[];
static HashSet<Integer> set=new HashSet<>();
static HashMap<Integer,ArrayList<C682>> map=new HashMap<>();
//static List<Integer> neg=new ArrayList<>();
public C682(int i,int w)
{
this.id=i;
this.wt=w;
}
static int dfs(int ind,int par,int w)
{
vis[ind]=true;
dist[ind]=dist[par]+w;
if(dist[ind]>=0)
{
if(dist[ind]>arr[ind])
set.add(ind);
}
else
{
//neg.add(ind);
dist[ind]=0;
}
int c=1;
for(C682 ob:map.get(ind))
{
if(!vis[ob.id])
{
c+=dfs(ob.id,ind,ob.wt);
}
}
cou[ind]=c;
return c;
}
public static void main(String args[])throws IOException
{
Reader sc=new Reader();
int n=sc.nextInt();
arr=new int[n+1];
//neg.add(1);
//int par[]=new int[n+1];
//HashMap<Integer,ArrayList<C682>> map=new HashMap<>();
for(int i=1;i<=n;i++)
{
arr[i]=sc.nextInt();
map.put(i,new ArrayList<>());
}
for(int i=1;i<n;i++)
{
int x=sc.nextInt();
int w=sc.nextInt();
map.get(i+1).add(new C682(x,w));
map.get(x).add(new C682(i+1,w));
}
cou=new int[n+1];
dist=new long[n+1];
vis=new boolean[n+1];
dfs(1,0,0);
vis=new boolean[n+1];
for(int i:set)
{
vis[i]=true;
}
int q[]=new int[n+1];
q[0]=1;int back=0,front=1;
vis[1]=true;int c=0;
while(back!=front)
{
int a=q[back];back++;c++;
//System.out.println(a);
for(C682 ob:map.get(a))
{
if(!vis[ob.id])
{
q[front++]=ob.id;
vis[ob.id]=true;
}
}
}
System.out.println(n-c);
}
}
//import java.io.*;
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[1024];
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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 4171499b7b791f21e0570ace43614cf4 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class C extends cf {
public static void main(String[] args) {C c=new C();}
public void run(InputReader in, PrintWriter out) {
int n=in.nextInt(),ans=0,v,p,c,newd;
int[] a=new int[n+1],d=new int[n+1];
List<Map<Integer,Integer>> w=new ArrayList<Map<Integer,Integer>>();
List<List<Integer>> g=new ArrayList<List<Integer>>();
for (int i=1;i<=n;i++) {
a[i]=in.nextInt();
}
for (int i=0;i<=n;i++) {
g.add(new ArrayList<Integer>());
w.add(new HashMap<Integer,Integer>());
}
for (int i=2;i<=n;i++) {
p=in.nextInt();
c=in.nextInt();
g.get(i).add(p);
g.get(p).add(i);
w.get(i).put(p,c);
w.get(p).put(i,c);
}
boolean[] m=new boolean[n+1],mkd=new boolean[n+1];
Deque<Integer> st=new ArrayDeque<Integer>();
st.addFirst(1);
mkd[1]=true;
while (!st.isEmpty()) {
v=st.pollFirst();
for (int u:g.get(v)) {
if (!mkd[u]) {
mkd[u]=true;
newd=d[v]+w.get(v).get(u);
if (m[v]) {
m[u]=true;
ans++;
}
else if (a[u]>=newd) {
d[u]=Math.max(0,newd);
}
else {
m[u]=true;
ans++;
}
st.addFirst(u);
}
}
}
out.print(ans);
}
}
class cf {
public cf() {
try {
InputStream inputStream=System.in;
OutputStream outputStream=System.out;
//InputStream inputStream=new FileInputStream("file.in");
//OutputStream outputStream=new FileOutputStream("file.out");
InputReader in=new InputReader(inputStream);
PrintWriter out=new PrintWriter(outputStream);
run(in,out);
out.close();
} catch (Exception e) {
if (e instanceof FileNotFoundException) {System.out.print("File not found.");}
else {e.printStackTrace();}
}
}
public void run(InputReader in,PrintWriter out) {}
}
class InputReader {
private BufferedReader br;
private StringTokenizer st;
public InputReader(InputStream stream) {
br=new BufferedReader(new InputStreamReader(stream),32768);
st=null;
}
public String next() {
while (st==null||!st.hasMoreTokens()) {
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public int[] nextIntArray(int n) {
int[] a=new int[n];
for (int i=0;i<n;i++) {a[i]=nextInt();}
return a;
}
public long[] nextLongArray(int n) {
long[] a=new long[n];
for (int i=0;i<n;i++) {a[i]=nextLong();}
return a;
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 60568b8dea180b91c1d5fd019b2f31c4 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class AlyonaandtheTree {
static int V;
static long val[];
static ArrayList<Point>[] adjList;
static int solve(int u, int parent, long dist, boolean rem){
if(rem){
int ans = 1;
for (int i = 0; i < adjList[u].size(); i++) {
Point cur = adjList[u].get(i);
if(cur.x != parent)
ans += solve(cur.x, u, -1, true);
}
return ans;
}else{
int ans = 0;
for (int i = 0; i < adjList[u].size(); i++) {
Point cur = adjList[u].get(i);
if(cur.x != parent && val[cur.x] < dist + cur.y)
ans += solve(cur.x, u, -1, true);
else if(cur.x != parent)
ans += solve(cur.x, u, Math.max(0, dist + cur.y), false);
}
return ans;
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
V = sc.nextInt();
val = new long[V];
adjList = new ArrayList[V];
for (int i = 0; i < V; i++){
val[i] = sc.nextLong();
adjList[i] = new ArrayList<>();
}
for (int i = 1; i < V; i++)
adjList[sc.nextInt() - 1].add(new Point(i, sc.nextInt()));
out.println(solve(0, -1, 0, false));
out.flush();
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | a7be62de20cd18194e5530ca42fd3d19 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 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.*;
/**
* Created by yujiahao on 9/14/16.
*/
public class cf_358_c {
private FastScanner in;
private PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
long[] a = new long[n];
for (int i=0; i<n; i++) a[i] = in.nextLong();
ArrayList<ArrayList<pair_358>> graph = new ArrayList<ArrayList<pair_358>>();
for (int i=0; i<n; i++) graph.add(new ArrayList<pair_358>());
for (int i=1; i<=n-1; i++){
int p = in.nextInt()-1;
long c = in.nextInt();
pair_358 cur1 = new pair_358(p, c);
graph.get(i).add(cur1);
pair_358 cur2 = new pair_358(i, c);
graph.get(p).add(cur2);
}
int[] res = {0};
long[] min = {Integer.MAX_VALUE};
dfs(0, graph, res, 0L, min, a, -1);
out.print(n-res[0]);
}
void dfs(int idx, ArrayList<ArrayList<pair_358>> graph, int[] res, long dis, long[] min, long[] a, int pre){
long curA = a[idx];
if (dis<0) dis = 0;
if (dis - min[0] > curA) return;
min[0] = Math.min(min[0], dis);
res[0]++;
ArrayList<pair_358> neighbors = graph.get(idx);
for (pair_358 next : neighbors){
int nextP = next.p;
long nextC = next.c;
if (nextP == pre) continue;
dfs(nextP, graph, res, dis+nextC, min, a, idx);
}
return;
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
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 BigInteger nextBigInteger() { return new BigInteger(next());}
}
public static void main(String[] arg) {
new cf_358_c().run();
}
}
class pair_358 {
int p ;
long c ;
public pair_358(int p, long c){
this.p = p;
this.c = c;
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | c2a850e087a447de2a918e0325e18da8 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 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.*;
/**
* Created by yujiahao on 9/14/16.
*/
public class cf_358_c {
private FastScanner in;
private PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
long[] a = new long[n];
for (int i=0; i<n; i++) a[i] = in.nextLong();
ArrayList<ArrayList<pair_358>> graph = new ArrayList<ArrayList<pair_358>>();
for (int i=0; i<n; i++) graph.add(new ArrayList<pair_358>());
for (int i=1; i<=n-1; i++){
int p = in.nextInt()-1;
long c = in.nextInt();
pair_358 cur1 = new pair_358(p, c);
graph.get(i).add(cur1);
pair_358 cur2 = new pair_358(i, c);
graph.get(p).add(cur2);
}
int[] res = {0};
long min = Integer.MAX_VALUE;
dfs(0, graph, res, 0L, min, a, -1);
out.print(n-res[0]);
}
void dfs(int idx, ArrayList<ArrayList<pair_358>> graph, int[] res, long dis, long min, long[] a, int pre){
long curA = a[idx];
//if (dis<0) dis = 0;
if (dis - min > curA) return;
min = Math.min(min, dis);
res[0]++;
ArrayList<pair_358> neighbors = graph.get(idx);
for (pair_358 next : neighbors){
int nextP = next.p;
long nextC = next.c;
if (nextP == pre) continue;
dfs(nextP, graph, res, dis+nextC, min, a, idx);
}
return;
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
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 BigInteger nextBigInteger() { return new BigInteger(next());}
}
public static void main(String[] arg) {
new cf_358_c().run();
}
}
class pair_358 {
int p ;
long c ;
public pair_358(int p, long c){
this.p = p;
this.c = c;
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | c9691445bcceeb97f05549ab85bcf99b | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Luck{
public static InputReader sc;
public static PrintWriter out;
public static final long MOD = (long)1e9 + 7L;
static int n;
static ArrayList<Pair>[] adj;
static long[] A;
static long[] val;
static ArrayList<Integer> count=new ArrayList<Integer>();
static class Pair{
long cost;
int v;
Pair(int v,long cost){
this.cost=cost;
this.v=v;
}
}
public static void main(String[] args){
sc=new InputReader(System.in);
out=new PrintWriter(System.out);
n=sc.nextInt();
adj=new ArrayList[n+1];
A=new long[n+1];
val=new long[n+1];
Arrays.fill(val, 0L);
for(int i=1;i<=n;i++){
A[i]=sc.nextLong();
adj[i]=new ArrayList<Pair>();
}
for(int i=1;i<n;i++){
int p=sc.nextInt();
long cost=sc.nextLong();
adj[p].add(new Pair(i+1,cost));
}
count.add(1);
dfs(1);
out.println((n-count.size()));
//out.println(count);
//out.println(val[9]+" "+A[9]);
out.close();
}
static void dfs(int src){
if(val[src]<0L){
val[src]=0L;
}
for(Pair nei:adj[src]){
if(val[src]+nei.cost<=A[nei.v]){
val[nei.v]=val[src]+nei.cost;
count.add(nei.v);
dfs(nei.v);
}
}
}
static void insert(Node root,int item){
if(item<=root.data){
if(root.left==null){
root.left=new Node(item);
}
else{
insert(root.left,item);
}
}
else{
if(root.right==null){
root.right=new Node(item);
}
else{
insert(root.right,item);
}
}
}
static class Node{
int data;
Node left;
Node right;
Node(int data){
this.data=data;
left=null;
right=null;
}
}
// static class Pair{
// String x;
// int y;
// Pair(){
// this.x="";
// this.y=-1;
// }
// Pair(String profit,int val,int count){
// this.x=profit;
// this.y=val;
// }
// public static Comparator<Pair> Val=new Comparator<Pair>(){
// public int compare(Pair p1,Pair p2){
// if(p1.x==p2.y){
// return p1.y-p2.y;
// }
// return (int)p1.x-(int)p2.x;
// }
// };
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + x;
// result = prime * result + x;
// return result;
// }
// public boolean equals(Object obj){
// if (this == obj)
// return true;
// if (!(obj instanceof Pair)) {
// return false;
// }
//
// Pair p = (Pair) obj;
// if(p.x!=this.x){
// return false;
// }
// else if(p.y!=p.y){
// return false;
// }
// return true;
// }
// }
static class DisjointSet{
int n;
int[] par;
int[] rank;
DisjointSet(int n){
this.n=n;
this.par=new int[n];
this.rank=new int[n];
makeSet();
}
void makeSet(){
for(int i=0;i<n;i++){
par[i]=i;
rank[i]=1;
}
}
void union(int x,int y){
int parX=parent(x);
int parY=parent(y);
if(parX!=parY){
if(rank[parX]>=rank[parY]){
rank[parX]+=rank[parY];
rank[parY]=0;
par[parY]=parX;
}
else{
rank[parY]+=rank[parX];
rank[parX]=0;
par[parX]=parY;
}
}
}
int parent(int c){
int i=c;
while(i!=par[i]){
i=par[i];
}
return i;
}
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
static int lcm(int a,int b){
int g;
if(a<b){
g=gcd(b,a);
}
else{
g=gcd(a,b);
}
return (a*b)/g;
}
static boolean isPrime(int n){
if (n == 2)
return true;
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
static void shuffle(int[] A){
for(int i=A.length-1;i>0;i--){
int j=(int)(Math.random()*(i+1));
int temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
// public static class Node implements Comparable<Node>{
// int u;
// int v;
// public Node(){
// ;
// }
// public Node (int u, int v) {
// this.u = u;
// this.v = v;
// }
//
// public void print() {
// out.println(v + " " + u + " ");
// }
//
// public int compareTo(Node n1){
// return this.u-n1.u;
// }
// }
public static long power(long base,long exp,long mod){
if(exp==0){
return 1;
}
if(exp==1){
return base;
}
long temp=exp/2;
long val=power(base,temp,mod);
long result=val*val;
result=(result%mod);
long AND=exp&1;
if(AND==1){
result*=base;
result=(result%mod);
}
return result;
}
public static BigInteger pow(BigInteger base, BigInteger exp) {
if(exp.equals(new BigInteger(String.valueOf(0)))){
return new BigInteger(String.valueOf(1));
}
if(exp.equals(new BigInteger(String.valueOf(1))))
return base;
BigInteger temp=exp.divide(new BigInteger(String.valueOf(2)));
BigInteger val = pow(base, temp);
BigInteger result = val.multiply(val);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
BigInteger AND=exp.and(new BigInteger(String.valueOf(1)));
if(AND.equals(new BigInteger(String.valueOf(1)))){
result = result.multiply(base);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
}
return result;
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public 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 | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 73fca7db117aff8b8a9c836281dfa025 | train_000.jsonl | 1466181300 | Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,βu)β>βau, where au is the number written on vertex u, dist(v,βu) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertexΒ β root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove? | 256 megabytes | import java.util.*;
import java.io.*;
public class R682C {
FastScanner in;
PrintWriter out;
long ans=1;
ArrayList<Pair>[] v;
boolean[] used;
long[]a;
void solve() {
int n=in.nextInt();
v = new ArrayList[n];
used = new boolean[n];
for(int i=0; i<n; i++) {
v[i] = new ArrayList<>();
used[i] = false;
}
a = new long[n];
for(int i=0; i<n; i++)
a[i]=in.nextInt();
for(int i=1; i<n; i++) {
int u=in.nextInt()-1;
int d=in.nextInt();
v[i].add(new Pair(u, d));
v[u].add(new Pair(i, d));
}
used[0]=true;
get(0, 0);
System.out.println(n-ans);
}
void get(int u, long d) {
for(Pair p : v[u])
if (!used[p.n]) {
used[p.n]=true;
long dd=Math.max(d+p.a, p.a);
if (a[p.n]>=dd) {
ans++;
get(p.n, dd);
}
}
}
static class Pair {
public int n;
public int a;
public Pair(int n, int a) {
this.n = n;
this.a = a;
}
}
void run() {
try {
in = new FastScanner(new File("CF.in"));
out = new PrintWriter(new File("CF.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new R682C().runIO();
}
}
| Java | ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"] | 1 second | ["5"] | NoteThe following image represents possible process of removing leaves from the tree: | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | 0c4bc51e5be9cc642f62d2b3df2bddc4 | In the first line of the input integer n (1ββ€βnββ€β105) is givenΒ β the number of vertices in the tree. In the second line the sequence of n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) is given, where ai is the number written on vertex i. The next nβ-β1 lines describe tree edges: ith of them consists of two integers pi and ci (1ββ€βpiββ€βn, β-β109ββ€βciββ€β109), meaning that there is an edge connecting vertices iβ+β1 and pi with number ci written on it. | 1,600 | Print the only integerΒ β the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree. | standard output | |
PASSED | 8f9f413717965d2ae0692707ad864a82 | train_000.jsonl | 1339342200 | An oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.The root of vertex v of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex v moving along the edges of the weighted oriented forest. We denote the root of vertex v as root(v).The depth of vertex v is the sum of weights of paths passing from the vertex v to its root. Let's denote the depth of the vertex v as depth(v).Let's consider the process of constructing a weighted directed forest. Initially, the forest does not contain vertices. Vertices are added sequentially one by one. Overall, there are n performed operations of adding. The i-th (iβ>β0) adding operation is described by a set of numbers (k,ββv1,ββx1,ββv2,ββx2,ββ... ,ββvk,ββxk) and means that we should add vertex number i and k edges to the graph: an edge from vertex root(v1) to vertex i with weight depth(v1)β+βx1, an edge from vertex root(v2) to vertex i with weight depth(v2)β+βx2 and so on. If kβ=β0, then only vertex i is added to the graph, there are no added edges.Your task is like this: given the operations of adding vertices, calculate the sum of the weights of all edges of the forest, resulting after the application of all defined operations, modulo 1000000007 (109β+β7). | 256 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF195E extends PrintWriter {
CF195E() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF195E o = new CF195E(); o.main(); o.flush();
}
static final int MD = 1000000007;
int[] pp, ww;
int find(int i) {
int p = pp[i];
if (p == -1)
return i;
pp[i] = find(p);
ww[i] = (ww[i] + ww[p]) % MD;
return pp[i];
}
void main() {
int n = sc.nextInt();
pp = new int[n]; Arrays.fill(pp, -1);
ww = new int[n];
int ans = 0;
for (int i = 0; i < n; i++) {
int k = sc.nextInt();
while (k-- > 0) {
int j = sc.nextInt() - 1;
int x = sc.nextInt();
int r = find(j);
int w = (ww[j] + x) % MD;
pp[r] = i;
ww[r] = w;
ans = (ans + w) % MD;
}
}
if (ans < 0)
ans += MD;
println(ans);
}
}
| Java | ["6\n0\n0\n1 2 1\n2 1 5 2 2\n1 1 2\n1 3 4", "5\n0\n1 1 5\n0\n0\n2 3 1 4 3"] | 2 seconds | ["30", "9"] | NoteConside the first sample: Vertex 1 is added. kβ=β0, thus no edges are added. Vertex 2 is added. kβ=β0, thus no edges are added. Vertex 3 is added. kβ=β1. v1β=β2, x1β=β1. Edge from vertex root(2)β=β2 to vertex 3 with weight depth(2)β+βx1β=β0β+β1β=β1 is added. Vertex 4 is added. kβ=β2. v1β=β1, x1β=β5. Edge from vertex root(1)β=β1 to vertex 4 with weight depth(1)β+βx1β=β0β+β5β=β5 is added. v2β=β2, x2β=β2. Edge from vertex root(2)β=β3 to vertex 4 with weight depth(2)β+βx1β=β1β+β2β=β3 is added. Vertex 5 is added. kβ=β1. v1β=β1, x1β=β2. Edge from vertex root(1)β=β4 to vertex 5 with weight depth(1)β+βx1β=β5β+β2β=β7 is added. Vertex 6 is added. kβ=β1. v1β=β3, x1β=β4. Edge from vertex root(3)β=β5 to vertex 6 with weight depth(3)β+βx1β=β10β+β4β=β14 is added.The resulting graph is shown on the pictore below: | Java 11 | standard input | [
"data structures",
"dsu",
"graphs"
] | c4d464f1770d2c1b41f8123df4325615 | The first line contains a single integer n (1ββ€βnββ€β105) β the number of operations of adding a vertex. Next n lines contain descriptions of the operations, the i-th line contains the description of the operation of adding the i-th vertex in the following format: the first number of a line is an integer k (0ββ€βkββ€βiβ-β1), then follow 2k space-separated integers: v1,βx1,βv2,βx2,β... ,βvk,βxk (1ββ€βvjββ€βiβ-β1,β|xj|ββ€β109). The operations are given in the order, in which they should be applied to the graph. It is guaranteed that sum k of all operations does not exceed 105, also that applying operations of adding vertexes does not result in loops and multiple edges. | 2,000 | Print a single number β the sum of weights of all edges of the resulting graph modulo 1000000007 (109β+β7). | standard output | |
PASSED | 7201244b9b2195f295ebfea8b10b4a93 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class E {
public static void main(String[] args) throws Exception {
// StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next());
StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next());
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(stok.nextToken());
ArrayList<Integer>[] G = new ArrayList[n];
for (int i = 0; i < n; i++)
G[i] = new ArrayList<Integer>();
for (int i = 0; i < n-1; i++) {
int u = Integer.parseInt(stok.nextToken())-1;
int v = Integer.parseInt(stok.nextToken())-1;
G[u].add(v);
G[v].add(u);
}
int[] a = dfsTree(G,0);
int[][] b = new int[n+1][2];
for(int i=0;i<a.length;i++) {
if(b[a[i]][0]==0) b[a[i]][0] = i+1; else b[a[i]][1] = i+1;
}
for(int i=1;i<=n;i++) sb.append(b[i][0]+" "+b[i][1]+"\n");
System.out.println(sb);
}
private static int[] dfsTree(ArrayList<Integer>[] G, int s) {
int n = G.length;
boolean[] visited= new boolean[n];
int ptr=0;
int[] ret = new int[2*n];
int[] ss = new int[n];
int[] p = new int[n];
p[s] = s;
ArrayDeque<Integer> S = new ArrayDeque<Integer>();
S.add(s);
while(!S.isEmpty()) {
int c = S.pop();
if(visited[c]!=true) {
visited[c] = true;
while(ss[c]<G[c].size() && visited[G[c].get(ss[c])]) ss[c]++;
if(ss[c]==G[c].size()) {
ret[ptr++]=c+1;
}
else {
S.push(c);
p[G[c].get(ss[c])]=c;
S.push(G[c].get(ss[c]));
}
}
else {
ss[c]++;
while(ss[c]<G[c].size() && visited[G[c].get(ss[c])]) ss[c]++;
if(ss[c]==G[c].size()) {
ret[ptr++] = c+1;
for(int i=ss[c]-1;i>=0;i--) {
if(G[c].get(i)!=p[c]) ret[ptr++] = G[c].get(i)+1;
}
}
else {
S.push(c);
p[G[c].get(ss[c])]=c;
S.push(G[c].get(ss[c]));
}
}
}
ret[ptr++]=s+1;
return ret;
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 8d2dd66cb75818307fad43e454f647bb | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.*;
import java.util.*;
/*
ββββββββββββββββ β β βββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββ βββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββ
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9);
static final int MOD = (int) (1e9 + 7);
static final int N = (int) (1e6 + 6);
static int n;
static ArrayList<Integer>[] g;
static int[] size;
static int[][] segs;
static void dfs1(int v, int par) {
size[v] = 1;
for (int u : g[v]) {
if (u != par) {
dfs1(u, v);
size[v] += size[u];
}
}
}
static void dfs2(int v, int par, int x) {
int r = x + g[v].size() - 1;
if (par == -1) r++;
int i = r - 1, j = r + 1;
for (int u : g[v]) {
if (u != par) {
segs[u][0] = i;
dfs2(u, v, j);
i--;
j += size[u] * 2 - 1;
}
}
segs[v][1] = r;
}
static void solve() {
n = in.nextInt();
g = new ArrayList[n];
Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 0; i < n - 1; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
g[x].add(y);
g[y].add(x);
}
size = new int[n];
dfs1(0, -1);
segs = new int[n][2];
segs[0][0] = 1;
dfs2(0, -1, 2);
for (int i = 0; i < n; i++) {
out.println(segs[i][0] + " " + segs[i][1]);
}
}
public static void main(String[] args) throws FileNotFoundException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("output.txt"));
int q = 1;
while (q-- > 0) {
solve();
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | b457c20522bd3c44d20ff0a29999bbc0 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import static java.lang.Math.*;
import java.util.stream.*;
public class E {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
G = graph(N, E);
S = new int [2*N];
dfs(0, -1);
S[2*N-1] = -1;
int [][] res = new int [N][2]; int i = 1;
for (int s : S)
if (s > 0)
res[s-1][0] = i++;
else
res[-s-1][1] = i++;
for (int j : rep(N))
print(res[j]);
return null;
}
int [][] G;
int [] S; int J = 0;
void dfs(int i, int p) {
for (int j : G[i])
if (j != p)
dfs(j, i);
S[J++] = i+1;
int s = G[i].length + 2*J - 2;
if (p == -1)
++s;
for (int j : G[i])
if (j != p)
S[s - J++] = -j-1;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; }
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new E().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | d02df92c6df5a127c9ec94e1234df20a | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import static java.lang.Math.*;
import java.util.*;
import java.util.stream.*;
public class E {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
G = graph(N, E);
dfs(0, -1);
S.add(-1);
int [][] res = new int [N][2]; int i = 1;
for (int s : S)
if (s > 0)
res[s-1][0] = i++;
else
res[-s-1][1] = i++;
for (int j : rep(N))
print(res[j]);
return null;
}
int [][] G;
List<Integer> S = new ArrayList<>();
void dfs(int i, int p) {
for (int j : rep(G[i].length))
if (G[i][j] != p)
dfs(G[i][j], i);
S.add(i+1);
for (int j : sep(G[i].length))
if (G[i][j] != p)
S.add(-G[i][j]-1);
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [] sep (int N) { return sep(0, N); }
private static int [] sep (final int S, final int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; }
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new E().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | f1b261e7af5676f5d8e4eb17a20cc8ca | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import static java.lang.Math.*;
import java.util.*;
import java.util.stream.*;
public class E {
public Object solve () {
int N = sc.nextInt();
int [][] E = dec(sc.nextInts(N-1));
G = graph(N, E);
S = new int [2*N];
dfs(0, -1);
S[2*N-1] = -1;
int [][] res = new int [N][2]; int i = 1;
for (int s : S)
if (s > 0)
res[s-1][0] = i++;
else
res[-s-1][1] = i++;
for (int j : rep(N))
print(res[j]);
return null;
}
int [][] G;
int [] S; int J = 0;
void dfs(int i, int p) {
for (int j : rep(G[i].length))
if (G[i][j] != p)
dfs(G[i][j], i);
S[J++] = i+1;
for (int j : sep(G[i].length))
if (G[i][j] != p)
S[J++] = -G[i][j]-1;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) { return wgraph(N, E)[0]; }
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [] sep (int N) { return sep(0, N); }
private static int [] sep (final int S, final int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[T-1-i] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; }
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new E().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | a77b0bef0a5e5f22cd1ec56387e126fb | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
static PrintWriter out;
static InputReader in;
public static void main(String args[]){
out = new PrintWriter(System.out);
in = new InputReader();
new Main();
out.flush(); out.close();
}
Main(){
solve();
}
class pair{
int F, S;
pair(int a, int b){
F = a; S = b;
}
}
final int max = 500010;
int val[] = new int[2 * max];
ArrayList<Integer> al[] = new ArrayList[max];
int p = 0;
void dfs(int u, int pa){
for(int v : al[u]){
if(v == pa)continue;
dfs(v, u);
}
val[p++] = u;
for(int i = al[u].size() - 1; i >= 0; i--){
int v = al[u].get(i);
if(v == pa)continue;
val[p++] = v;
}
}
void solve(){
int n = in.nextInt();
for(int i = 0; i <= n; i++)al[i] = new ArrayList<>();
for(int i = 0; i < n - 1; i++){
int u = in.nextInt(), v = in.nextInt();
al[u].add(v); al[v].add(u);
}
dfs(1, 0);
val[p++] = 1;
int dp[][] = new int[n + 1][2];
for(int i = 0; i < p; i++){
int node = val[i];
// System.out.print(node + " ");
if(dp[node][0] != 0)dp[node][1] = i + 1;
else dp[node][0] = i + 1;
}
for(int i = 1; i <= n; i++){
out.println(dp[i][0] + " " + dp[i][1]);
}
}
public static class InputReader{
BufferedReader br;
StringTokenizer st;
InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){}
}
return st.nextToken();
}
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 009928e8dbec837b95d102bf445ef1ce | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
// written by luchy0120
public class Main {
public static void main(String[] args) throws Exception {
new Main().run();
}
int cnt=1;
int ps[][];
void dfs(int rt,int fa){
int sz =g[rt].size();
for(int i=0;i<sz;++i){
int v = g[rt].get(i);
if(v==fa) continue;
if(ps[v][0]==0) {
ps[v][0] = cnt++;
}else{
ps[v][1] = cnt++;
}
}
ps[rt][1] = cnt++;
for(int i=sz-1;i>=0;--i){
int v = g[rt].get(i);
if(v==fa) continue;
dfs(v, rt);
}
}
List<Integer> g[];
void solve(){
int n = ni();
ps =new int[n+1][2];
g = new ArrayList[n+1];
for(int i=1;i<=n;++i){
g[i] = new ArrayList<>();
}
for(int i=0;i<n-1;++i){
int u = ni();
int v = ni();
g[u].add(v);
g[v].add(u);
}
ps[1][0] = cnt++;
dfs(1,-1);
for(int i=1;i<=n;++i){
println(ps[i][0]+" "+ps[i][1]);
}
}
public static String roundS(double result, int scale){
String fmt = String.format("%%.%df", scale);
return String.format(fmt, result);
}
// void solve() {
//
// for(int i=0;i<9;++i) {
// for (int j = 0; j < 9; ++j) {
// int v = ni();
// a[i][j] = v;
// if(v>0) {
// vis_row[i][v] = true;
// vis_col[j][v] = true;
// vis_room[get_room(i, j)][v] = true;
// }else{
// space++;
// }
// }
// }
//
//
// prepare = new int[space][2];
//
// int p = 0;
//
// for(int i=0;i<9;++i) {
// for (int j = 0; j < 9; ++j) {
// if(a[i][j]==0){
// prepare[p][0] = i;
// prepare[p][1]= j;p++;
// List<Integer> temp =new ArrayList<>();
// for(int k=1;k<=9;++k){
// if(!vis_col[j][k]&&!vis_row[i][k]&&!vis_room[get_room(i,j)][k]){
// temp.add(k);
// }
// }
// int sz = temp.size();
// val[i][j] = new int[sz];
// for(int k=0;k<sz;++k){
// val[i][j][k] = temp.get(k);
// }
// }
// }
// }
// Arrays.sort(prepare,(x,y)->{
// return Integer.compare(val[x[0]][x[1]].length,val[y[0]][y[1]].length);
// });
// dfs(0);
//
//
//
//
//
//
//
//
//
//
// }
InputStream is;
PrintWriter out;
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private char ncc() {
int b = readByte();
return (char) b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private String nline() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[][] nm(int n, int m) {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) a[i] = ns(m);
return a;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private long[] nal(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nl();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
}
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0');
else return minus ? -num : num;
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) {
}
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') num = num * 10 + (b - '0');
else return minus ? -num : num;
b = readByte();
}
}
void print(Object obj) {
out.print(obj);
}
void println(Object obj) {
out.println(obj);
}
void println() {
out.println();
}
void printArray(int a[],int from){
int l = a.length;
for(int i=from;i<l;++i){
print(a[i]);
if(i!=l-1){
print(" ");
}
}
println();
}
void printArray(long a[],int from){
int l = a.length;
for(int i=from;i<l;++i){
print(a[i]);
if(i!=l-1){
print(" ");
}
}
println();
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 91b7c552bc399f26ceb9225011fe5e09 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class E {
static PrintWriter out = new PrintWriter(System.out);
static int[] l, r, sz;
static ArrayList<Integer> adj[];
static int N;
public static void main(String args[]){
new Thread(null, ()->asdf(args), "", 1<<28).start();
}
public static void asdf(String[] args) {
FS in = new FS();
N = in.nextInt();
l = new int[N];
r = new int[N];
adj = new ArrayList[N];
for(int i = 0; i < N; i++) {
adj[i] = new ArrayList<Integer>();
}
for(int i = 0; i < N-1; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
adj[a].add(b);
adj[b].add(a);
}
sz = new int[N];
getSz(0, -1);
l = new int[N];
r = new int[N];
dfs(0, -1, 1, 2*N);
for(int i = 0; i < N; i++) {
out.println(l[i]+" "+r[i]);
}
out.close();
}
static void getSz(int node, int p) {
sz[node] = 1;
for(int ii : adj[node]) {
if(ii != p) { getSz(ii, node);
sz[node] += sz[ii];
}
}
}
static void dfs(int node, int p, int ll, int rr) {
if(p == -1) {
l[node] = ll++;
for(int ii : adj[node]) if(ii != p) r[ii] = rr--;
r[node] = rr--;
for(int ii : adj[node]) {
if(ii != p) {
int give = 2*sz[ii]-1;
dfs(ii, node, ll, ll+give-1);
ll += give;
}
}
}
else {
for(int ii : adj[node]) if(ii != p) r[ii] = rr--;
l[node] = rr--;
for(int ii : adj[node]) {
if(ii != p) {
int give = 2*sz[ii]-1;
dfs(ii, node, ll, ll+give-1);
ll += give;
}
}
}
}
static class FS{
BufferedReader br;
StringTokenizer st;
public FS() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch(Exception e) { throw null;}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next());}
double nextDouble() { return Double.parseDouble(next());}
long nextLong() { return Long.parseLong(next());}
int[] NIA(int n) {
int r[] = new int[n];
for(int i = 0; i < n; i++) r[i] = nextInt();
return r;
}
long[] NLA(int n) {
long r[] = new long[n];
for(int i = 0; i < n; i++) r[i] = nextLong();
return r;
}
char[][] grid(int r, int c){
char res[][] = new char[r][c];
for(int i = 0; i < r; i++) {
char l[] = next().toCharArray();
for(int j = 0; j < c; j++) {
res[i][j] = l[j];
}
}
return res;
}
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 8b102d1a2f7f7ae710b61cedc3396b67 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | //package cf;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class USACO {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter (System.out);
//BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
//StringTokenizer st = new StringTokenizer(reader.readLine()," ");
int n = Integer.parseInt(reader.readLine());
HashMap<Integer,List<Integer>> edges = new HashMap<>();
for (int i=0;i<n;i++) edges.put(i,new ArrayList<>());
for (int i=0;i<n-1;i++) {
StringTokenizer st = new StringTokenizer(reader.readLine()," ");
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
edges.get(a).add(b);
edges.get(b).add(a);
}
Stack<Integer> dfs = new Stack<>();
int[] answer = new int[2*n];
int count=1;
/*for (int i=0;i<edges.get(0).size();i++) {
answer[count]=edges.get(0).get(i);
count++;
}*/
int[] dead = new int[n];
dfs.push(0);
while (!dfs.isEmpty()) {
int k = dfs.pop();
if (dead[k]==0) {
for (int i=edges.get(k).size()-1;i>=0;i--) {
if (dead[edges.get(k).get(i)]==1) edges.get(k).remove(i);
}
for (int i=0;i<edges.get(k).size();i++) {
//System.out.println(k+" "+count);
answer[count]=edges.get(k).get(i);
count++;
}
answer[count]=k;
count++;
}
dead[k]=1;
if (!edges.get(k).isEmpty()) {
dfs.push(k);
int m=edges.get(k).get(edges.get(k).size()-1); // next in pushpop
edges.get(k).remove(edges.get(k).size()-1);
dfs.push(m);
}
}
int[] reformat = new int[2*n];
int[] openclose = new int[n];
for (int i=0;i<2*n;i++) {
if (openclose[answer[i]]==0) reformat[2*answer[i]]=i;
else reformat[2*answer[i]+1]=i;
openclose[answer[i]]++;
}
for (int i=0;i<n;i++) {
out.println((reformat[2*i]+1)+" "+(reformat[2*i+1]+1));
}
reader.close();
out.close();
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 9b180e462c315f4108c740579319333c | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | /*********** This template help me to solve the SLOW I/O ***********/
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
public class Main extends Thread {
public static int[] visit;
public static int max=1;
public static int[][] arr;
public static ArrayList<Integer>[] adj;
boolean[] prime;
FastScanner sc;
PrintWriter pw;
MathF mf;
final class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
public long nlo() {
return Long.parseLong(next());
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public String nli() {
String line = "";
if (st.hasMoreTokens()) line = st.nextToken();
else try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (st.hasMoreTokens()) line += " " + st.nextToken();
return line;
}
public double nd() {
return Double.parseDouble(next());
}
}
final class MathF {
long grtdiv(long x)
{
if(isPrime(x))
return 1;
else
{
long ans=0;
long y=(long)Math.sqrt(x)+1;
for(;y>=2;y--)
{
if(x%y==0)
ans=Math.max(ans,Math.max(y,x/y));
}
return ans;
}
}
boolean isPrime(long x)
{
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
return false;
}
}
return true;
}
long[][] mul(long[][] arr,long[][] brr,int a,int b,int c,int d)
{
long[][] crr=new long[a][d];
for(int i=0;i<a;i++)
{
for(int j=0;j<d;j++)
{
for(int k=0;k<b;k++)
{
crr[i][j]+=(((arr[i][k]%1000000007)*(brr[k][j]%1000000007))%1000000007);
}
}
}
return crr;
}
int sod(long a)
{
int ans=0;
while(a!=0)
{
ans+=(a%10);
a=a/10;
}
return ans;
}
long pow(long a,long b)
{
if(b==0)
return 1;
else
{
long x=pow(a,b/2);
if(b%2==1)
return (x*x*a);
else
return (x*x);
}
}
public long gcd(long a, long b) {
return (b == 0 ? a : gcd(b, a % b));
}
public long exponent(long a,long b)
{
if(b==0)
return 1;
else
{
long x=exponent(a,b/2);
x*=x;
if(b%2==1)
x*=a;
return x;
}
}
public int nod(long x) {
int i = 0;
while (x != 0) {
i++;
x = x / 10;
}
return i;
}
public int nob(long x) {
if(x==0)
return 1;
return (int) Math.floor(Math.log(x) / Math.log(2)) + 1;
}
public int[] FastradixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public void Primesieve(int n) {
prime=new boolean[n];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 2; p * p < n; p++) {
if (prime[p] == true) {
for (int i = p * p; i < n; i += p)
prime[i] = false;
}
}
}
}
public Main(ThreadGroup t,Runnable r,String s,long d )
{
super(t,r,s,d);
}
public void run()
{
sc=new FastScanner();
pw=new PrintWriter(System.out);
mf=new MathF();
solve();
pw.flush();
pw.close();
}
public static void main(String[] args)
{
new Main(null,null,"",1<<30).start();
}
/////////////------------------------------------/////////////
/////////////------------------------------------/////////////
////////////------------------MAIN-LOGIC---------/////////////
////////////-------------------------------------/////////////
///////////--------------------------------------/////////////
public void solve() {
int n=sc.ni();
adj=new ArrayList[n];
for(int i=0;i<n;i++)
adj[i]=new ArrayList();
visit=new int[n];
arr=new int[n][2];
for(int i=0;i<n-1;i++)
{
int x=sc.ni();
int y=sc.ni();
x--;y--;
// System.out.println(x+" "+y);
adj[x].add(y);
adj[y].add(x);
}
Stack<Integer> stk=new Stack();
for(int x:adj[0])
{
stk.push(x);
arr[x][0]=max++;
//System.out.println(x+" 0 :"+arr[x][0]);
}
visit[0]=1;
arr[0][0]=max++;
while(!stk.isEmpty())
{
solve(stk.pop());
}
arr[0][1]=max++;
for(int i=0;i<n;i++)
pw.println(arr[i][0]+" "+arr[i][1]);
}
public static void solve(int x)
{
visit[x]=1;
Stack<Integer> stk=new Stack();
for(int k:adj[x])
{
if(visit[k]==0)
{stk.push(k);
arr[k][0]=max++;
// System.out.println(x+" 0 :"+arr[x][0]);
}
}
arr[x][1]=max++;
//System.out.println(x+" 1 :"+arr[x][1]);
while(!stk.isEmpty())
{
solve(stk.pop());
}
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | c7c028f901d528b921f359aabb9f84ae | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main{
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long mod = (long) (1e9+7);
static long cf = 998244353;
static final long MAX = (long) 1e8;
public static List<Integer>[] edges;
public static int[][] parent;
public static long[] fac;
public static int N = (int) 1e5;
public static int x = 0;
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
edges = new ArrayList[n+1];
for(int i=0;i<=n;++i) edges[i] = new ArrayList<>();
for(int i=0;i<n-1;++i) {
int u = sc.nextInt();
int v = sc.nextInt();
edges[u].add(v);
edges[v].add(u);
}
int[] l = new int[n+1];
int[] r = new int[n+1];
l[1] = ++x;
dfs(1,0,l,r);
for(int i=1;i<=n;++i) out.println(l[i] +" "+ r[i]);
out.close();
}
private static void dfs(int v, int p, int[] l, int[] r) {
for(int child : edges[v]) {
if(child != p) {
l[child] = ++x; // add each child
}
}
// close parent
r[v] = ++x;
for(int i = edges[v].size()-1;i>=0;--i) {
int child = edges[v].get(i);
if(child != p)
dfs(child,v,l,r);
}
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | f7444b24198915e4ade8a12bc0b28172 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class ETask {
private static final String QUICK_ANSWER = "NO";
private final Input in;
private final StringBuilder out;
private int n;
int[] from;
int[] to;
private Tree tree;
public ETask(Input in, StringBuilder out) {
this.in = in;
this.out = out;
}
public void solve() throws QuickAnswer {
n = nextInt();
from = new int[n];
to = new int[n];
tree = Tree.treeBuilder()
.nodeCount(n)
.build(this::nextInt);
place(0, 1, 2);
for (int i = 0; i < n; i++) {
println(from[i] + " " + to[i]);
}
}
int place(int node, int start, int cont) {
from[node] = start;
int[] children = tree.children[node];
to[node] = cont + children.length;
int end = cont + children.length + 1;
for (int i = 0; i < children.length; ++i) {
end = place(children[i], cont + children.length - 1 - i, end);
}
return end;
}
// Common functions
private static class Input {
private final BufferedReader in;
private StringTokenizer tokenizer = null;
public Input(BufferedReader in) {
this.in = in;
}
String nextToken() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(in.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return "";
}
}
}
void quickAnswer(String answer) throws QuickAnswer {
throw new QuickAnswer(answer);
}
void quickAnswer() throws QuickAnswer {
quickAnswer(QUICK_ANSWER);
}
static class QuickAnswer extends Exception {
private String answer;
public QuickAnswer(String answer) {
this.answer = answer;
}
}
void print(Object... args) {
String prefix = "";
for (Object arg : args) {
out.append(prefix);
out.append(arg);
prefix = " ";
}
}
void println(Object... args) {
print(args);
out.append("\n");
}
void printsp(Object... args) {
print(args);
out.append(" ");
}
int nextInt() {
return in.nextInt();
}
long nextLong() {
return in.nextLong();
}
String nextString() {
return in.nextLine();
}
int[] nextInts(int count) {
int[] res = new int[count];
for (int i = 0; i < count; ++i) {
res[i] = nextInt();
}
return res;
}
int[][] nextInts(int count, int n) {
int[][] res = new int[n][count];
for (int i = 0; i < count; ++i) {
for (int j = 0; j < n; j++) {
res[j][i] = nextInt();
}
}
return res;
}
long[] nextLongs(int count) {
long[] res = new long[count];
for (int i = 0; i < count; ++i) {
res[i] = nextLong();
}
return res;
}
long[][] nextLongs(int count, int n) {
long[][] res = new long[n][count];
for (int i = 0; i < count; ++i) {
for (int j = 0; j < n; j++) {
res[j][i] = nextLong();
}
}
return res;
}
public static void main(String[] args) {
doMain(System.in, System.out);
}
static void doMain(InputStream inStream, PrintStream outStream) {
Input in = new Input(new BufferedReader(new InputStreamReader(inStream)));
StringBuilder totalOut = new StringBuilder();
int count = 1;
//count = in.nextInt();
while (count-- > 0) {
try {
StringBuilder out = new StringBuilder();
new ETask(in, out).solve();
totalOut.append(out.toString());
} catch (QuickAnswer e) {
totalOut.append(e.answer);
}
if (count > 0) {
totalOut.append("\n");
}
}
outStream.print(totalOut.toString());
}
static class Graph {
interface Input {
int nextInt();
}
final int nodeCount;
final int edgeCount;
final int[][] neighbors;
final int[] color;
final int[] edgeFrom;
final int[] edgeTo;
final int[] edgeWeight;
static Builder builder() {
return new Builder();
}
static class Builder {
int adjustIndex = -1;
boolean withWeights = false;
int nodeCount = -1;
int edgeCount = -1;
Builder adjustIndex(int adjustIndex) {
this.adjustIndex = adjustIndex;
return this;
}
Builder withWeights() {
this.withWeights = true;
return this;
}
Builder nodeCount(int n) {
this.nodeCount = n;
return this;
}
Builder edgeCount(int m) {
this.edgeCount = m;
return this;
}
Graph build(Input in) {
return new Graph(
in,
nodeCount == -1 ? in.nextInt() : nodeCount,
edgeCount == -1 ? in.nextInt() : edgeCount,
adjustIndex,
withWeights);
}
}
Graph(Input in, int nodeCount, int m, int adjustIndex, boolean withWeights) {
this.nodeCount = nodeCount;
this.edgeCount = m;
this.color = new int[nodeCount];
int[] cnt = new int[nodeCount];
edgeFrom = new int[m];
edgeTo = new int[m];
edgeWeight = new int[m];
for (int i = 0; i < m; ++i) {
int x = in.nextInt() + adjustIndex;
int y = in.nextInt() + adjustIndex;
edgeFrom[i] = x;
edgeTo[i] = y;
edgeWeight[i] = withWeights ? in.nextInt() : 1;
cnt[x]++;
cnt[y]++;
}
this.neighbors = new int[nodeCount][];
for (int i = 0; i < nodeCount; i++) {
neighbors[i] = new int[cnt[i]];
}
for (int i = 0; i < m; ++i) {
int from = edgeFrom[i];
int to = edgeTo[i];
neighbors[from][--cnt[from]] = to;
neighbors[to][--cnt[to]] = from;
}
}
}
static class IntQueue {
final int[] togo;
int curr;
int end;
public IntQueue(int maxLen) {
togo = new int[maxLen];
}
void add(int val) {
togo[end++] = val;
}
int poll() {
return togo[curr++];
}
boolean isEmpty() {
return curr == end;
}
}
static class Tree extends Graph {
final int[] level;
final int[] parent;
final int[][] children;
static Builder treeBuilder() {
return new Builder();
}
static class Builder {
private int rootNode = 0;
int adjustIndex = -1;
boolean withWeights = false;
int nodeCount = -1;
Builder rootNode(int rootNode) {
this.rootNode = rootNode;
return this;
}
Builder adjustIndex(int adjustIndex) {
this.adjustIndex = adjustIndex;
return this;
}
Builder withWeights() {
this.withWeights = true;
return this;
}
Builder nodeCount(int n) {
this.nodeCount = n;
return this;
}
public Tree build(Input in) {
return new Tree(
in,
nodeCount == -1 ? in.nextInt() : nodeCount,
adjustIndex,
withWeights,
rootNode);
}
}
Tree(Input in, int n, int adjustIndex, boolean withWeights, int rootNode) {
super(in, n, n - 1, adjustIndex, withWeights);
level = new int[n];
parent = new int[n];
children = new int[n][];
IntQueue iq = new IntQueue(n);
level[rootNode] = 0;
parent[rootNode] = -1;
iq.add(rootNode);
while (!iq.isEmpty()) {
int node = iq.poll();
int childLevel = level[node] + 1;
if (parent[node] == -1) {
children[node] = new int[neighbors[node].length];
} else {
children[node] = new int[neighbors[node].length - 1];
}
int curr = 0;
for (int neighbor : neighbors[node]) {
if (neighbor == parent[node]) continue;
level[neighbor] = childLevel;
parent[neighbor] = node;
children[node][curr++] = neighbor;
iq.add(neighbor);
}
}
}
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | ed6f5116856e843a78160646d4b102c1 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.UncheckedIOException;
import java.util.List;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
ETestsForProblemD solver = new ETestsForProblemD();
solver.solve(1, in, out);
out.close();
}
}
static class ETestsForProblemD {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
Node[] nodes = new Node[n];
for (int i = 0; i < n; i++) {
nodes[i] = new Node();
}
for (int i = 1; i < n; i++) {
Node a = nodes[in.readInt() - 1];
Node b = nodes[in.readInt() - 1];
a.next.add(b);
b.next.add(a);
}
dfs(nodes[0], null);
for (int i = 0; i < n; i++) {
Splay.splay(nodes[i].left);
out.append(nodes[i].left.size - nodes[i].left.right.size).append(' ');
Splay.splay(nodes[i].right);
out.println(nodes[i].right.size - nodes[i].right.right.size);
}
}
public Splay dfs(Node root, Node p) {
root.next.remove(p);
Splay splay = Splay.NIL;
for (int i = 0; i < root.next.size(); i++) {
Node node = root.next.get(i);
Splay child = dfs(node, root);
if (splay == Splay.NIL) {
splay = child;
continue;
}
splay = Splay.selectKthAsRoot(splay, i);
Splay right = Splay.splitRight(splay);
splay = Splay.merge(splay, child);
splay = Splay.merge(splay, right);
}
splay = Splay.merge(root.left, splay);
splay = Splay.selectKthAsRoot(splay, root.next.size() + 1);
Splay right = Splay.splitRight(splay);
splay = Splay.merge(splay, root.right);
splay = Splay.merge(splay, right);
return splay;
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class Node {
List<Node> next = new ArrayList<>();
Splay left = new Splay();
Splay right = new Splay();
}
static class Splay implements Cloneable {
public static final Splay NIL = new Splay();
Splay left = NIL;
Splay right = NIL;
Splay father = NIL;
int size = 1;
int key;
static {
NIL.left = NIL;
NIL.right = NIL;
NIL.father = NIL;
NIL.size = 0;
}
public static void splay(Splay x) {
if (x == NIL) {
return;
}
Splay y, z;
while ((y = x.father) != NIL) {
if ((z = y.father) == NIL) {
y.pushDown();
x.pushDown();
if (x == y.left) {
zig(x);
} else {
zag(x);
}
} else {
z.pushDown();
y.pushDown();
x.pushDown();
if (x == y.left) {
if (y == z.left) {
zig(y);
zig(x);
} else {
zig(x);
zag(x);
}
} else {
if (y == z.left) {
zag(x);
zig(x);
} else {
zag(y);
zag(x);
}
}
}
}
x.pushDown();
x.pushUp();
}
public static void zig(Splay x) {
Splay y = x.father;
Splay z = y.father;
Splay b = x.right;
y.setLeft(b);
x.setRight(y);
z.changeChild(y, x);
y.pushUp();
}
public static void zag(Splay x) {
Splay y = x.father;
Splay z = y.father;
Splay b = x.left;
y.setRight(b);
x.setLeft(y);
z.changeChild(y, x);
y.pushUp();
}
public void setLeft(Splay x) {
left = x;
x.father = this;
}
public void setRight(Splay x) {
right = x;
x.father = this;
}
public void changeChild(Splay y, Splay x) {
if (left == y) {
setLeft(x);
} else {
setRight(x);
}
}
public void pushUp() {
size = left.size + right.size + 1;
}
public void pushDown() {
}
public static void toString(Splay root, StringBuilder builder) {
if (root == NIL) {
return;
}
root.pushDown();
toString(root.left, builder);
builder.append(root.key).append(',');
toString(root.right, builder);
}
public Splay clone() {
try {
return (Splay) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public static Splay cloneTree(Splay splay) {
if (splay == NIL) {
return NIL;
}
splay = splay.clone();
splay.left = cloneTree(splay.left);
splay.right = cloneTree(splay.right);
return splay;
}
public static Splay selectMaxAsRoot(Splay root) {
if (root == NIL) {
return root;
}
root.pushDown();
while (root.right != NIL) {
root = root.right;
root.pushDown();
}
splay(root);
return root;
}
public static Splay splitRight(Splay root) {
root.pushDown();
Splay right = root.right;
right.father = NIL;
root.setRight(NIL);
root.pushUp();
return right;
}
public static Splay merge(Splay a, Splay b) {
if (a == NIL) {
return b;
}
if (b == NIL) {
return a;
}
a = selectMaxAsRoot(a);
a.setRight(b);
a.pushUp();
return a;
}
public static Splay selectKthAsRoot(Splay root, int k) {
if (root == NIL) {
return NIL;
}
Splay trace = root;
Splay father = NIL;
while (trace != NIL) {
father = trace;
trace.pushDown();
if (trace.left.size >= k) {
trace = trace.left;
} else {
k -= trace.left.size + 1;
if (k == 0) {
break;
} else {
trace = trace.right;
}
}
}
splay(father);
return father;
}
public String toString() {
StringBuilder builder = new StringBuilder().append(key).append(":");
toString(cloneTree(this), builder);
return builder.toString();
}
}
static class FastOutput implements AutoCloseable, Closeable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput println(int c) {
cache.append(c).append('\n');
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 1422af99746d73ab3315621cc024d939 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static PrintWriter out;
static Reader in;
public static void main(String[] args) throws IOException {
//out = new PrintWriter(new File("out.txt"));
//PrintWriter out = new PrintWriter(System.out);
//in = new Reader(new FileInputStream("in.txt"));
//Reader in = new Reader();
input_output();
Main solver = new Main();
solver.solve();
out.flush();
out.close();
}
static int INF = (int)1e9-1;
static int maxn = (int)1e6+5;
static int mod = 998_244_353;
static int n, m, q, k, t;
static List<Integer> adj[];
void solve() throws IOException{
n = in.nextInt();
adj = new ArrayList[n+1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<Integer>();
for (int i = 1; i < n; i++) {
int u = in.nextInt(),
v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
ans = new int[2*n+1];
cur = 2;
ans[1] = 1;
DFS(1, 0);
int[][] pair = new int[n+1][2];
for (int i = 1; i <= 2*n; i++) {
int elm = ans[i];
if (pair[elm][0] == 0) pair[elm][0] = i;
else pair[elm][1] = i;
}
for (int i = 1; i <= n; i++) out.println(pair[i][0]+" "+pair[i][1]);
}
//<>
static int cur, ans[];
static void DFS(int s, int p) {
int elm;
for (int i = 0; i < adj[s].size(); i++) {
elm = adj[s].get(i);
if (elm == p) continue;
ans[cur++] = elm;
}
ans[cur++] = s;
for (int i = adj[s].size()-1; i >= 0; i--) {
elm = adj[s].get(i);
if (elm == p) continue;
DFS(elm, s);
}
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static void input_output() throws IOException {
File f = new File("in.txt");
if(f.exists() && !f.isDirectory()) {
in = new Reader(new FileInputStream("in.txt"));
} else in = new Reader();
f = new File("out.txt");
if(f.exists() && !f.isDirectory()) {
out = new PrintWriter(new File("out.txt"));
} else out = new PrintWriter(System.out);
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 05141da056420846cad09ff35f6a7d92 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 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.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author John Martin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
ETestsForProblemD solver = new ETestsForProblemD();
solver.solve(1, in, out);
out.close();
}
static class ETestsForProblemD {
int nxt = 1;
int[] l;
int[] r;
public void solve(int testNumber, InputReader c, OutputWriter w) {
int n = c.readInt();
ArrayList<Integer> adj[] = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = c.readInt() - 1, v = c.readInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
l = new int[n];
r = new int[n];
l[0] = nxt++;
dfs(0, adj, -1);
for (int i = 0; i < n; i++) {
w.printLine(l[i], r[i]);
}
}
private void dfs(int x, ArrayList<Integer>[] adj, int p) {
for (int t : adj[x]) {
if (t != p) {
l[t] = nxt++;
}
}
r[x] = nxt++;
Collections.reverse(adj[x]);
for (int t : adj[x]) {
if (t != p) {
dfs(t, adj, x);
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
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 print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 74ef661b8de5be774bb96dc0c759e5e3 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.io.*;
import java.util.*;
public class tr1 {
static PrintWriter out;
static StringBuilder sb;
static int inf = (int) 1e9;
static long mod = (long) 1e9 + 7;
static int[] si;
static ArrayList<Integer> primes;
static HashSet<Integer> pr;
static int n, k, m;
static int[] in;
static HashMap<Integer, Integer> factors;
static HashSet<Integer> f;
static int[] fac, a, b;
static int[] l, r;
static int[][] memo;
static int[] numc;
static ArrayList<Integer>[] ad;
static HashMap<Integer, Integer> hm;
static pair[] ed;
static TreeSet<Integer>[] np;
static TreeMap<pair, Integer> tm;
static int[] le,re;
static char[] h;
static pair[] mm;
static boolean[] vis;
static int y;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n=sc.nextInt();
ad=new ArrayList[n];
for(int i=0;i<n;i++)
ad[i]=new ArrayList<>();
// int m=sc.nextInt();
for(int i=0;i<n-1;i++) {
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
ad[a].add(b);
ad[b].add(a);
}
re=new int [n];
le=new int [n];
y=1;
le[0]=y;
dfs(0,-1);
for(int i=0;i<n;i++)
out.println(le[i]+" "+re[i]);
out.flush();
}
static void dfs(int u,int p) {
for(int v:ad[u]) {
if(v!=p) {
le[v]=++y;
}
}
re[u]=++y;
for(int v=ad[u].size()-1;v>=0;v--) {
if(ad[u].get(v)!=p) {
dfs(ad[u].get(v),u);
}
}
}
static class pair implements Comparable<pair> {
int x;
int y;
// int z;
pair(int f, int t) {
x = f;
y = t;
// z=u;
// num = n;
}
public String toString() {
return x + " " + y;
}
@Override
public int compareTo(pair o) {
if(x==o.x)
return y-o.y;
return o.x-x;
}
}
static class pair1 implements Comparable<pair1> {
int x;
int y;
int z;
pair1(int f, int t,int u) {
x = f;
y = t;
z=u;
// num = n;
}
public String toString() {
return x + " " + y;
}
@Override
public int compareTo(pair1 o) {
if(x==o.x)
return y-o.y;
return x-o.x;
}
}
static public class FenwickTree { // one-based DS
int n;
int[] ft;
FenwickTree(int size) {
n = size;
ft = new int[n + 1];
// for(int i=1;i<=n;i++)
// ft[i]=i;
}
int rsq(int b) // O(log n)
{
int sum = 0;
while (b > 0) {
sum += ft[b];
b -= b & -b;
} // min?
return sum;
}
int rsq(int a, int b) {
return rsq(b) - rsq(a - 1);
}
void point_update(int k, int val) // O(log n), update = increment
{
while (k <= n) {
// System.out.println(k+" "+val);
ft[k] += val;
k += k & -k;
} // min?
}
int point_query(int idx) // c * O(log n), c < 1
{
int sum = ft[idx];
if (idx > 0) {
int z = idx ^ (idx & -idx);
--idx;
while (idx != z) {
// System.out.println("oo");
sum -= ft[idx];
idx ^= idx & -idx;
}
}
return sum;
}
void scale(int c) {
for (int i = 1; i <= n; ++i)
ft[i] *= c;
}
int findIndex(int cumFreq) {
int msk = n;
while ((msk & (msk - 1)) != 0)
msk ^= msk & -msk; // msk will contain the MSB of n
int idx = 0;
while (msk != 0) {
int tIdx = idx + msk;
if (tIdx <= n && cumFreq >= ft[tIdx]) {
idx = tIdx;
cumFreq -= ft[tIdx];
}
msk >>= 1;
}
if (cumFreq != 0)
return -1;
return idx;
}
}
static public class SegmentTree { // 1-based DS, OOP
int N; // the number of elements in the array as a power of 2 (i.e. after padding)
long[] array, sTree, lazy;
SegmentTree(long[] in) {
array = in;
N = in.length - 1;
sTree = new long[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero
lazy = new long[N << 1];
build(1, 1, N);
}
void build(int node, int b, int e) // O(n)
{
if (b == e)
sTree[node] = array[b];
else {
int mid = b + e >> 1;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
sTree[node] = sTree[node << 1] + sTree[node << 1 | 1];
}
}
void update_point(int index, int val) // O(log n)
{
index += N - 1;
sTree[index] += val;
while (index > 1) {
index >>= 1;
sTree[index] = sTree[index << 1] + sTree[index << 1 | 1];
}
}
void update_range(int i, int j, long val) // O(log n)
{
update_range(1, 1, N, i, j, val);
}
void update_range(int node, int b, int e, int i, int j, long val) {
if (i > e || j < b)
return;
if (b >= i && e <= j) {
sTree[node] += (e - b + 1) * val;
lazy[node] += val;
} else {
int mid = b + e >> 1;
propagate(node, b, mid, e);
update_range(node << 1, b, mid, i, j, val);
update_range(node << 1 | 1, mid + 1, e, i, j, val);
sTree[node] = sTree[node << 1] + sTree[node << 1 | 1];
}
}
void propagate(int node, int b, int mid, int e) {
lazy[node << 1] += lazy[node];
lazy[node << 1 | 1] += lazy[node];
sTree[node << 1] += (mid - b + 1) * lazy[node];
sTree[node << 1 | 1] += (e - mid) * lazy[node];
lazy[node] = 0;
}
long query(int i, int j) {
return query(1, 1, N, i, j);
}
long query(int node, int b, int e, int i, int j) // O(log n)
{
if (i > e || j < b)
return 0;
if (b >= i && e <= j)
return sTree[node];
int mid = b + e >> 1;
propagate(node, b, mid, e);
long q1 = query(node << 1, b, mid, i, j);
long q2 = query(node << 1 | 1, mid + 1, e, i, j);
return q1 + q2;
}
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public int[] merge(int[] d, int st, int e) {
if (st > e)
return null;
if (e == st) {
int[] ans = { d[e] };
return ans;
}
int mid = (st + e) / 2;
int[] ans = new int[e - st + 1];
int[] ll = merge(d, st, mid);
int[] rr = merge(d, mid + 1, e);
if (ll == null)
return rr;
if (rr == null)
return ll;
int iver = 0;
int idxl = 0;
int idxr = 0;
for (int i = st; i <= e; i++) {
if (ll[idxl] < rr[idxr]) {
}
}
return ans;
}
public static class pair2 implements Comparable<pair2> {
int a;
int idx;
pair2(int a, int i) {
this.a = a;
idx = i;
}
public String toString() {
return a + " " + idx;
}
@Override
public int compareTo(pair2 o) {
// TODO Auto-generated method stub
return idx - o.idx;
}
}
static long inver(long x) {
int a = (int) x;
long e = (mod - 2);
long res = 1;
while (e > 0) {
if ((e & 1) == 1) {
// System.out.println(res*a);
res = (int) ((1l * res * a) % mod);
}
a = (int) ((1l * a * a) % mod);
e >>= 1;
}
// out.println(res+" "+x);
return res % mod;
}
static int atMostSum(int arr[], int n, int k) {
int sum = 0;
int cnt = 0, maxcnt = 0;
for (int i = 0; i < n; i++) {
// If adding current element doesn't
// cross limit add it to current window
if ((sum + arr[i]) <= k) {
sum += arr[i];
cnt++;
}
// Else, remove first element of current
// window and add the current element
else if (sum != 0) {
sum = sum - arr[i - cnt] + arr[i];
}
// keep track of max length.
maxcnt = Math.max(cnt, maxcnt);
}
return maxcnt;
}
public static int[] longestSubarray(int[] inp) {
// array containing prefix sums up to a certain index i
int[] p = new int[inp.length];
p[0] = inp[0];
for (int i = 1; i < inp.length; i++) {
p[i] = p[i - 1] + inp[i];
}
// array Q from the description below
int[] q = new int[inp.length];
q[inp.length - 1] = p[inp.length - 1];
for (int i = inp.length - 2; i >= 0; i--) {
q[i] = Math.max(q[i + 1], p[i]);
}
int a = 0;
int b = 0;
int maxLen = 0;
int curr;
int[] res = new int[] { -1, -1 };
while (b < inp.length) {
curr = a > 0 ? q[b] - p[a - 1] : q[b];
if (curr >= 0) {
if (b - a > maxLen) {
maxLen = b - a;
res = new int[] { a, b };
}
b++;
} else {
a++;
}
}
return res;
}
static void factor(int n) {
if (si[n] == n) {
f.add(n);
return;
}
f.add(si[n]);
factor(n / si[n]);
}
static void seive() {
si = new int[100001];
primes = new ArrayList<>();
int N = 100001;
si[1] = 1;
for (int i = 2; i < N; i++) {
if (si[i] == 0) {
si[i] = i;
primes.add(i);
}
for (int j = 0; j < primes.size() && primes.get(j) <= si[i] && (i * primes.get(j)) < N; j++)
si[primes.get(j) * i] = primes.get(j);
}
}
static class unionfind {
int[] p;
int[] size;
int jum;
unionfind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
jum=n;
Arrays.fill(size, 1);
}
int findSet(int v) {
if (v == p[v])
return v;
return p[v] = findSet(p[v]);
}
boolean sameSet(int a, int b) {
a = findSet(a);
b = findSet(b);
if (a == b)
return true;
return false;
}
int max() {
int max = 0;
for (int i = 0; i < size.length; i++)
if (size[i] > max)
max = size[i];
return max;
}
void combine(int a, int b) {
a = findSet(a);
b = findSet(b);
if (a == b)
return;
jum--;
if (size[a] > size[b]) {
p[b] = a;
size[a] += size[b];
} else {
p[a] = b;
size[b] += size[a];
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 9d184a6f523e31030b02275d07e65028 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
class DJS {
int[] a;
public DJS(int n) {
a = new int[n];
Arrays.fill(a, -1);
}
int find (int x) {
if (a[x] < 0) return x;
return a[x] = find(a[x]);
}
boolean union(int x, int y) {
int rx = find(x), ry = find(y);
if (rx== ry) return false;
a[rx] = ry;
return true;
}
}
int glob = 0;
List<Integer>[] edges;
int[] start;
int[] end;
void dfs(int u, int p) {
for (int v: edges[u]) if (v != p) {
end[v] = glob--;
}
start[u] = glob--;
for (int i = 0; i < edges[u].size(); i++) {
int v = edges[u].get(edges[u].size() - 1- i);
if (v == p) continue;
dfs(v, u);
}
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
int n = sc.nextInt();
edges = new List[n];
for (int i = 0; i < n; i++) {
edges[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
edges[a].add(b);
edges[b].add(a);
}
glob = 2 * n;
start = new int[n];
end = new int[n];
end[0] = glob--;
dfs(0, -1);
for (int i = 0; i < n;i ++) {
pw.println(start[i] + " " + end[i]);
}
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("input_line"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("input_line"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 7d84dc02f06b811c0015a6aedca50acb | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | /**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class ACMIND
{
static FastReader scan;
static PrintWriter pw;
static long MOD = 1_000_000_007 ;
static long INF = 1_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<27)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n,l[],r[],max;
static ArrayList<Integer> adj[];
static void solve() throws IOException
{
scan = new FastReader();
pw = new PrintWriter(System.out,true);
StringBuilder sb = new StringBuilder();
n = ni();
adj = new ArrayList[n+1];
for(int i=1;i<=n;++i) {
adj[i] = new ArrayList<>();
}
for(int i=1;i<n;++i) {
int u = ni(), v = ni();
adj[u].add(v);
adj[v].add(u);
}
l = new int[n+1];
r = new int[n+1];
l[1] = 1;
r[1] = 1+adj[1].size()+1;
max = r[1];
int idx = 0;
for(int e : adj[1]) {
dfs(e, 1, idx++);
}
for(int i=1;i<=n;++i) {
sb.append(l[i]);
sb.append(" ");
sb.append(r[i]);
sb.append("\n");
}
psb(sb);
pw.flush();
pw.close();
}
static void dfs(int v, int par, int pos) {
l[v] = r[par] - (pos+1);
r[v] = max + adj[v].size();
max = r[v];
int ptr = 0;
for(int e : adj[v]) {
if(e!=par) {
dfs(e, v, ptr++);
}
}
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static 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 readLine() throws IOException {
byte[] buf = new byte[1000000];
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 | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | ef78275b516947797ca299ed69ed2d2c | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 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.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Sparsh Sanchorawala
*/
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);
ETestsForProblemD solver = new ETestsForProblemD();
solver.solve(1, in, out);
out.close();
}
static class ETestsForProblemD {
ArrayList<Integer>[] adj;
int[] resl;
int[] resr;
int[] sub;
int[] child;
void fillsub(int x, int p) {
sub[x]++;
for (int y : adj[x]) {
if (y != p) {
child[x]++;
fillsub(y, x);
sub[x] += sub[y];
}
}
}
void recur(int x, int l, int m, int p) {
resl[x] = l;
resr[x] = m + child[x];
int c = 1;
int s = 0;
for (int y : adj[x]) {
if (y != p) {
recur(y, resr[x] - c, resr[x] - c + 2 * s + 2, x);
c++;
s += sub[y];
}
}
}
public void solve(int testNumber, InputReader s, PrintWriter w) {
int n = s.nextInt();
adj = new ArrayList[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int u = s.nextInt() - 1, v = s.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
child = new int[n];
sub = new int[n];
fillsub(0, -1);
resl = new int[n];
resr = new int[n];
recur(0, 0, 1, -1);
for (int i = 0; i < n; i++)
w.println((resl[i] + 1) + " " + (resr[i] + 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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | 447f245d76c07bad058a6f2214db54fd | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.util.*;
import java.io.*;
public class TestD {
static BufferedReader br;
static StringTokenizer tokenizer;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
int n = nextInt();
ArrayList<Integer>[] adj = new ArrayList[n];
for(int i = 0; i < n; i++)
adj[i] = new ArrayList<Integer>();
for(int i = 0; i < n - 1; i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
ArrayList<Integer> ans = new ArrayList<Integer>();
ans.add(0);
DFS(ans, 0, adj, new boolean[n]);
int[] start = new int[n];
int[] end = new int[n];
for(int i = 0; i < 2 * n; i++) {
if(start[ans.get(i)] != 0) end[ans.get(i)] = i + 1;
else start[ans.get(i)] = i + 1;
}
PrintWriter out = new PrintWriter(System.out);
for(int i = 0; i < n; i++)
out.println(start[i] + " " + end[i]);
out.close();
}
public static void DFS(ArrayList<Integer> ans, int curr, ArrayList<Integer>[] adj, boolean[] visited) {
visited[curr] = true;
for(int e: adj[curr]) if(!visited[e]) ans.add(e);
ans.add(curr);
for(int i = adj[curr].size() - 1; i >= 0; i--)
if(!visited[adj[curr].get(i)])
DFS(ans, adj[curr].get(i), adj, visited);
}
public static String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = br.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | daef36ce311113909f7f896f78467369 | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
work();
out.flush();
}
ArrayList<Integer>[] graph;
int[][] ret;
int[] degree;
int max;
void work() {
int n=in.nextInt();
graph=(ArrayList<Integer>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
ret=new int[n][];
degree=new int[n];
for(int i=0;i<n-1;i++) {
int n1=in.nextInt()-1;
int n2=in.nextInt()-1;
graph[n1].add(n2);
graph[n2].add(n1);
degree[n1]++;
degree[n2]++;
}
dfs(0,new boolean[n],0);
for(int i=0;i<n;i++) {
out.println((ret[i][0]+1)+" "+(ret[i][1]+1));
}
}
private void dfs(int node,boolean[] vis,int cur) {
vis[node]=true;
int d=degree[node];
ret[node]=new int[] {cur,max+d+1};
int p=max+d;
max+=d+1;
for(int nn:graph[node]) {
if(!vis[nn]) {
degree[nn]--;
dfs(nn,vis,p--);
}
}
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(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());
}
} | Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output | |
PASSED | d793637aa1bb0b669c58ba92b17c9efc | train_000.jsonl | 1576766100 | We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of $$$n$$$ vertices, find a set of segments such that: both endpoints of each segment are integers from $$$1$$$ to $$$2n$$$, and each integer from $$$1$$$ to $$$2n$$$ should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair $$$(i, j)$$$ such that $$$i \ne j$$$, $$$i \in [1, n]$$$ and $$$j \in [1, n]$$$, the vertices $$$i$$$ and $$$j$$$ are connected with an edge if and only if the segments $$$i$$$ and $$$j$$$ intersect, but neither segment $$$i$$$ is fully contained in segment $$$j$$$, nor segment $$$j$$$ is fully contained in segment $$$i$$$. Can you solve this problem too? | 256 megabytes | //package cf1;
import java.io.*;
import java.util.*;
public class utkarsh {
BufferedReader br;
PrintWriter out;
long mod = (long) (1e9 + 7), inf = (long) (3e18);
class pair {
int L, R;
pair(int l, int r) {
L = l; R = r;
}
}
ArrayList <Integer> a[];
pair seg[];
int R;
void dfs(int s, int pt) {
int l = seg[s].R - 1;
for(int x : a[s]) {
if(x == pt) continue;
R += a[x].size();
seg[x].L = l--;
seg[x].R = R;
dfs(x, s);
}
}
void solve() {
int n = ni();
a = new ArrayList[n];
for(int i = 0; i < n; i++) a[i] = new ArrayList<>();
for(int i = 0; i < n-1; i++) {
int u = ni() - 1, v = ni() - 1;
a[u].add(v);
a[v].add(u);
}
seg = new pair[n];
for(int i = 0; i < n; i++) seg[i] = new pair(-1, -1);
seg[0].L = 1; seg[0].R = a[0].size() + 2;
R = seg[0].R;
dfs(0, -1);
for(int i = 0; i < n; i++) out.println(seg[i].L +" "+ seg[i].R);
}
long mp(long b, long e) {
long r = 1;
while(e > 0) {
if( (e&1) == 1 ) r = (r * b) % mod;
b = (b * b) % mod;
e >>= 1;
}
return r;
}
// -------- I/O Template -------------
char nc() {
return ns().charAt(0);
}
String nLine() {
try {
return br.readLine();
} catch(IOException e) {
return "-1";
}
}
double nd() {
return Double.parseDouble(ns());
}
long nl() {
return Long.parseLong(ns());
}
int ni() {
return Integer.parseInt(ns());
}
StringTokenizer ip;
String ns() {
if(ip == null || !ip.hasMoreTokens()) {
try {
ip = new StringTokenizer(br.readLine());
} catch(IOException e) {
throw new InputMismatchException();
}
}
return ip.nextToken();
}
void run() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) {
new utkarsh().run();
}
}
| Java | ["6\n1 2\n1 3\n3 4\n3 5\n2 6", "1"] | 2 seconds | ["9 12\n7 10\n3 11\n1 5\n2 4\n6 8", "1 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"divide and conquer",
"trees",
"dfs and similar"
] | 739e60a2fa71aff9a5c7e781db861d1e | The first line contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) β the number of vertices in the tree. Then $$$n - 1$$$ lines follow, each containing two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) denoting the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. | 2,200 | Print $$$n$$$ pairs of integers, the $$$i$$$-th pair should contain two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 2n$$$) β the endpoints of the $$$i$$$-th segment. All $$$2n$$$ integers you print should be unique. It is guaranteed that the answer always exists. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.