exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
listlengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED
|
a70bf0e56974f5bc05e96c188180abc6
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class DirectionalIncrease {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(System.out);
int t=Integer.parseInt(br.readLine());
while(t!=0){
solve(br,pr);
t--;
}
pr.flush();
pr.close();
}
public static void solve(BufferedReader br,PrintWriter pr) throws IOException{
int n=Integer.parseInt(br.readLine());
String[] temp=br.readLine().split(" ");
int lastIndex=n;
int[] nums=new int[n];
for(int i=n-1;i>=0;i--){
nums[i]=Integer.parseInt(temp[i]);
if(nums[i]!=0&&lastIndex==n){
lastIndex=i;
}
}
if(lastIndex==n){
pr.println("YES");
return;
}
long sum=0;
for(int i=0;i<=lastIndex;i++){
int num=Integer.parseInt(temp[i]);
sum+=num;
if(sum<=0&&i!=lastIndex){
pr.println("NO");
return;
}
}
pr.println(sum==0?"YES":"NO");
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
0f702cbed8fd399141cf1e48816d9fa3
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.util.*;
public class SelectionSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
boolean ans = true, checkCycleComplete = false;
long sum = 0;
for(int i=1; i<=n; i++)
{
long a = sc.nextInt();
sum+=a;
if(checkCycleComplete && a!=0) ans = false;
if(sum==0 && !checkCycleComplete) checkCycleComplete = true;
if(sum<0) ans = false;
}
if(ans&&sum==0) System.out.println("Yes");
else System.out.println("No");
}
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
7d49b96ac13442eb64519009991b64f9
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
public static Scanner obj = new Scanner(System.in);
public static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int len = obj.nextInt();
while (len-- != 0) {
int n=obj.nextInt();
long[] a=new long[n];
long sum=0;
int last=0;
for(int i=0;i<n;i++)
{
a[i]=obj.nextLong();
sum+=a[i];
if(a[i]!=0)last=i;
}
if(sum==0)
{
long c=0;
boolean ans=true;
for(int i=0;i<last;i++)
{
c+=a[i];
if(c<=0)
{
ans=false;
break;
}
}
if(ans)out.println("Yes");
else out.println("No");
}
else out.println("No");
}
out.flush();
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
e1b09043c550cf408e1a7137dc8b86ab
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int nt = sc.nextInt();
for(int f=0;f<nt;f++)
{
int n = sc.nextInt();
long s = 0;
boolean ok=true;
boolean hadZero = false;
for(int i=0;i<n;i++)
{
long a = sc.nextLong();
s+=a;
if(s<0)
{
ok = false;
}
if(s==0)
{
hadZero = true;
}
if(s>0 && hadZero)
{
ok = false;
}
}
if(s!=0)
{
ok = false;
}
if(ok)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
b9fc65037072e36532beda8193d55161
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
void pre() throws Exception{}
void solve(int TC) throws Exception {
int N = ni();
long[] A = new long[N];
for(int i = 0; i< N; i++)A[i] = nl();
boolean f = true;
long sum = 0;
for(int i = 0; i< N; i++){
sum += A[i];
if(sum < 0){
f = false;
break;
}
if(sum == 0){
for(int j = i+1; j< N; j++)if(A[j] != 0)f = false;
break;
}
}
f &= sum == 0;
pn(f?"Yes":"No");
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void exit(boolean b){if(!b)System.exit(0);}
final long IINF = Long.MAX_VALUE/2;
final int INF = Integer.MAX_VALUE/2;
DecimalFormat df = new DecimalFormat("0.000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-9;
static boolean multipleTC = true, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println("Runtime: " + (System.currentTimeMillis() - ct));
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 26).start();
else new Main().run();
}
int[][] make(int n, int e, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int[][] make(int n, int[] par, boolean f){
int[][] g = new int[n][];
int[] cnt = new int[n];
for(int x:par)cnt[x]++;
if(f)for(int i = 1; i< n; i++)cnt[i]++;
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 1; i< n-1; i++){
g[par[i]][--cnt[par[i]]] = i;
if(f)g[i][--cnt[i]] = par[i];
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int brute = 0;while(s>0){s/=10;brute++;}return brute;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object... o){for(Object oo:o)out.print(oo+" ");}
void pn(Object... o){
if(o.length == 0)out.println("");
for(int i = 0; i< o.length; i++){
out.print(o[i]);
out.print((i+1 == o.length?"\n":" "));
}
}
void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
45367efa7019b2023c937d935c46758b
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static FastReader sc=new FastReader();
static final Random random=new Random();
static long mod=1000000007L;
static HashMap<String,Integer>map=new HashMap<>();
public static void main(String args[]) throws IOException {
int t=sc.nextInt();
loop:
while(t-->0)
{
int n=sc.nextInt();
int[]arr=new int[n];
for(int i=0;i<n;i++)arr[i]=sc.nextInt();
long sum=Arrays.stream(arr).sum();
if(sum!=0){
print("NO");
continue;
}
int j=n-1;
while(j>=0&&arr[j]==0)j--;
long curr=0;
for(int i=0;i<=j;i++){
curr+=arr[i];
if(curr<0){
print("NO");
continue loop;
}
if(curr==0&&i!=j){
print("NO");
continue loop;
}
}
print("YES");
}
}
static int max(int a, int b)
{
if(a<b)
return b;
return a;
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static < E > void print(E res)
{
System.out.println(res);
}
static int gcd(int a,int b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static int abs(int a)
{
if(a<0)
return -1*a;
return a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int [] readintarray(int n) {
int res [] = new int [n];
for(int i = 0; i<n; i++)res[i] = nextInt();
return res;
}
long [] readlongarray(int n) {
long res [] = new long [n];
for(int i = 0; i<n; i++)res[i] = nextLong();
return res;
}
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
1ad5e79fa5de9e2f73f0373e85f8c179
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Q1693A {
static int mod = (int) (1e9 + 7);
static void solve() {
int n = i();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = l();
}
int lastNonZeroELem = n - 1;
while (lastNonZeroELem >= 0 && arr[lastNonZeroELem] == 0) {
lastNonZeroELem--;
}
if (lastNonZeroELem < 0) {
System.out.println("YES");
return;
}
if (arr[lastNonZeroELem] > 0) {
System.out.println("NO");
return;
}
long[] ans = new long[n];
for (int i = 0; i < lastNonZeroELem - 1; i++) {
ans[i] = 1;
}
ans[lastNonZeroELem - 1] = (int) Math.abs(arr[lastNonZeroELem]);
ans[lastNonZeroELem] = arr[lastNonZeroELem];
// System.out.println(Arrays.toString(ans));
for (int i = lastNonZeroELem-1; i >= 1; i--) {
long diff=ans[i]-arr[i];
if(diff<=0){
System.out.println("NO");
return;
}
ans[i]=arr[i];
ans[i-1]+=(diff-1);
// System.out.println(Arrays.toString(ans));
}
for(int i=0;i<n;i++){
if(arr[i]!=ans[i]){
System.out.println("NO");
return;
}
}
System.out.println("YES");
}
public static void main(String[] args) {
int test = i();
while (test-- > 0) {
solve();
}
}
// -----> POWER ---> long power(long x, long y) <----
// -----> LCM ---> long lcm(long x, long y) <----
// -----> GCD ---> long gcd(long x, long y) <----
// -----> SIEVE --> ArrayList<Integer> sieve(int N) <-----
// -----> NCR ---> long ncr(int n, int r) <----
// -----> BINARY_SEARCH ---> int binary_Search(long[]arr,long x) <----
// -----> (SORTING OF LONG, CHAR,INT) -->long[] sortLong(long[] a2)<--
// ----> DFS ---> void dfs(ArrayList<ArrayList<Integer>>edges,int child,int
// parent)<---
// ---> NODETOROOT --> ArrayList<Integer>
// node2Root(ArrayList<ArrayList<Integer>>edges,int child,int parent,int tofind)
// <--
// ---> LEVELS_TREE -->levels_Trees(ArrayList<HashSet<Integer>> edges, int
// child, int parent,int[]level,int currLevel) <--
// ---> K_THPARENT --> int k_thparent(int node,int[][]parent,int k) <---
// ---> TWOPOWERITHPARENTFILL --> void twoPowerIthParentFill(int[][]parent) <---
// -----> (INPUT OF INT,LONG ,STRING) -> int i() long l() String s()<-
// tempstart
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public 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);
}
}
static InputReader in = new InputReader(System.in);
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
edb6ac40a868a9190608e36306306106
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution {
static class FastReader {
private final BufferedReader br;
private StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public String nextLine() {
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
void solve() {
int n = sc.nextInt();
int[] a = new int[n];
long sum = 0;
boolean ok = true;
boolean flag = false;
for (int i = 0;i < n;i++) {
a[i] = sc.nextInt();
sum += a[i];
if (flag && a[i] != 0) ok = false;
if (sum < 0) {
ok = false;
} else if (sum == 0) {
flag = true;
}
}
if (sum != 0) ok = false;
System.out.println(ok ? "YES" : "NO");
}
static FastReader sc = new FastReader();
public static void main(String[] args) {
int t = sc.nextInt();
for (int i = 0;i < t;i++) {
new Solution().solve();
}
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
8b9cc4594429584a5f99652f5c285887
|
train_109.jsonl
|
1655390100
|
We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.
|
256 megabytes
|
/*
I am dead inside
Do you like NCT, sKz, BTS?
5 4 3 2 1 Moonwalk
Imma knock it down like domino
Is this what you want? Is this what you want?
Let's ttalkbocky about that :()
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class x1693A
{
public static void main(String followthekkathyoninsta[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
while(T-->0)
{
st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int[] arr = readArr(N, infile, st);
long sum = 0L;
for(int x: arr)
sum += x;
if(sum == 0)
{
String res = "YES";
while(N >= 1 && arr[N-1] == 0)
N--;
if(N >= 1)
{
long pos = 0L;
long neg = 0L;
for(int i=0; i < N; i++)
{
int x = arr[i];
if(x >= 0)
pos += x;
else
{
neg += -1*x;
if(neg > pos)
res = "no";
}
if(pos == neg && i != N-1)
res = "nO";
}
}
sb.append(res+"\n");
}
else
sb.append("NO\n");
}
System.out.print(sb);
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
}
|
Java
|
["7\n2\n1 0\n4\n2 -1 -1 0\n4\n1 -4 3 0\n4\n1 -1 1 -1\n5\n1 2 3 4 -10\n7\n2 -1 1 -2 0 0 0\n1\n0"]
|
1 second
|
["No\nYes\nNo\nNo\nYes\nYes\nYes"]
|
NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$
|
Java 11
|
standard input
|
[
"greedy"
] |
9f0ffcbd0ce62a365a1ecbb4a2c1de3e
|
The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,300
|
For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
|
standard output
| |
PASSED
|
662a7abe722cc109442e92049b3c48a8
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
long[] maxUp = new long[N + 1];
int moves = 0;
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new LinkedList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public List<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
81e4ec5cfaa05e43489160ea41b82fd4
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
long[] maxUp = new long[N + 1];
int moves = 0;
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new LinkedList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return sgn < 0 ? -res : res;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
5510e681b6bc001bad79f8dea96e3dd4
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
long[] maxUp = new long[N + 1];
int moves = 0;
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new LinkedList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
263ef39da37ad28674ede736cd6040ce
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
int uID = u.id;
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[uID]) {
maxUp[uID] = Math.min(childSum, R[uID]);
} else {
maxUp[uID] = R[uID];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new ArrayList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
179ccbb4a22001deee8f64001b896eff
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.function.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<IntList> nodeIDsByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodeIDsByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (int d = nodeIDsByDepth.size() - 1; d >= 0; --d) {
IntList lst = nodeIDsByDepth.get(d);
for (int i = 0; i < lst.size(); ++i) {
int uID = lst.get(i);
long childSum = 0;
for (Node v : nodes[uID].next) {
childSum += maxUp[v.id];
}
if (childSum >= L[uID]) {
maxUp[uID] = Math.min(childSum, R[uID]);
} else {
maxUp[uID] = R[uID];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<IntList> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new IntList(4));
}
IntList lst = nodesByDepth.get(d);
lst.add(u.id);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static class IntList {
public int[] arr;
public int pos;
public IntList(int capacity) {
this.arr = new int[capacity];
}
public IntList() {
this(10);
}
public IntList(IntList other) {
this.arr = Arrays.copyOfRange(other.arr, 0, other.pos);
this.pos = other.pos;
}
public void add(int x) {
if (pos >= arr.length) {
resize(arr.length << 1);
}
arr[pos++] = x;
}
public void insert(int i, int x) {
if (pos >= arr.length) {
resize(arr.length << 1);
}
System.arraycopy(arr, i, arr, i + 1, pos++ - i);
arr[i] = x;
}
public int get(int i) {
return arr[i];
}
public void set(int i, int x) {
arr[i] = x;
}
public void clear() {
pos = 0;
}
public int size() {
return pos;
}
public boolean isEmpty() {
return pos == 0;
}
public int last() {
return arr[pos - 1];
}
public int removeLast() {
return arr[--pos];
}
public void push(int x) {
add(x);
}
public int pop() {
return removeLast();
}
public boolean remove(int x) {
for (int i = 0; i < pos; ++i) {
if (arr[i] == x) {
removeAt(i);
return true;
}
}
return false;
}
public void removeAt(int i) {
System.arraycopy(arr, i + 1, arr, i, --pos - i);
}
public IntList subList(int fromIndex, int toIndexExclusive) {
IntList lst = new IntList();
lst.arr = Arrays.copyOfRange(arr, fromIndex, toIndexExclusive);
lst.pos = toIndexExclusive - fromIndex;
return lst;
}
public void forEach(IntConsumer consumer) {
for (int i = 0; i < pos; ++i) {
consumer.accept(arr[i]);
}
}
public int[] toArray() {
return Arrays.copyOf(arr, pos);
}
public static IntList of(int... items) {
IntList lst = new IntList(items.length);
System.arraycopy(items, 0, lst.arr, 0, items.length);
lst.pos = items.length;
return lst;
}
public String join(CharSequence sep) {
StringBuilder sb = new StringBuilder();
joinToBuffer(sb, sep);
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
joinToBuffer(sb, ", ");
sb.append(']');
return sb.toString();
}
private void resize(int newCapacity) {
arr = Arrays.copyOf(arr, newCapacity);
}
private void joinToBuffer(StringBuilder sb, CharSequence sep) {
for (int i = 0; i < pos; ++i) {
if (i > 0) {
sb.append(sep);
}
sb.append(arr[i]);
}
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
989dffb83cf350896b6ba55a3a9bdd3d
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.function.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<IntList> nodeIDsByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodeIDsByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (int d = nodeIDsByDepth.size() - 1; d >= 0; --d) {
IntList lst = nodeIDsByDepth.get(d);
for (int i = 0; i < lst.size(); ++i) {
int uID = lst.get(i);
long childSum = 0;
for (Node v : nodes[uID].next) {
childSum += maxUp[v.id];
}
if (childSum >= L[uID]) {
maxUp[uID] = Math.min(childSum, R[uID]);
} else {
maxUp[uID] = R[uID];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<IntList> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new IntList());
}
IntList lst = nodesByDepth.get(d);
lst.add(u.id);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static class IntList {
public int[] arr;
public int pos;
public IntList(int capacity) {
this.arr = new int[capacity];
}
public IntList() {
this(10);
}
public IntList(IntList other) {
this.arr = Arrays.copyOfRange(other.arr, 0, other.pos);
this.pos = other.pos;
}
public void add(int x) {
if (pos >= arr.length) {
resize(arr.length << 1);
}
arr[pos++] = x;
}
public void insert(int i, int x) {
if (pos >= arr.length) {
resize(arr.length << 1);
}
System.arraycopy(arr, i, arr, i + 1, pos++ - i);
arr[i] = x;
}
public int get(int i) {
return arr[i];
}
public void set(int i, int x) {
arr[i] = x;
}
public void clear() {
pos = 0;
}
public int size() {
return pos;
}
public boolean isEmpty() {
return pos == 0;
}
public int last() {
return arr[pos - 1];
}
public int removeLast() {
return arr[--pos];
}
public void push(int x) {
add(x);
}
public int pop() {
return removeLast();
}
public boolean remove(int x) {
for (int i = 0; i < pos; ++i) {
if (arr[i] == x) {
removeAt(i);
return true;
}
}
return false;
}
public void removeAt(int i) {
System.arraycopy(arr, i + 1, arr, i, --pos - i);
}
public IntList subList(int fromIndex, int toIndexExclusive) {
IntList lst = new IntList();
lst.arr = Arrays.copyOfRange(arr, fromIndex, toIndexExclusive);
lst.pos = toIndexExclusive - fromIndex;
return lst;
}
public void forEach(IntConsumer consumer) {
for (int i = 0; i < pos; ++i) {
consumer.accept(arr[i]);
}
}
public int[] toArray() {
return Arrays.copyOf(arr, pos);
}
public static IntList of(int... items) {
IntList lst = new IntList(items.length);
System.arraycopy(items, 0, lst.arr, 0, items.length);
lst.pos = items.length;
return lst;
}
public String join(CharSequence sep) {
StringBuilder sb = new StringBuilder();
joinToBuffer(sb, sep);
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
joinToBuffer(sb, ", ");
sb.append(']');
return sb.toString();
}
private void resize(int newCapacity) {
arr = Arrays.copyOf(arr, newCapacity);
}
private void joinToBuffer(StringBuilder sb, CharSequence sep) {
for (int i = 0; i < pos; ++i) {
if (i > 0) {
sb.append(sep);
}
sb.append(arr[i]);
}
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
169b2b9ef9336df0359dcc063caeda9f
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new ArrayList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
f586974c596d942f47e9c88f2cb663e3
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
NodeList[] nodesByDepth = new NodeList[N];
dfs(nodes[1], 0, nodesByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (int d = N - 1; d >= 0; --d) {
NodeList lst = nodesByDepth[d];
if (lst == null) {
continue;
}
for (Node u : lst) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static class NodeList extends LinkedList<Node> {
private static final long serialVersionUID = -75261480487914309L;
}
private static void dfs(Node u, int d, NodeList[] nodesByDepth) {
NodeList lst = nodesByDepth[d];
if (lst == null) {
lst = new NodeList();
nodesByDepth[d] = lst;
}
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
7b4395768cb7acd9a7d8c90514d0d103
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
Collections.reverse(nodesByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (List<Node> lst : nodesByDepth) {
for (Node u : lst) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new ArrayList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
1de36f249755bc3be7066c2f619a0764
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<LinkedList<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
Collections.reverse(nodesByDepth);
int moves = 0;
long[] maxUp = new long[N + 1];
for (LinkedList<Node> lst : nodesByDepth) {
for (Node u : lst) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<LinkedList<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new LinkedList<>());
}
LinkedList<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
6858a60377399a2119460a318e30471b
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.List;
import java.util.*;
public class FakePlasticTrees {
public static void main(String[] args) {
InputReader sc = new InputReader(System.in);
int testCases = sc.nextInt();
for(int t=0; t<testCases; t++) {
int n = sc.nextInt();
List<List<Integer>> tree = new ArrayList<>();
for(int i=0;i<n;i++) {
tree.add(new ArrayList<>());
}
for(int i=1;i<n;i++) {
int p = sc.nextInt();
tree.get(p-1).add(i);
}
int[][] range = new int[n][2];
for(int i=0;i<n;i++) {
int l = sc.nextInt();
int r = sc.nextInt();
range[i][0] = l;
range[i][1] = r;
}
int leafCount = 0;
for(int i=0;i<n;i++) {
if(tree.get(i).size()==0) leafCount++;
}
long[] ans = {(leafCount+0L)};
dfs(tree, 0, ans, range);
System.out.println(ans[0]);
}
}
static long dfs(List<List<Integer>> tree, int currNode, long[] ans, int[][] range) {
if(tree.get(currNode).size()==0) return range[currNode][1];
long childSum = 0L;
for(int child: tree.get(currNode)) {
childSum += dfs(tree, child, ans, range);
}
if(childSum<range[currNode][0]) {
ans[0]++;
childSum = range[currNode][1];
}
return (childSum>=range[currNode][1]?range[currNode][1]:childSum);
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream st) {
br = new BufferedReader(new InputStreamReader(st));
}
String next() {
while(st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
ex.printStackTrace();
}
}
return st.nextToken();
}
Integer nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
c4b8ed5032767be9bffed505ff5ca11c
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
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.math.BigInteger;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class c731{
public static void main(String[] args) throws IOException{
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter pt = new PrintWriter(System.out);
FastReader sc = new FastReader();
int o1 = sc.nextInt();
StringBuilder sb = new StringBuilder();
for(int t1 = 0 ; t1<o1;t1++) {
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 1 ; i<n;i++) {
arr[i] = sc.nextInt();
}
coup[] wt = new coup[n];
for(int i = 0 ; i<n;i++) {
int a = sc.nextInt();
int b = sc.nextInt();
wt[i] = new coup(a,b);
}
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0 ; i<n;i++) {
map.put(i+1, new ArrayList<Integer>());
}
for(int i = 1; i<n;i++) {
map.get(arr[i]).add(i+1);
}
long ans = 0;
for(int x : map.keySet()) {
if(map.get(x).size()==0) {
ans++;
}
}
// ans++;
// for(int x : map.keySet()) {
//// if(map.get(x).size() == 0) {
//// continue;
//// }
// long val = 0;
// for(int y : map.get(x)) {
// val += wt[y-1].b;
// }
// if(val<wt[x-1].a) {
// ans+= map.get(x).size();
// }
//
// }
long[] self = new long[n+1];
long[] val = new long[1];
dfs(map, 1, self, wt, val);
// ans+=val[0];
long v = val[0];
// sb.append(v + "\n");
System.out.println(v);
}
// System.out.println(sb);
}
//------------------------------------------------------------------------------------------------------------------------------------------------
public static void dfs(HashMap<Integer, ArrayList<Integer>> map, int s, long[] self, coup[] wt, long[] ans) {
for(int x : map.get(s)) {
dfs(map, x, self, wt,ans);
}
long val = 0;
for(int x : map.get(s)) {
val += self[x-1];
}
if(val<wt[s-1].a) {
self[s-1] = wt[s-1].b;
ans[0]++;
}else {
self[s-1] = Math.min(val, wt[s-1].b);
}
}
public static ArrayList<Long> printDivisors(long n)
{
ArrayList<Long> al = new ArrayList<>();
for (long i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)al.add(i);
else {
al.add(i);
al.add(n/i);
}
}
}
return al;
}
public static boolean palin(String s) {
int n = s.length();
int i = 0;
int j = n-1;
while(i<=j) {
if(s.charAt(i)!=s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public static boolean check(int[] arr , int n , int v , int l ) {
int x = v/2;
int y = v/2;
// System.out.println(x + " " + y);
if(v%2 == 1 ) {
x++;
}
for(int i = 0 ; i<n;i++) {
int d = l - arr[i];
int c = Math.min(d/2, y);
y -= c;
arr[i] -= c*2;
if(arr[i] > x) {
return false;
}
x -= arr[i];
}
return true;
}
public static int cnt_set(long x) {
long v = 1l;
int c =0;
int f = 0;
while(v<=x) {
if((v&x)!=0) {
c++;
}
v = v<<1;
}
return c;
}
public static int lis(int[] arr,int[] dp) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
dp[0]= 1;
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>x) {
al.add(arr[i]);
}else {
int v = lower_bound(al, 0, al.size(), arr[i]);
// System.out.println(v);
al.set(v, arr[i]);
}
dp[i] = al.size();
}
//return al.size();
return al.size();
}
public static int lis2(int[] arr,int[] dp) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(-arr[n-1]);
dp[n-1] = 1;
// System.out.println(al);
for(int i = n-2 ; i>=0;i--) {
int x = al.get(al.size()-1);
// System.out.println(-arr[i] + " " + i + " " + x);
if((-arr[i])>x) {
al.add(-arr[i]);
}else {
int v = lower_bound(al, 0, al.size(), -arr[i]);
// System.out.println(v);
al.set(v, -arr[i]);
}
dp[i] = al.size();
}
//return al.size();
return al.size();
}
static int cntDivisors(int n){
int cnt = 0;
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
cnt++;
else
cnt+=2;
}
}
return cnt;
}
public static long power(long x, long y, long p){
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0){
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long ncr(long[] fac, int n , int r , long m) {
if(r>n) {
return 0;
}
return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m;
}
public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (arr.get(mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==arr.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (arr.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==arr.size())
{
return -1;
}
return s;
}
// -----------------------------------------------------------------------------------------------------------------------------------------------
public static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public static long modInverse(long a, long m){
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process
// same as Euclid's algo
m = a % m;
a = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
//_________________________________________________________________________________________________________________________________________________________________
// private static int[] parent;
// private static int[] size;
public static int find(int[] parent, int u) {
while(u != parent[u]) {
parent[u] = parent[parent[u]];
u = parent[u];
}
return u;
}
private static void union(int[] parent,int[] size,int u, int v) {
int rootU = find(parent,u);
int rootV = find(parent,v);
if(rootU == rootV) {
return;
}
if(size[rootU] < size[rootV]) {
parent[rootU] = rootV;
size[rootV] += size[rootU];
} else {
parent[rootV] = rootU;
size[rootU] += size[rootV];
}
}
//-----------------------------------------------------------------------------------------------------------------------------------
//segment tree
//for finding minimum in range
public static void build(long [] seg,long []arr,int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build(seg,arr,2*idx+1, lo, mid);
build(seg,arr,idx*2+2, mid +1, hi);
seg[idx] = seg[idx*2+1] + seg[idx*2+2];
}
//for finding minimum in range
public static long query(long[]seg,int idx , int lo , int hi , int l , int r) {
if(lo>=l && hi<=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return 0;
}
int mid = (lo + hi)/2;
long left = query(seg,idx*2 +1, lo, mid, l, r);
long right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
return left + right;
}
public static void build2(long [] seg,long []arr,int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build2(seg,arr,2*idx+1, lo, mid);
build2(seg,arr,idx*2+2, mid +1, hi);
seg[idx] = Math.max(seg[idx*2+1],seg[idx*2+2]);
}
public static long query2(long[]seg,int idx , int lo , int hi , int l , int r) {
if(r<l) {
return Long.MIN_VALUE;
}
if(lo>=l && hi<=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return Long.MIN_VALUE;
}
int mid = (lo + hi)/2;
long left = query(seg,idx*2 +1, lo, mid, l, r);
long right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
return Math.max(left, right);
}
public static void update(boolean[]seg,int idx, int lo , int hi , int node , boolean val) {
if(lo == hi) {
seg[idx] = val;
}else {
int mid = (lo + hi )/2;
if(node<=mid && node>=lo) {
update(seg, idx * 2 +1, lo, mid, node, val);
}else {
update(seg, idx*2 + 2, mid + 1, hi, node, val);
}
seg[idx] = seg[idx*2 + 1] & seg[idx*2 + 2];
}
//
}
//---------------------------------------------------------------------------------------------------------------------------------------
//
//static void shuffleArray(int[] ar)
//{
// // If running on Java 6 or older, use `new Random()` on RHS here
// Random rnd = ThreadLocalRandom.current();
// for (int i = ar.length - 1; i > 0; i--)
// {
// int index = rnd.nextInt(i + 1);
// // Simple swap
// int a = ar[index];
// ar[index] = ar[i];
// ar[i] = a;
// }
//}
// static void shuffleArray(coup[] ar)
// {
// // If running on Java 6 or older, use `new Random()` on RHS here
// Random rnd = ThreadLocalRandom.current();
// for (int i = ar.length - 1; i > 0; i--)
// {
// int index = rnd.nextInt(i + 1);
// // Simple swap
// coup a = ar[index];
// ar[index] = ar[i];
// ar[i] = a;
// }
// }
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
}
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;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
class coup{
int a;
int b;
public coup(int a , int b) {
this.a = a;
this.b = b;
}
}
class dob{
int a;
double b;
public dob(int a , double b) {
this.a = a;
this.b = b;
}
}
class trip{
int a;
int b;
int c;
public trip(int a , int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
6467680fc5fed90c4e9a85d6ef11b080
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
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.math.BigInteger;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class c731{
public static void main(String[] args) throws IOException{
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter pt = new PrintWriter(System.out);
FastReader sc = new FastReader();
int o1 = sc.nextInt();
StringBuilder sb = new StringBuilder();
for(int t1 = 0 ; t1<o1;t1++) {
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 1 ; i<n;i++) {
arr[i] = sc.nextInt();
}
coup[] wt = new coup[n];
for(int i = 0 ; i<n;i++) {
int a = sc.nextInt();
int b = sc.nextInt();
wt[i] = new coup(a,b);
}
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0 ; i<n;i++) {
map.put(i+1, new ArrayList<Integer>());
}
for(int i = 1; i<n;i++) {
map.get(arr[i]).add(i+1);
}
long ans = 0;
for(int x : map.keySet()) {
if(map.get(x).size()==0) {
ans++;
}
}
// ans++;
// for(int x : map.keySet()) {
//// if(map.get(x).size() == 0) {
//// continue;
//// }
// long val = 0;
// for(int y : map.get(x)) {
// val += wt[y-1].b;
// }
// if(val<wt[x-1].a) {
// ans+= map.get(x).size();
// }
//
// }
long[] self = new long[n+1];
long[] val = new long[1];
dfs(map, 1, self, wt, val);
// ans+=val[0];
long v = val[0];
sb.append(v + "\n");
}
System.out.println(sb);
}
//------------------------------------------------------------------------------------------------------------------------------------------------
public static void dfs(HashMap<Integer, ArrayList<Integer>> map, int s, long[] self, coup[] wt, long[] ans) {
for(int x : map.get(s)) {
dfs(map, x, self, wt,ans);
}
long val = 0;
for(int x : map.get(s)) {
val += self[x-1];
}
if(val<wt[s-1].a) {
self[s-1] = wt[s-1].b;
ans[0]++;
}else {
self[s-1] = Math.min(val, wt[s-1].b);
}
}
public static ArrayList<Long> printDivisors(long n)
{
ArrayList<Long> al = new ArrayList<>();
for (long i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)al.add(i);
else {
al.add(i);
al.add(n/i);
}
}
}
return al;
}
public static boolean palin(String s) {
int n = s.length();
int i = 0;
int j = n-1;
while(i<=j) {
if(s.charAt(i)!=s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public static boolean check(int[] arr , int n , int v , int l ) {
int x = v/2;
int y = v/2;
// System.out.println(x + " " + y);
if(v%2 == 1 ) {
x++;
}
for(int i = 0 ; i<n;i++) {
int d = l - arr[i];
int c = Math.min(d/2, y);
y -= c;
arr[i] -= c*2;
if(arr[i] > x) {
return false;
}
x -= arr[i];
}
return true;
}
public static int cnt_set(long x) {
long v = 1l;
int c =0;
int f = 0;
while(v<=x) {
if((v&x)!=0) {
c++;
}
v = v<<1;
}
return c;
}
public static int lis(int[] arr,int[] dp) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
dp[0]= 1;
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>x) {
al.add(arr[i]);
}else {
int v = lower_bound(al, 0, al.size(), arr[i]);
// System.out.println(v);
al.set(v, arr[i]);
}
dp[i] = al.size();
}
//return al.size();
return al.size();
}
public static int lis2(int[] arr,int[] dp) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(-arr[n-1]);
dp[n-1] = 1;
// System.out.println(al);
for(int i = n-2 ; i>=0;i--) {
int x = al.get(al.size()-1);
// System.out.println(-arr[i] + " " + i + " " + x);
if((-arr[i])>x) {
al.add(-arr[i]);
}else {
int v = lower_bound(al, 0, al.size(), -arr[i]);
// System.out.println(v);
al.set(v, -arr[i]);
}
dp[i] = al.size();
}
//return al.size();
return al.size();
}
static int cntDivisors(int n){
int cnt = 0;
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
cnt++;
else
cnt+=2;
}
}
return cnt;
}
public static long power(long x, long y, long p){
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0){
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long ncr(long[] fac, int n , int r , long m) {
if(r>n) {
return 0;
}
return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m;
}
public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (arr.get(mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==arr.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (arr.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==arr.size())
{
return -1;
}
return s;
}
// -----------------------------------------------------------------------------------------------------------------------------------------------
public static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public static long modInverse(long a, long m){
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process
// same as Euclid's algo
m = a % m;
a = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
//_________________________________________________________________________________________________________________________________________________________________
// private static int[] parent;
// private static int[] size;
public static int find(int[] parent, int u) {
while(u != parent[u]) {
parent[u] = parent[parent[u]];
u = parent[u];
}
return u;
}
private static void union(int[] parent,int[] size,int u, int v) {
int rootU = find(parent,u);
int rootV = find(parent,v);
if(rootU == rootV) {
return;
}
if(size[rootU] < size[rootV]) {
parent[rootU] = rootV;
size[rootV] += size[rootU];
} else {
parent[rootV] = rootU;
size[rootU] += size[rootV];
}
}
//-----------------------------------------------------------------------------------------------------------------------------------
//segment tree
//for finding minimum in range
public static void build(long [] seg,long []arr,int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build(seg,arr,2*idx+1, lo, mid);
build(seg,arr,idx*2+2, mid +1, hi);
seg[idx] = seg[idx*2+1] + seg[idx*2+2];
}
//for finding minimum in range
public static long query(long[]seg,int idx , int lo , int hi , int l , int r) {
if(lo>=l && hi<=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return 0;
}
int mid = (lo + hi)/2;
long left = query(seg,idx*2 +1, lo, mid, l, r);
long right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
return left + right;
}
public static void build2(long [] seg,long []arr,int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build2(seg,arr,2*idx+1, lo, mid);
build2(seg,arr,idx*2+2, mid +1, hi);
seg[idx] = Math.max(seg[idx*2+1],seg[idx*2+2]);
}
public static long query2(long[]seg,int idx , int lo , int hi , int l , int r) {
if(r<l) {
return Long.MIN_VALUE;
}
if(lo>=l && hi<=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return Long.MIN_VALUE;
}
int mid = (lo + hi)/2;
long left = query(seg,idx*2 +1, lo, mid, l, r);
long right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
return Math.max(left, right);
}
public static void update(boolean[]seg,int idx, int lo , int hi , int node , boolean val) {
if(lo == hi) {
seg[idx] = val;
}else {
int mid = (lo + hi )/2;
if(node<=mid && node>=lo) {
update(seg, idx * 2 +1, lo, mid, node, val);
}else {
update(seg, idx*2 + 2, mid + 1, hi, node, val);
}
seg[idx] = seg[idx*2 + 1] & seg[idx*2 + 2];
}
//
}
//---------------------------------------------------------------------------------------------------------------------------------------
//
//static void shuffleArray(int[] ar)
//{
// // If running on Java 6 or older, use `new Random()` on RHS here
// Random rnd = ThreadLocalRandom.current();
// for (int i = ar.length - 1; i > 0; i--)
// {
// int index = rnd.nextInt(i + 1);
// // Simple swap
// int a = ar[index];
// ar[index] = ar[i];
// ar[i] = a;
// }
//}
// static void shuffleArray(coup[] ar)
// {
// // If running on Java 6 or older, use `new Random()` on RHS here
// Random rnd = ThreadLocalRandom.current();
// for (int i = ar.length - 1; i > 0; i--)
// {
// int index = rnd.nextInt(i + 1);
// // Simple swap
// coup a = ar[index];
// ar[index] = ar[i];
// ar[i] = a;
// }
// }
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
}
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;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
class coup{
int a;
int b;
public coup(int a , int b) {
this.a = a;
this.b = b;
}
}
class dob{
int a;
double b;
public dob(int a , double b) {
this.a = a;
this.b = b;
}
}
class trip{
int a;
int b;
int c;
public trip(int a , int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
7d62790738e084d2e4ab4c3134e6f37f
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
List<List<Integer>> adj = new ArrayList<>();
for(int i=0;i<=n;i++) adj.add(new ArrayList<>());
for(int i=2;i<=n;i++) {
int p = sc.nextInt();
adj.get(p).add(i);
}
int[][] range = new int[n+1][2];
for(int i=1;i<=n;i++) {
range[i][0] = sc.nextInt();
range[i][1] = sc.nextInt();
}
int[] ans = new int[1];
util(1, adj, range, ans);
System.out.println(ans[0]);
}
// ####################
}
// ####################
static long util(int node, List<List<Integer>> adj, int[][] range, int[] ans) {
long sum = 0;
for(int child : adj.get(node)) {
long fc = util(child, adj, range, ans);
sum += fc;
}
long l = range[node][0], r = range[node][1];
if(sum >= l) {
return Math.min(r, sum);
}else {
ans[0] += 1;
return r;
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
8c1c2b9db11a904ed54cceb9f1e66555
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
List<List<Integer>> adj = new ArrayList<>();
for(int i=0;i<=n;i++) adj.add(new ArrayList<>());
for(int i=2;i<=n;i++) {
int p = sc.nextInt();
adj.get(p).add(i);
}
int[][] range = new int[n+1][2];
for(int i=1;i<=n;i++) {
range[i][0] = sc.nextInt();
range[i][1] = sc.nextInt();
}
int[] ans = new int[1];
util(1, adj, range, ans);
System.out.println(ans[0]);
}
// ####################
}
// ####################
static long util(int node, List<List<Integer>> adj, int[][] range, int[] ans) {
long sum = 0;
for(int child : adj.get(node)) {
long fc = util(child, adj, range, ans);
sum += fc;
}
long l = range[node][0], r = range[node][1];
if(sum >= l) {
return Math.min(r, sum);
}else {
ans[0] += 1;
return r;
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
2d90e93128eb0c83a24923caf8259071
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
public class Test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
while(tc-->0) {
int n = sc.nextInt();
List<List<Integer>> adj = new ArrayList<>();
for(int i=0;i<=n;i++) adj.add(new ArrayList<>());
for(int i=2;i<=n;i++) {
int p = sc.nextInt();
adj.get(p).add(i);
}
int[][] range = new int[n+1][2];
for(int i=1;i<=n;i++) {
range[i][0] = sc.nextInt();
range[i][1] = sc.nextInt();
}
int[] ans = new int[1];
util(1, adj, range, ans);
System.out.println(ans[0]);
}
// ####################
}
// ####################
static long util(int node, List<List<Integer>> adj, int[][] range, int[] ans) {
long sum = 0;
for(int child : adj.get(node)) {
long fc = util(child, adj, range, ans);
sum += fc;
}
long l = range[node][0], r = range[node][1];
if(sum >= l) {
return Math.min(r, sum);
}else {
ans[0] += 1;
return r;
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
2af4203634874ba2490683f71ac23f6b
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
//import java.io.*;
//import java.util.ArrayList;
//import java.util.Arrays;
//
//public class Codeforces
//{
// public static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
// public static BufferedWriter write = new BufferedWriter(new OutputStreamWriter(System.out));
//
// private static void Solution() throws IOException {
//
//
//
//// long n = Long.parseLong(read.readLine().trim());
// int n = Integer.parseInt(read.readLine());
//// int [] array = Arrays.stream(read.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
//
//// String string = read.readLine().trim();
//// String[] binary = read.readLine().split("");
//// String[] string = read.readLine().split(" " );
//// int a = Integer.parseInt(string[0]);
//// int b = Integer.parseInt(string[1]);
//// int k = Integer.parseInt(string[2]);
//// int z = Integer.parseInt(string[3]);
// int [] array = Arrays.stream(read.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
////
//// ArrayList<ArrayList<Integer>> list = new ArrayList<>();
//// for (int i = 0; i <= n; i++) list.add(new ArrayList<>());
//// Arrays.fill(dp,-1);
////
//// Arrays.sort(new int[10], Collections.reverseOrder());
////
//// for (int i = 0; i < n - 1; i++) {
//// String[] str = read.readLine().split(" ");
//// int x = Integer.parseInt(str[0]);
//// int y = Integer.parseInt(str[1]);
//// list.get(x).add(y);
//// list.get(y).add(x);
//// }
//
// int min = array[0];
// for (int i = 1; i < n; i++) {
// if(array[i] < min){
// min = array[i];
// }
// }
//
// long count = Math.abs(min);
// long ans = Integer.MAX_VALUE;
//
// for (int i = 0; i < n; i++) {
// array[i] += (-1*min);
// }
// ArrayList<Integer> list = new ArrayList<>();
// for (int i = 0; i < n; i++) {
// if(array[i] == 0)
// list.add(i);
// }
//
// for(int index : list) {
// count = Math.abs(min);
// int add = 0;
// int sub = 0;
// for (int i = index - 1; i > -1; i--) {
// int temp = add + sub + array[i];
// if (temp > 0) {
// sub = (-1 * temp);
// count += temp;
// } else if (temp < 0) {
// add = (-1 * temp);
// count += (-1 * temp);
// }
// }
//// add = 0;
// sub = 0;
// int t = add;
//// write.write(count+ " " + add+" "+ sub + "\n");
//
//
// for (int i = index + 1; i < n; i++) {
// int temp = add + sub + array[i];
// if (temp > 0) {
// sub = (-1 * temp);
// count += temp;
// } else if (temp < 0) {
// add = (-1 * temp);
// count += (-1 * temp);
// }
// }
//
// if (t < add)
// count += add;
//
// write.write(count + " ");
// ans = Math.min(ans,count);
// }
// write.write(ans + "\n");
//
//
//
// }
//
// public static void main(String[] args) throws java.lang.Exception{
//
// long testCases = Long.parseLong(read.readLine());
//
// for(int it = 0; it < testCases ; it++){
//
// Solution();
// }
// write.flush();
// write.close();
// read.close();
//
// }
//
//}
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Codeforces
{
static class Pair{
long count;
long max;
public Pair(long count, long max) {
this.count = count;
this.max = max;
}
}
public static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
public static BufferedWriter write = new BufferedWriter(new OutputStreamWriter(System.out));
public static Scanner scan = new Scanner(System.in);
private static boolean[] prime;
private static final int MOD = 1000000007;
private static int[] factorial = new int[100001];
private static Pair dfs(ArrayList<ArrayList<Integer>> tree, int node, int[] minArray, int[] maxArray) throws IOException {
if(tree.get(node).size() == 0){
return new Pair(1, maxArray[node]);
}
long count = 0;
long max = 0;
for(int a : tree.get(node)){
Pair p = dfs(tree,a,minArray,maxArray);
count += p.count;
max += p.max;
}
if(max < minArray[node])
return new Pair(count+1, maxArray[node]);
else if(max <= maxArray[node])
return new Pair(count, max);
else
return new Pair(count,maxArray[node]);
}
public static void main(String[] kshg) throws java.lang.Exception{
long testCases = Long.parseLong(read.readLine().trim());
// long testCases = scan.nextLong();
for(int it = 0; it < testCases ; it++){
int n = Integer.parseInt(read.readLine());
int [] array = Arrays.stream(read.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();
// long [] array = Arrays.stream(read.readLine().split(" ")).mapToLong(Long::parseLong).toArray();
// String[] string = read.readLine().split(" " );
// int n = Integer.parseInt(string[0]);
// int k = Integer.parseInt(string[1]);
// int[] array = Arrays.stream(read.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for (int i = 0; i <= n; i++) {
tree.add(new ArrayList<>());
}
for (int i = 0; i < array.length; i++) {
tree.get(array[i]).add(i+2);
}
int[] minArray = new int[n+1];
int[] maxArray = new int[n+1];
for (int i = 1; i <= n; i++) {
String[] string = read.readLine().split(" " );
minArray[i] = Integer.parseInt(string[0]);
maxArray[i] = Integer.parseInt(string[1]);
}
// for (int i = 1; i <= n; i++) {
// write.write(i + "->");
// for(int a : tree.get(i)){
// write.write(a + " ");
// }
// write.write("\n");
// }
Pair p = dfs(tree,1,minArray,maxArray);
write.write(p.count + "\n");
}
write.flush();
write.close();
read.close();
}
private static void sieve(){
for (int i = 2; i*i <= MOD; i++) {
if(!prime[i]){
for (int j = i*i; j < MOD; j+=i) {
prime[j] = true;
}
}
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int binarySearch(int[] arr, int l, int h, int key) {
if (l > h)
return -1;
int mid = (l + h) / 2;
if (arr[mid] == key)
return mid;
if (key > arr[mid])
return binarySearch(arr, mid + 1, h, key);
return binarySearch(arr, l, mid - 1, key);
}
private static int binarySearch(long[] arr, int l, int h, long key){
if (l > h)
return -1;
int mid = (l + h) / 2;
if (arr[mid] == key)
return mid;
if (key > arr[mid])
return binarySearch(arr, mid + 1, h, key);
return binarySearch(arr, l, mid - 1, key);
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
346d43a56cc06d0314d13e4ba3d48a12
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
/*
I am dead inside
Do you like NCT, sKz, BTS?
5 4 3 2 1 Moonwalk
Imma knock it down like domino
Is this what you want? Is this what you want?
Let's ttalkbocky about that :()
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class x1693B
{
static int[][] edges;
public static void main(String followthekkathyoninsta[]) throws Exception
{
FastScanner infile = new FastScanner();
int T = infile.nextInt();
StringBuilder sb = new StringBuilder();
while(T-->0)
{
int N = infile.nextInt();
int[] parents = new int[N+1];
for(int i=2; i <= N; i++)
parents[i] = infile.nextInt();
left = new int[N+1];
right = new int[N+1];
for(int i=1; i <= N; i++)
{
left[i] = infile.nextInt();
right[i] = infile.nextInt();
}
dp = new int[N+1];
edges = new int[N+1][];
int[] freq = new int[N+1];
for(int i=2; i <= N; i++)
freq[parents[i]]++;
for(int i=1; i <= N; i++)
edges[i] = new int[freq[i]];
for(int i=2; i <= N; i++)
edges[parents[i]][--freq[parents[i]]] = i;
dfs(1);
sb.append(dp[1]+"\n");
}
System.out.print(sb);
}
static int[] left;
static int[] right;
static int[] dp;
public static int dfs(int curr)
{
//returns what the largest possible value of curr could be
dp[curr] = 0;
long sumChild = 0L;
for(int next: edges[curr])
{
int child = dfs(next);
dp[curr] += dp[next];
sumChild += child;
}
if(sumChild < left[curr])
dp[curr]++;
if(sumChild <= right[curr] && sumChild >= left[curr])
return (int)sumChild;
return right[curr];
}
}
/*
if arr[v] >= arr[p_v], then we can incude arr[v] in any operation that involves arr[p_v]
otherwise they must be treated separately
just count this?
*/
class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
40c43fe4a19150ca5b2d3b25b2e8092f
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Thread(null, new Main(), "", 256 * (1L << 20)).start();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
long[] readLongArray(int n) throws IOException{
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = readLong();
}
return array;
}
int[] readIntArray(int n) throws IOException{
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = readInt();
}
return array;
}
// if using Long array with Long search swap the input parameters to longs
int bsForMinNumberGreaterEqual(int[] n, int search) {
int lowB = 0;
int highB = n.length - 1;
int k;
while (lowB <= highB) {
k = (lowB + highB) / 2;
if (k > 0 && n[k] >= search && n[k - 1] < search) {
return k;
} else if (k == 0 && n[k] >= search) {
return k;
} else if (k > 0 && n[k - 1] >= search) {
highB = k - 1;
} else if (n[k] < search) {
lowB = k + 1;
}
}
return -1;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi = random.nextInt(n);
long temp = a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
ArrayList<ArrayList<Integer>> adj;
ArrayList<ArrayList<Integer>> ranges;
int moves;
long w(int v) {
if (adj.get(v).isEmpty()) {
return ranges.get(v).get(1);
}
long sumOfLimits = 0;
for (int i = 0; i < adj.get(v).size(); i++) {
sumOfLimits += w(adj.get(v).get(i));
}
if (ranges.get(v).get(0) > sumOfLimits) {
moves++;
return ranges.get(v).get(1);
}
if (ranges.get(v).get(1) >= sumOfLimits) {
return sumOfLimits;
} else {
return ranges.get(v).get(1);
}
}
void solveTest() throws IOException {
int n = readInt();
adj = new ArrayList<>();
ranges = new ArrayList<>();
moves = 0;
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
adj.get(readInt() - 1).add(i + 1);
}
for (int i = 0; i < n; i++) {
ranges.add(new ArrayList<>());
ranges.get(i).add(readInt());
ranges.get(i).add(readInt());
}
for (int i = 0; i < n; i++) {
if (adj.get(i).isEmpty()) {
moves++;
}
}
long x = w(0);
out.println(moves);
}
void solve() throws IOException {
int testCases = readInt();
for (int tests = 0; tests < testCases; tests++) {
solveTest();
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
6562c9b4578664515527ae4baf63dd36
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
//import org.graalvm.compiler.core.common.Fields.ObjectTransformer;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
// static int g[][];
static ArrayList<Integer> g[];
static long mod=(long)1e9+7,INF=Long.MAX_VALUE;
static boolean set[];
static int max=0;
static int lca[][];
static int par[],col[],D[];
static long fact[];
static int size[],dp[][],countW[],countB[],N;
static long sum[],f[];
static long t[],max_depth[],seg[];
static boolean sep[],isWhite[];
static boolean marked[],visited[],recStack[];
static int segR[],segC[];
static HashMap<Long,Integer> mp[];
public static void main(String args[])throws IOException
{
/*
* star,rope,TPST
* BS,LST,MS,MQ
*/
int T=i();
outer:while(T-->0)
{
int N=i();
g=new ArrayList[N+1];
for(int i=0; i<=N; i++)g[i]=new ArrayList<>();
for(int i=2; i<=N; i++)
{
int a=i();
g[a].add(i);
g[i].add(a);
}
long L[]=new long[N+1],R[]=new long[N+1];
sum=new long[N+1];
for(int i=0; i<N; i++)
{
L[i+1]=l();
R[i+1]=l();
}
out.println(dff(1,-1,L,R));
}
out.println(ans);
out.close();
}
static int dff(int n,int p,long L[],long R[])
{
long s=0;
int cnt=0;
for(int c:g[n])
{
if(c!=p)
{
cnt+=dff(c,n,L,R);
s+=sum[c];
}
}
if(s<L[n])
{
cnt++;
sum[n]=R[n];
}
else
{
sum[n]=Math.min(s, R[n]);
}
return cnt;
}
static void calculatePre(long A[][],int N,int M)
{
for(int i=1; i<=N; i++)
{
for(int j=1; j<=M; j++)A[i][j]+=A[i][j-1];
}
for(int j=1; j<=M; j++)
{
for(int i=2; i<=N; i++)A[i][j]+=A[i-1][j];
}
}
static boolean equals(char X[],char Y[])
{
for(int i=0; i<X.length; i++)if(X[i]!=Y[i])return false;
return true;
}
static long nCr(long n,long r)
{
long s=0;
long c=n-r;
n=fact[(int)n];
r=fact[(int)r];
c=fact[(int)c];
r=pow(r,mod-2)%mod;
c=pow(c,mod-2)%mod;
s=(r*c)%mod;
s=(s*n)%mod;
return s%mod;
}
static boolean isValid(int x,int y,int N,int M)
{
if(x>=N || y>=M)return false;
if(x<0 || y<0)return false;
return true;
}
static int f2(int n,int p)
{
ArrayList<Integer> X=new ArrayList<>();
for(int c:g[n])
{
if(c!=p)
{
X.add(c);
}
}
// System.out.println("for--> "+n+" "+X);
if(X.size()==0)return 0;
if(X.size()==1)return size[n]-1;
int a=X.get(0),b=X.get(1);
// System.out.println("n--> "+n+" "+(size[a]+f2(b,n))+" "+(size[b]+f2(a,n)));
return Math.max(size[a]+f2(b,n), size[b]+f2(a,n));
// return 0;
}
static void f(int n,int p)
{
for(int c:g[n])
{
if(c!=p)
{
f(c,n);
size[n]+=size[c]+1;
}
}
// size[n]++;
}
static boolean isPower(long a,long b)
{
while(a%b==0)
{
}
return a==1;
}
static String rotate(String X,int K)
{
StringBuilder sb=new StringBuilder();
int N=X.length();
int k=K%N;
for(int i=N-k; i<N;i++)
{
sb.append(X.charAt(i));
}
for(int i=0; i<N-k; i++)
{
sb.append(X.charAt(i));
}
return sb.toString();
}
static int rounds(String X,String Y)
{
int n=Y.length();
for(int i=1; i<Y.length(); i++)
{
if(X.charAt(0)==Y.charAt(0) && X.substring(i,i+n).equals(Y))return i;
}
return Y.length();
}
static int index(ArrayList<Long> X,long x)
{
int l=-1,r=X.size();
while(r-l>1)
{
int m=(l+r)/2;
if(X.get(m)<=x)l=m;
else r=m;
}
return l+1;
}
static void swap(int i,int j,long A[][])
{
for(int row=0; row<A.length; row++)
{
long t=A[row][i];
A[row][i]=A[row][j];
A[row][j]=t;
}
}
static boolean isSorted(long A[])
{
for(int i=1; i<A.length; i++)if(A[i]<A[i-1])return false;
return true;
}
static void dfs(int node, int dp[],
boolean visited[],long A[],long a)
{
// Mark as visited
visited[node] = true;
// Traverse for all its children
for (int c:g[node])
{
// If not visited
if (A[c-1]<=a && !visited[c])
dfs(c, dp, visited,A,a);
// Store the max of the paths
dp[node] = Math.max(dp[node], 1 + dp[c]);
}
}
static int findLongestPath( int n,long A[],long a)
{
// Dp array
int[] dp = new int[n+1];
// Visited array to know if the node
// has been visited previously or not
boolean[] visited = new boolean[n + 1];
// Call DFS for every unvisited vertex
for (int i = 1; i <= n; i++)
{
if (A[i-1]<=a && !visited[i])
dfs(i, dp, visited,A,a);
}
int ans = 0;
// Traverse and find the maximum of all dp[i]
for (int i = 1; i <= n; i++)
{
ans = Math.max(ans, dp[i]);
}
return ans;
}
static boolean isCyclicUtil(int n, boolean[] visited,
boolean[] recStack,long A[],long a)
{
if (recStack[n])
return true;
if (visited[n])
return false;
visited[n] = true;
recStack[n] = true;
for (int c: g[n])
{
if(A[c-1]<=a )
{
if (isCyclicUtil(c, visited, recStack,A,a))
return true;
}
}
recStack[n] = false;
return false;
}
static void push(int v) {
if (marked[v]) {
t[v*2] = t[v*2+1] = t[v];
marked[v*2] = marked[v*2+1] = true;
marked[v] = false;
}
}
static void update1(int v, int tl, int tr, int l, int r, int new_val) {
if (l > r)
return;
if (l == tl && tr == r) {
t[v] = new_val;
marked[v] = true;
} else {
push(v);
int tm = (tl + tr) / 2;
update1(v*2, tl, tm, l, Math.min(r, tm), new_val);
update1(v*2+1, tm+1, tr, Math.max(l, tm+1), r, new_val);
}
}
static long get1(int v, int tl, int tr, int pos) {
if (tl == tr) {
return t[v];
}
push(v);
int tm = (tl + tr) / 2;
if (pos <= tm)
return get1(v*2, tl, tm, pos);
else
return get1(v*2+1, tm+1, tr, pos);
}
static int cost=0;
static void fmin(int i,int j,ArrayList<Integer> A,int cZ,int cO)
{
if(j-i>1)
{
int a=A.get(i),b=A.get(j);
cO+=Math.min(a, b);
if(a<b)
{
}
else if(b>a)
{
}
else
{
}
}
}
static void fs(int n,int p)
{
if(isWhite[n])countW[n]=1;
else countB[n]=1;
for(int c:g[n])
{
if(c!=p)
{
fs(c,n);
countB[n]+=countB[c];
countW[n]+=countW[c];
}
}
}
static int f(char X[],char Y[])
{
int s=0;
for(int i=0; i<Y.length; i++)
{
s+=Math.abs(X[i]-Y[i]);
}
return s;
}
public static long mergeSort(int A[],int l,int r)
{
long a=0;
if(l<r)
{
int m=(l+r)/2;
a+=mergeSort(A,l,m);
a+=mergeSort(A,m+1,r);
a+=merge(A,l,m,r);
}
return a;
}
public static long merge(int A[],int l,int m,int r)
{
long a=0;
int i=l,j=m+1,index=0;
long c=0;
int B[]=new int[r-l+1];
while(i<=m && j<=r)
{
if(A[i]<=A[j])
{
c++;
B[index++]=A[i++];
}
else
{
long s=(m-l)+1;
a+=(s-c);
B[index++]=A[j++];
}
}
while(i<=m)B[index++]=A[i++];
while(j<=r)B[index++]=A[j++];
index=0;
for(; l<=r; l++)A[l]=B[index++];
return a;
}
static int f(int A[])
{
int s=0;
for(int i=1; i<4; i++)
{
s+=Math.abs(A[i]-A[i-1]);
}
return s;
}
static boolean f(int A[],int B[],int N)
{
for(int i=0; i<N; i++)
{
if(Math.abs(A[i]-B[i])>1)return false;
}
return true;
}
static int [] prefix(char s[],int N) {
// int n = (int)s.length();
// vector<int> pi(n);
N=s.length;
int pi[]=new int[N];
for (int i = 1; i < N; i++) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static int count(long N)
{
int cnt=0;
long p=1L;
while(p<=N)
{
if((p&N)!=0)cnt++;
p<<=1;
}
return cnt;
}
static long kadane(long A[])
{
long lsum=A[0],gsum=0;
gsum=Math.max(gsum, lsum);
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
public static void reverse(int i,int j,int A[])
{
while(i<j)
{
int t=A[i];
A[i]=A[j];
A[j]=t;
i++;
j--;
}
}
public static int ask(int a,int b,int c)
{
System.out.println("? "+a+" "+b+" "+c);
return i();
}
static int[] reverse(int A[],int N)
{
int B[]=new int[N];
for(int i=N-1; i>=0; i--)
{
B[N-i-1]=A[i];
}
return B;
}
static boolean isPalin(char X[])
{
int i=0,j=X.length-1;
while(i<=j)
{
if(X[i]!=X[j])return false;
i++;
j--;
}
return true;
}
static int distance(int a,int b)
{
int d=D[a]+D[b];
int l=LCA(a,b);
l=2*D[l];
return d-l;
}
static int LCA(int a,int b)
{
if(D[a]<D[b])
{
int t=a;
a=b;
b=t;
}
int d=D[a]-D[b];
int p=1;
for(int i=0; i>=0 && p<=d; i++)
{
if((p&d)!=0)
{
a=lca[a][i];
}
p<<=1;
}
if(a==b)return a;
for(int i=max-1; i>=0; i--)
{
if(lca[a][i]!=-1 && lca[a][i]!=lca[b][i])
{
a=lca[a][i];
b=lca[b][i];
}
}
return lca[a][0];
}
static void dfs(int n,int p)
{
lca[n][0]=p;
if(p!=-1)D[n]=D[p]+1;
for(int c:g[n])
{
if(c!=p)
{
dfs(c,n);
}
}
}
static int[] prefix_function(char X[])//returns pi(i) array
{
int N=X.length;
int pre[]=new int[N];
for(int i=1; i<N; i++)
{
int j=pre[i-1];
while(j>0 && X[i]!=X[j])
j=pre[j-1];
if(X[i]==X[j])j++;
pre[i]=j;
}
return pre;
}
static TreeNode start;
public static void f(TreeNode root,TreeNode p,int r)
{
if(root==null)return;
if(p!=null)
{
root.par=p;
}
if(root.val==r)start=root;
f(root.left,root,r);
f(root.right,root,r);
}
static int right(int A[],int Limit,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<Limit)l=m;
else r=m;
}
return l;
}
static int left(int A[],int a,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<a)l=m;
else r=m;
}
return l;
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// long a=0;
// if(A[tl]>0)
// {
// a=A[tl];
//
// }
// seg[v]=new node(a,a,a,A[tl],A[tl]);
// return;
// }
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=combine(seg[v*2],seg[v*2+1]);
// }
// static node combine(node a,node b)
// {
// node temp=new node(0,0,0,0);
// temp.pref=max(a.pref,a.sum+b.pref,a.sum+b.sum);
// temp.suff=max(b.suff,b.sum+a.suff,b.sum+a.sum);
// temp.max=max(a.max,b.max,a.suff+b.pref);
// temp.sum=a.sum+b.sum;
// temp.min=Math.max(a.min, b.min);
// return temp;
// }
// static long max(long a,long b,long c)
// {
// return Math.max(a,Math.max(b, c));
// }
// // static void update(int v,int tl,int tr,int index)
// // {
// // if(index==tl && index==tr)
// // {
// // segR[v]+=1;
// // segR[v]%=2;
// // }
// // else
// // {
// // int tm=(tl+tr)/2;
// // if(index<=tm)update(v*2,tl,tm,index);
// // else update(v*2+1,tm+1,tr,index);
// // segR[v]=segR[v*2]+segR[v*2+1];
// // }
// // }
// static long ask(int v,int tl,int tr,int l,int r)
// {
//
// if(l>r)return 0;
// if(tl==l && r==tr)
// {
// return seg[v].max;
// }
// int tm=(tl+tr)/2;
//
// return Math.max(ask(v*2,tl,tm,l,Math.min(tm, r)),ask(v*2+1,tm+1,tr,Math.max(tm+1, l),r));
// }
static void build(int v,int tl,int tr,long A[])
{
if(tl==tr)
{
seg[v]=A[tl];
return;
}
int tm=(tl+tr)/2;
build(v*2,tl,tm,A);
build(v*2+1,tm+1,tr,A);
seg[v]=Math.max(seg[v*2],seg[v*2+1]);
}
static void update(int v,int tl,int tr,int index,int a)
{
if(index==tl && tl==tr)
{
seg[v]++;
seg[v]%=2;
}
else
{
int tm=(tl+tr)/2;
if(index<=tm)update(2*v,tl,tm,index,a);
else update(2*v+1,tm+1,tr,index,a);
seg[v]=seg[v*2]+seg[v*2+1];
}
}
static long ask(int v,int tl,int tr,int l,int r)
{
if(l>r)return 0;
if(tl==l && tr==r)return seg[v];
int tm=(tl+tr)/2;
return Math.max(ask(v*2,tl,tm,l,Math.min(tm,r)),ask(v*2+1,tm+1,tr,Math.max(l, tm+1),r));
}
static void updateC(int v,int tl,int tr,int index)
{
if(index==tl && index==tr)
{
segC[v]+=1;
segC[v]%=2;
}
else
{
int tm=(tl+tr)/2;
if(index<=tm)updateC(v*2,tl,tm,index);
else updateC(v*2+1,tm+1,tr,index);
segC[v]=segC[v*2]+segC[v*2+1];
}
}
static int askC(int v,int tl,int tr,int l,int r)
{
if(l>r)return 0;
if(tl==l && r==tr)
{
return segC[v];
}
int tm=(tl+tr)/2;
return askC(v*2,tl,tm,l,Math.min(tm, r))+askC(v*2+1,tm+1,tr,Math.max(tm+1, l),r);
}
static boolean f(long A[],long m,int N)
{
long B[]=new long[N];
for(int i=0; i<N; i++)
{
B[i]=A[i];
}
for(int i=N-1; i>=0; i--)
{
if(B[i]<m)return false;
if(i>=2)
{
long extra=Math.min(B[i]-m, A[i]);
long x=extra/3L;
B[i-2]+=2L*x;
B[i-1]+=x;
}
}
return true;
}
static int f(int l,int r,long A[],long x)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]>=x)l=m;
else r=m;
}
return r;
}
static boolean f(long m,long H,long A[],int N)
{
long s=m;
for(int i=0; i<N-1;i++)
{
s+=Math.min(m, A[i+1]-A[i]);
}
return s>=H;
}
static long ask(long l,long r)
{
System.out.println("? "+l+" "+r);
return l();
}
static long f(long N,long M)
{
long s=0;
if(N%3==0)
{
N/=3;
s=N*M;
}
else
{
long b=N%3;
N/=3;
N++;
s=N*M;
N--;
long a=N*M;
if(M%3==0)
{
M/=3;
a+=(b*M);
}
else
{
M/=3;
M++;
a+=(b*M);
}
s=Math.min(s, a);
}
return s;
}
static int ask(StringBuilder sb,int a)
{
System.out.println(sb+""+a);
return i();
}
static void swap(char X[],int i,int j)
{
char x=X[i];
X[i]=X[j];
X[j]=x;
}
static int min(int a,int b,int c)
{
return Math.min(Math.min(a, b), c);
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static int len=0,number=0;
static void f(char X[],int i,int num,int l)
{
if(i==X.length)
{
if(num==0)return;
//update our num
if(isPrime(num))return;
if(l<len)
{
len=l;
number=num;
}
return;
}
int a=X[i]-'0';
f(X,i+1,num*10+a,l+1);
f(X,i+1,num,l);
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
static int f(long K)
{
long l=0,r=K;
while(r-l>1)
{
long m=(l+r)/2;
if(m*m<K)l=m;
else r=m;
}
return (int)l;
}
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int[] f(int N)
{
char X[]=in.next().toCharArray();
int A[]=new int[N];
for(int i=0; i<N; i++)A[i]=X[i]-'a';
return A;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
if(par[a]>par[b]) //this means size of a is less than that of b
{
int t=b;
b=a;
a=t;
}
par[a]+=par[b];
par[b]=a;
}
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sortR(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
int N=a.length;
for (int i=0; i<a.length; i++) a[i]=l.get(N-i-1);
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
// static void setGraph(int N,int nodes)
// {
//// size=new int[N+1];
// par=new int[N+1];
// col=new int[N+1];
//// g=new int[N+1][];
// D=new int[N+1];
// int deg[]=new int[N+1];
// int A[][]=new int[nodes][2];
// for(int i=0; i<nodes; i++)
// {
// int a=i(),b=i();
// A[i][0]=a;
// A[i][1]=b;
// deg[a]++;
// deg[b]++;
// }
// for(int i=0; i<=N; i++)
// {
// g[i]=new int[deg[i]];
// deg[i]=0;
// }
// for(int a[]:A)
// {
// int x=a[0],y=a[1];
// g[x][deg[x]++]=y;
// g[y][deg[y]++]=x;
// }
// }
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class node
{
long pref,suff,max,sum,min;
node(long a,long b,long c,long d)
{
pref=a;
suff=b;
max=c;
sum=d;
min=Long.MIN_VALUE;
}
node(long a,long b,long c,long d,long e)
{
pref=a;
suff=b;
max=c;
sum=d;
min=e;
}
}
class project implements Comparable<project>
{
int score,index;
project(int s,int i)
{
// roles=r;
index=i;
score=s;
// skill=new String[r];
// lvl=new int[r];
}
public int compareTo(project x)
{
return x.score-this.score;
}
}
class post implements Comparable<post>
{
long x,y,d,t;
post(long a,long b,long c)
{
x=a;
y=b;
d=c;
}
public int compareTo(post X)
{
if(X.t==this.t)
{
return 0;
}
else
{
long xt=this.t-X.t;
if(xt>0)return 1;
return -1;
}
}
}
class TreeNode
{
int val;
TreeNode left, right,par;
TreeNode() {}
TreeNode(int item)
{
val = item;
left =null;
right = null;
par=null;
}
}
class pair implements Comparable<pair>
{
int l,r,index;
pair(int a,int b,int i)
{
l=a;
r=b;
index=i;
}
public int compareTo(pair x)
{
if(this.r==x.r)return this.l-x.l;
return this.r-x.r;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
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
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
4c670cee5e0776e7a11ccff77c58011a
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
int t = cin.nextInt();
while (t-->0) {
solve();
}
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int[] p = new int[n+1];
int[] cnum = new int[n+1];
for(int i=2;i<=n;i++) {
p[i] = cin.nextInt();
cnum[p[i]]++;
}
long[][] bound = new long[n+1][2];
for(int i=1;i<=n;i++) {
bound[i][0] = cin.nextLong();
bound[i][1] = cin.nextLong();
}
long[] c = new long[n+1];
int ans =0;
Queue<Integer> queue = new LinkedList<>();
for(int i=1;i<=n;i++) {
if(cnum[i]==0) {
queue.add(i);
}
}
while (!queue.isEmpty()) {
int id = queue.poll();
cnum[p[id]]--;
if(cnum[p[id]]==0) {
queue.add(p[id]);
}
if(c[id]>= bound[id][0]) {
if(c[id]> bound[id][1]) {
c[id] =bound[id][1];
}
c[p[id]] = c[p[id]] + c[id];
continue;
}
ans++;
c[id] =bound[id][1];
c[p[id]] = c[p[id]] + c[id];
}
System.out.println(ans);
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
82ca141c856647c985bee8a1fd7d62b1
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class fake_PlasticTrees {
static int ans;
static ArrayList<ArrayList<Integer>> adj;
static long[] dp;
public static void dfs(int v,int[] l, int[] r) {
long sum = 0;
for(int i=0;adj.get(v).size()>i;i++) {
dfs(adj.get(v).get(i),l,r);
sum+=dp[adj.get(v).get(i)];
}
if(sum<l[v])
{
ans+=1;
dp[v] = r[v];
}
else {
dp[v] = Math.min(sum, r[v]);
}
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
int t = sc.nextInt();
while(t-->0) {
ans=0;
int n = sc.nextInt();
int[] p = new int[n-1];
dp = new long[n];
ans=0;
adj= new ArrayList<ArrayList<Integer>>();
for(int i=0;n-1>i;i++) {
p[i] = sc.nextInt();
adj.add(i, new ArrayList<Integer>());
}
adj.add(n-1, new ArrayList<Integer>());
for(int i=1;n>i;i++)
adj.get(p[i-1]-1).add(i);
int[] l = new int[n];
int[] r = new int[n];
for(int i=0;n>i;i++) {
l[i] = sc.nextInt();
r[i] = sc.nextInt();
}
dfs(0,l,r);
sb.append(ans);
if(t>=1) sb.append("\n");
}
out.println(sb.toString());
out.flush();
out.close();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
041839184b7541f513bbf379ea672426
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
/* || श्री राम समर्थ ||
|| जय जय रघुवीर समर्थ ||
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.*;
import static java.util.Arrays.sort;
/*
Think until you get Good idea And then Code Easily
Try Hard And Pay Attention to details (be positive always possible)
think smart
*/
public class CodeforcesTemp {
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
FastPrinter out = new FastPrinter();
int tt = scan.nextInt();
for (int tc = 1; tc <= tt; tc++) {
int n= scan.nextInt();
int[] arr= scan.nextIntArray(n-1);
List<Integer>[] li=new List[n+1];
for (int i = 0; i <=n; i++) {
li[i]=new ArrayList<>();
}
for (int i = 0; i < n-1; i++) {
li[arr[i]].add(i+2);
}
long[][] range=new long[n+1][2];
for (int i =1; i <=n ; i++) {
range[i][0]=scan.nextLong();
range[i][1]=scan.nextLong();
}
int[] ans=new int[1];
ans[0]=0;
dfs(li,1,ans,range);
out.println(ans[0]);
out.flush();
}
out.close();
}
private static long dfs(List<Integer>[] li, int i, int[] ans, long[][] range) {
if(li[i].size()==0){
ans[0]++;
return range[i][1];
}
long sum=0;
for (int j = 0; j < li[i].size() ; j++) {
sum+=dfs(li,li[i].get(j),ans,range);
}
if(sum<range[i][0]){
ans[0]++;
return range[i][1];
}
return Math.min(sum,range[i][1]);
}
static class Reader {
private final InputStream in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private static final long LONG_MAX_TENTHS = 922337203685477580L;
private static final int LONG_MAX_LAST_DIGIT = 7;
private static final int LONG_MIN_LAST_DIGIT = 8;
public Reader(InputStream in) {
this.in = in;
}
public Reader() {
this(System.in);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
public boolean hasNext() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
int digit = b - '0';
if (n >= LONG_MAX_TENTHS) {
if (n == LONG_MAX_TENTHS) {
if (minus) {
if (digit <= LONG_MIN_LAST_DIGIT) {
n = -n * 10 - digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("not number"));
}
}
} else {
if (digit <= LONG_MAX_LAST_DIGIT) {
n = n * 10 + digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("not number"));
}
}
}
}
throw new ArithmeticException(
String.format(" overflows long."));
}
n = n * 10 + digit;
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long[] nextLongArray(int length) {
long[] array = new long[length];
for (int i = 0; i < length; i++)
array[i] = this.nextLong();
return array;
}
public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) {
long[] array = new long[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsLong(this.nextLong());
return array;
}
public int[] nextIntArray(int length) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = this.nextInt();
return array;
}
public int[][] nextIntArrayMulti(int length, int width) {
int[][] arrays = new int[width][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++)
arrays[j][i] = this.nextInt();
}
return arrays;
}
public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsInt(this.nextInt());
return array;
}
public double[] nextDoubleArray(int length) {
double[] array = new double[length];
for (int i = 0; i < length; i++)
array[i] = this.nextDouble();
return array;
}
public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) {
double[] array = new double[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsDouble(this.nextDouble());
return array;
}
public long[][] nextLongMatrix(int height, int width) {
long[][] mat = new long[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextLong();
}
return mat;
}
public int[][] nextIntMatrix(int height, int width) {
int[][] mat = new int[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextInt();
}
return mat;
}
public double[][] nextDoubleMatrix(int height, int width) {
double[][] mat = new double[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextDouble();
}
return mat;
}
public char[][] nextCharMatrix(int height, int width) {
char[][] mat = new char[height][width];
for (int h = 0; h < height; h++) {
String s = this.next();
for (int w = 0; w < width; w++) {
mat[h][w] = s.charAt(w);
}
}
return mat;
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(PrintStream stream) {
super(stream);
}
public FastPrinter() {
super(System.out);
}
private static String dtos(double x, int n) {
StringBuilder sb = new StringBuilder();
if (x < 0) {
sb.append('-');
x = -x;
}
x += Math.pow(10, -n) / 2;
sb.append((long) x);
sb.append(".");
x -= (long) x;
for (int i = 0; i < n; i++) {
x *= 10;
sb.append((int) x);
x -= (int) x;
}
return sb.toString();
}
@Override
public void print(float f) {
super.print(dtos(f, 20));
}
@Override
public void println(float f) {
super.println(dtos(f, 20));
}
@Override
public void print(double d) {
super.print(dtos(d, 20));
}
@Override
public void println(double d) {
super.println(dtos(d, 20));
}
public void printArray(int[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(int[] array) {
this.printArray(array, " ");
}
public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsInt(array[i]));
super.print(separator);
}
super.println(map.applyAsInt(array[n - 1]));
}
public void printArray(int[] array, java.util.function.IntUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printArray(long[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(long[] array) {
this.printArray(array, " ");
}
public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsLong(array[i]));
super.print(separator);
}
super.println(map.applyAsLong(array[n - 1]));
}
public void printArray(long[] array, java.util.function.LongUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
this.printArray(arr[i]);
}
}
}
static Random __r = new Random();
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
05d61f6954ec7bde539b8dfbb74c3cc6
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static int I(String s) { return Integer.parseInt(s); }
static int N = (int)2e5 + 10;
static String[] ins;
static int n;
static int[] l;
static int[] r;
static int[] p;
static long[] dp;
static List[] graph;
static int res;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static void dfs(int u) {
long sum = 0;
for(int i = 0; i < graph[u].size(); i++) {
int v = (int)graph[u].get(i);
dfs(v);
sum += dp[v];
}
// pw.println(u + " -> " + sum);
int tmp = l[u];
if(sum >= r[u]) {
dp[u] = r[u];
} else if(sum >= l[u]) {
dp[u] = sum;
} else {
dp[u] = r[u];
res++;
// pw.println("! " + u);
}
}
public static void main(String[] args) throws IOException {
ins = br.readLine().split(" ");
int T = I(ins[0]);
while(T-- > 0) {
ins = br.readLine().split(" ");
n = I(ins[0]);
p = new int[n + 1];
dp = new long[n + 1];
l = new int[n + 1];
r = new int[n + 1];
graph = new List[n + 1];
res = 0;
for(int i = 1; i <= n; i++) graph[i] = new ArrayList<Integer>();
ins = br.readLine().split(" ");
for(int i = 2; i <= n; i++) {
p[i] = I(ins[i - 2]);
graph[p[i]].add(i);
}
for(int i = 1; i <= n; i++) {
ins = br.readLine().split(" ");
l[i] = I(ins[0]);
r[i] = I(ins[1]);
}
dfs(1);
// for(int i = 1; i <= n; i++) pw.print(dp[i] + " ");
// pw.println();
pw.println(res);
}
pw.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
778d0529e2cfa6a726be4d474a5dd740
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
for (int i = 0; i < testNumber; i++) {
int n = in.nextInt();
int[] a = new int[n];
a[0] = -1;
for (int j = 1; j < a.length; j++) {
a[j] = in.nextInt() - 1;
}
long[][] arr = new long[n][2];
for (int j = 0; j < arr.length; j++) {
arr[j] = new long[]{in.nextLong(), in.nextLong()};
}
out.println(new Solution().solve(a, arr));
}
}
}
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());
}
}
}
class Solution {
int cnt = 0;
int n;
Node[] nodes;
public int solve(int[] a, long[][] arr) {
n = a.length;
nodes = new Node[n];
for (int i = 0; i < n; i++) {
nodes[i] = new Node(arr[i][0], arr[i][1]);
}
for (int i = 1; i < a.length; i++) {
nodes[a[i]].child.add(i);
}
dfs(0);
return cnt;
}
private void dfs(int v) {
for (Integer w : nodes[v].child) {
dfs(w);
nodes[v].val += nodes[w].val;
}
if (nodes[v].val < nodes[v].l) {
cnt++;
nodes[v].val = nodes[v].r;
}
if (nodes[v].val > nodes[v].r) {
nodes[v].val = nodes[v].r;
}
}
}
class Node {
long val = 0;
long l;
long r;
Set<Integer> child = new HashSet<>();
public Node(long l, long r) {
this.l = l;
this.r = r;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
a2c47239b0230efde84cbe434e27fd22
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static int dx[]={0,0,-1,1},dy[]={-1,1,0,0};
static final double pi=3.1415926536;
static long mod=1000000007;
// static long mod=998244353;
static int MAX=Integer.MAX_VALUE;
static int MIN=Integer.MIN_VALUE;
static long MAXL=Long.MAX_VALUE;
static long MINL=Long.MIN_VALUE;
static ArrayList<Integer> graph[];
static long fact[];
static long seg[];
static int dp[][];
// static long dp[][];
public static void main (String[] args) throws java.lang.Exception
{
// code goes here
int t=I();
outer:while(t-->0)
{
int n=I();
graph=new ArrayList[n+1];
for(int i=0;i<n+1;i++){
graph[i]=new ArrayList<>();
}
for(int i=0;i<n-1;i++){
int u=i+2;
int v=I();
graph[u].add(v);
graph[v].add(u);
}
pair p[]=new pair[n+1];
for(int i=1;i<=n;i++){
p[i]=new pair(L(),L());
}
ans=0;
temp=new long[n+1];
dfs(1,0,p);
out.println(ans);
}
out.close();
}
static int ans=0;
static long temp[];
public static void dfs(int s,int par,pair p[])
{
boolean leaf=true;
for(int i:graph[s]){
if(i!=par){
leaf=false;
dfs(i,s,p);
}
}
if(leaf){
ans++;
temp[s]=p[s].b;
return;
}
long sum=0;
for(int i:graph[s]){
if(i!=par){
sum+=temp[i];
}
}
if(sum>=p[s].a){
temp[s]=min(sum,p[s].b);
}else{
ans++;
temp[s]=p[s].b;
}
}
public static class pair
{
long a;
long b;
public pair(long aa,long bb)
{
a=aa;
b=bb;
}
}
public static class myComp implements Comparator<pair>
{
//sort in ascending order.
public int compare(pair p1,pair p2)
{
if(p1.a==p2.a)
return 0;
else if(p1.a<p2.a)
return -1;
else
return 1;
}
// sort in descending order.
// public int compare(pair p1,pair p2)
// {
// if(p1.b==p2.b)
// return 0;
// else if(p1.b<p2.b)
// return 1;
// else
// return -1;
// }
}
public static void setGraph(int n,int m)throws IOException
{
graph=new ArrayList[n+1];
for(int i=0;i<=n;i++){
graph[i]=new ArrayList<>();
}
for(int i=0;i<m;i++){
int u=I(),v=I();
graph[u].add(v);
graph[v].add(u);
}
}
//LOWER_BOUND and UPPER_BOUND functions
//It returns answer according to zero based indexing.
public static int lower_bound(pair[] arr,int X,int start, int end) //start=0,end=n-1
{
if(start>end)return -1;
// if(arr.get(end)<X)return end;
if(arr[end].a<X)return end;
// if(arr.get(start)>X)return -1;
if(arr[start].a>X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
if(arr[mid].a==X){
// if(arr.get(mid)==X){ //Returns last index of lower bound value.
if(mid<end && arr[mid+1].a==X){
// if(mid<end && arr.get(mid+1)==X){
left=mid+1;
}else{
return mid;
}
}
// if(arr.get(mid)==X){ //Returns first index of lower bound value.
// if(arr[mid]==X){
// // if(mid>start && arr.get(mid-1)==X){
// if(mid>start && arr[mid-1]==X){
// right=mid-1;
// }else{
// return mid;
// }
// }
else if(arr[mid].a>X){
// else if(arr.get(mid)>X){
if(mid>start && arr[mid-1].a<X){
// if(mid>start && arr.get(mid-1)<X){
return mid-1;
}else{
right=mid-1;
}
}else{
if(mid<end && arr[mid+1].a>X){
// if(mid<end && arr.get(mid+1)>X){
return mid;
}else{
left=mid+1;
}
}
}
return left;
}
//It returns answer according to zero based indexing.
public static int upper_bound(ArrayList<Integer> arr,int X,int start,int end) //start=0,end=n-1
{
if(arr.get(0)>=X)return start;
if(arr.get(arr.size()-1)<X)return -1;
int left=start,right=end;
while(left<right){
int mid=(left+right)/2;
if(arr.get(mid)==X){ //returns first index of upper bound value.
if(mid>start && arr.get(mid-1)==X){
right=mid-1;
}else{
return mid;
}
}
// if(arr[mid]==X){ //returns last index of upper bound value.
// if(mid<end && arr[mid+1]==X){
// left=mid+1;
// }else{
// return mid;
// }
// }
else if(arr.get(mid)>X){
if(mid>start && arr.get(mid-1)<X){
return mid;
}else{
right=mid-1;
}
}else{
if(mid<end && arr.get(mid+1)>X){
return mid+1;
}else{
left=mid+1;
}
}
}
return left;
}
//END
//Segment Tree Code
public static void buildTree(long a[],int si,int ss,int se)
{
if(ss==se){
seg[si]=a[ss];
return;
}
int mid=(ss+se)/2;
buildTree(a,2*si+1,ss,mid);
buildTree(a,2*si+2,mid+1,se);
seg[si]=max(seg[2*si+1],seg[2*si+2]);
}
// public static void update(int si,int ss,int se,int pos,int val)
// {
// if(ss==se){
// // seg[si]=val;
// return;
// }
// int mid=(ss+se)/2;
// if(pos<=mid){
// update(2*si+1,ss,mid,pos,val);
// }else{
// update(2*si+2,mid+1,se,pos,val);
// }
// // seg[si]=min(seg[2*si+1],seg[2*si+2]);
// if(seg[2*si+1].a < seg[2*si+2].a){
// seg[si].a=seg[2*si+1].a;
// seg[si].b=seg[2*si+1].b;
// }else{
// seg[si].a=seg[2*si+2].a;
// seg[si].b=seg[2*si+2].b;
// }
// }
public static long query1(int si,int ss,int se,int qs,int qe)
{
if(qs>se || qe<ss)return 0;
if(ss>=qs && se<=qe)return seg[si];
int mid=(ss+se)/2;
long p1=query1(2*si+1,ss,mid,qs,qe);
long p2=query1(2*si+2,mid+1,se,qs,qe);
return max(p1,p2);
}
public static void merge(ArrayList<Integer> f,ArrayList<Integer> a,ArrayList<Integer> b)
{
int i=0,j=0;
while(i<a.size() && j<b.size()){
if(a.get(i)<=b.get(j)){
f.add(a.get(i));
i++;
}else{
f.add(b.get(j));
j++;
}
}
while(i<a.size()){
f.add(a.get(i));
i++;
}
while(j<b.size()){
f.add(b.get(j));
j++;
}
}
//Segment Tree Code end
//Prefix Function of KMP Algorithm
public static int[] KMP(char c[],int n)
{
int pi[]=new int[n];
for(int i=1;i<n;i++){
int j=pi[i-1];
while(j>0 && c[i]!=c[j]){
j=pi[j-1];
}
if(c[i]==c[j])j++;
pi[i]=j;
}
return pi;
}
public static long kadane(long a[],int n) //largest sum subarray
{
long max_sum=Long.MIN_VALUE,max_end=0;
for(int i=0;i<n;i++){
max_end+=a[i];
if(max_sum<max_end){max_sum=max_end;}
if(max_end<0){max_end=0;}
}
return max_sum;
}
public static long nPr(int n,int r)
{
long ans=divide(fact(n),fact(n-r),mod);
return ans;
}
public static long nCr(int n,int r)
{
long ans=divide(fact[n],mul(fact[n-r],fact[r]),mod);
return ans;
}
public static boolean isSorted(int a[])
{
int n=a.length;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1])return false;
}
return true;
}
public static boolean isSorted(long a[])
{
int n=a.length;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1])return false;
}
return true;
}
public static int computeXOR(int n) //compute XOR of all numbers between 1 to n.
{
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
public static int np2(int x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
public static int hp2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
public static long hp2(long x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
public static ArrayList<Integer> primeSieve(int n)
{
ArrayList<Integer> arr=new ArrayList<>();
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
arr.add(i);
}
return arr;
}
// Fenwick / BinaryIndexed Tree USE IT - FenwickTree ft1=new FenwickTree(n);
public static class FenwickTree
{
int farr[];
int n;
public FenwickTree(int c)
{
n=c+1;
farr=new int[n];
}
// public void update_range(int l,int r,long p)
// {
// update(l,p);
// update(r+1,(-1)*p);
// }
public void update(int x,int p)
{
for(;x<n;x+=x&(-x))
{
farr[x]+=p;
}
}
public int get(int x)
{
int ans=0;
for(;x>0;x-=x&(-x))
{
ans=ans+farr[x];
}
return ans;
}
}
//Disjoint Set Union
public static class DSU
{
int par[],rank[];
public DSU(int c)
{
par=new int[c+1];
rank=new int[c+1];
for(int i=0;i<=c;i++)
{
par[i]=i;
rank[i]=0;
}
}
public int find(int a)
{
if(a==par[a])
return a;
return par[a]=find(par[a]);
}
public void union(int a,int b)
{
int a_rep=find(a),b_rep=find(b);
if(a_rep==b_rep)
return;
if(rank[a_rep]<rank[b_rep])
par[a_rep]=b_rep;
else if(rank[a_rep]>rank[b_rep])
par[b_rep]=a_rep;
else
{
par[b_rep]=a_rep;
rank[a_rep]++;
}
}
}
public static HashMap<Integer,Integer> primeFact(int a)
{
// HashSet<Long> arr=new HashSet<>();
HashMap<Integer,Integer> hm=new HashMap<>();
int p=0;
while(a%2==0){
// arr.add(2L);
p++;
a=a/2;
}
hm.put(2,hm.getOrDefault(2,0)+p);
for(int i=3;i*i<=a;i+=2){
p=0;
while(a%i==0){
// arr.add(i);
p++;
a=a/i;
}
hm.put(i,hm.getOrDefault(i,0)+p);
}
if(a>2){
// arr.add(a);
hm.put(a,hm.getOrDefault(a,0)+1);
}
// return arr;
return hm;
}
public static boolean isVowel(char c)
{
if(c=='a' || c=='e' || c=='i' || c=='u' || c=='o')return true;
return false;
}
public static boolean isInteger(double N)
{
int X = (int)N;
double temp2 = N - X;
if (temp2 > 0)
{
return false;
}
return true;
}
public static boolean isPalindrome(String s)
{
int n=s.length();
for(int i=0;i<=n/2;i++){
if(s.charAt(i)!=s.charAt(n-i-1)){
return false;
}
}
return true;
}
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 long fact(long n)
{
long fact=1;
for(long i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
public static long fact(int n)
{
long fact=1;
for(int i=2;i<=n;i++){
fact=((fact%mod)*(i%mod))%mod;
}
return fact;
}
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;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean isPrime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void printArray(long a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(int a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(char a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]);
}
out.println();
}
public static void printArray(String a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(boolean a[])
{
for(int i=0;i<a.length;i++){
out.print(a[i]+" ");
}
out.println();
}
public static void printArray(pair a[])
{
for(pair p:a){
out.println(p.a+"->"+p.b);
}
}
public static void printArray(int a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(String a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(boolean a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(long a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(char a[][])
{
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++){
out.print(a[i][j]+" ");
}out.println();
}
}
public static void printArray(ArrayList<?> arr)
{
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}
out.println();
}
public static void printMapI(HashMap<?,?> hm){
for(Map.Entry<?,?> e:hm.entrySet()){
out.println(e.getKey()+"->"+e.getValue());
}out.println();
}
public static void printMap(HashMap<Long,ArrayList<Integer>> hm){
for(Map.Entry<Long,ArrayList<Integer>> e:hm.entrySet()){
out.print(e.getKey()+"->");
ArrayList<Integer> arr=e.getValue();
for(int i=0;i<arr.size();i++){
out.print(arr.get(i)+" ");
}out.println();
}
}
public static void printGraph(ArrayList<Integer> graph[])
{
int n=graph.length;
for(int i=0;i<n;i++){
out.print(i+"->");
for(int j:graph[i]){
out.print(j+" ");
}out.println();
}
}
//Modular Arithmetic
public static long add(long a,long b)
{
a+=b;
if(a>=mod)a-=mod;
return a;
}
public static long sub(long a,long b)
{
a-=b;
if(a<0)a+=mod;
return a;
}
public static long mul(long a,long b)
{
return ((a%mod)*(b%mod))%mod;
}
public static long divide(long a,long b,long m)
{
a=mul(a,modInverse(b,m));
return a;
}
public static long modInverse(long a,long m)
{
int x=0,y=0;
own p=new own(x,y);
long g=gcdExt(a,m,p);
if(g!=1){
out.println("inverse does not exists");
return -1;
}else{
long res=((p.a%m)+m)%m;
return res;
}
}
public static long gcdExt(long a,long b,own p)
{
if(b==0){
p.a=1;
p.b=0;
return a;
}
int x1=0,y1=0;
own p1=new own(x1,y1);
long gcd=gcdExt(b,a%b,p1);
p.b=p1.a - (a/b) * p1.b;
p.a=p1.b;
return gcd;
}
public static long pwr(long m,long n)
{
long res=1;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m);
}
n=n>>1;
m=(m*m);
}
return res;
}
public static long modpwr(long m,long n)
{
long res=1;
m=m%mod;
if(m==0)
return 0;
while(n>0)
{
if((n&1)!=0)
{
res=(res*m)%mod;
}
n=n>>1;
m=(m*m)%mod;
}
return res;
}
public static class own
{
long a;
long b;
public own(long val,long index)
{
a=val;
b=index;
}
}
//Modular Airthmetic
public static void sort(int[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(char[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
char tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
public static void sort(long[] A)
{
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i)
{
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
//max & min
public static int max(int a,int b){return Math.max(a,b);}
public static int min(int a,int b){return Math.min(a,b);}
public static int max(int a,int b,int c){return Math.max(a,Math.max(b,c));}
public static int min(int a,int b,int c){return Math.min(a,Math.min(b,c));}
public static long max(long a,long b){return Math.max(a,b);}
public static long min(long a,long b){return Math.min(a,b);}
public static long max(long a,long b,long c){return Math.max(a,Math.max(b,c));}
public static long min(long a,long b,long c){return Math.min(a,Math.min(b,c));}
public static int maxinA(int a[]){int n=a.length;int mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;}
public static long maxinA(long a[]){int n=a.length;long mx=a[0];for(int i=1;i<n;i++){mx=max(mx,a[i]);}return mx;}
public static int mininA(int a[]){int n=a.length;int mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;}
public static long mininA(long a[]){int n=a.length;long mn=a[0];for(int i=1;i<n;i++){mn=min(mn,a[i]);}return mn;}
public static long suminA(int a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;}
public static long suminA(long a[]){int n=a.length;long sum=0;for(int i=0;i<n;i++){sum+=a[i];}return sum;}
//end
public static int[] I(int n){int a[]=new int[n];for(int i=0;i<n;i++){a[i]=I();}return a;}
public static long[] IL(int n){long a[]=new long[n];for(int i=0;i<n;i++){a[i]=L();}return a;}
public static long[] prefix(int a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;}
public static long[] prefix(long a[]){int n=a.length;long pre[]=new long[n];pre[0]=a[0];for(int i=1;i<n;i++){pre[i]=pre[i-1]+a[i];}return pre;}
public static int I(){return sc.I();}
public static long L(){return sc.L();}
public static String S(){return sc.S();}
public static double D(){return sc.D();}
}
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 I(){ return Integer.parseInt(next());}
long L(){ return Long.parseLong(next());}
double D(){return Double.parseDouble(next());}
String S(){
String str = "";
try {
str = br.readLine();
}
catch (IOException e){
e.printStackTrace();
}
return str;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
ea8a2d0745680789cb4bb6eb31fc76ea
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
public static PrintWriter out;
static ArrayList<ArrayList<Integer>>al;
static int ans;
static int min[];
static int max[];
public static void main(String[] args)throws IOException {
JS sc=new JS();
out = new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
al=new ArrayList<>();
for(int i=0;i<n;i++) {
al.add(new ArrayList<>());
}
for(int i=1;i<n;i++) {
int a=sc.nextInt()-1;
al.get(i).add(a);
al.get(a).add(i);
}
ans=0;
min=new int[n];
max=new int[n];
for(int i=0;i<n;i++) {
min[i]=sc.nextInt();
max[i]=sc.nextInt();
}
dfs(0, -1);
out.println(ans);
}
out.close();
}
static long dfs(int cur, int par) {
long total=0;
for(int next:al.get(cur)) {
if(next!=par) {
total+=dfs(next, cur);
}
}
if(total>max[cur]) {
total=max[cur];
}else if(total<min[cur]) {
total=max[cur];
ans++;
}
return total;
}
static class JS {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
de4b94afd8e9b789e5c80b293fdf6461
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees{
static long mod = 1000000007L;
static MyScanner sc = new MyScanner();
static int ans;
static void solve() {
ans = 0;
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for(int i = 0;i<n;i++) tree.add(new ArrayList<>());
for(int i = 0;i<n-1;i++){
int a = sc.nextInt()-1;
tree.get(a).add(i+1);
tree.get(i+1).add(a);
}
int l[] = new int[n];
int r[] = new int[n];
for(int i= 0;i<n;i++){
l[i] = sc.nextInt();
r[i] = sc.nextInt();
}
function(tree,l,r,-1,0,0);
out.println(ans);
}
static long function(ArrayList<ArrayList<Integer>> tree,int l[],int r[],int pare,int cur,long sum){
long s = 0;
for(int v: tree.get(cur)){
if(v!=pare){
s += function(tree,l,r,cur,v,sum);
}
}
if(s<l[cur]){
ans++;
return r[cur];
}
if(s<r[cur]) return s;
return r[cur];
}
static long comb(int n,int k){
return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod;
}
static long factorial(int n){
long ret = 1;
while(n > 0){
ret = ret * n % mod;
n--;
}
return ret;
}
static class Pair implements Comparable<Pair>{
long a;
long b;
Pair(long aa,long bb){
a = aa;
b = bb;
}
public int compareTo(Pair p){
return Long.compare(this.b,p.b);
}
}
static void reverse(int arr[]){
int i = 0;int j = arr.length-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long pow(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res * res) % 1_000_000_007;
if (b % 2 == 1) {
res = (res * a) % 1_000_000_007;
}
return res;
}
static int lis(int arr[],int n){
int lis[] = new int[n];
lis[0] = 1;
for(int i = 1;i<n;i++){
lis[i] = 1;
for(int j = 0;j<i;j++){
if(arr[i]>arr[j]){
lis[i] = Math.max(lis[i],lis[j]+1);
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0;i<n;i++){
max = Math.max(lis[i],max);
}
return max;
}
static boolean isPali(String str){
int i = 0;
int j = str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static String reverse(String str){
char arr[] = str.toCharArray();
int i = 0;
int j = arr.length-1;
while(i<j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
String st = new String(arr);
return st;
}
static boolean isprime(int n){
if(n==1) return false;
if(n==3 || n==2) return true;
if(n%2==0 || n%3==0) return false;
for(int i = 5;i*i<=n;i+= 6){
if(n%i== 0 || n%(i+2)==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
// int t= 1;
while(t-- >0){
solve();
// solve2();
// solve3();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------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));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
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;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
d634c928db128b01cacd9c9949a166d7
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
/*
Goal: Become better in CP!
Key: Consistency and Discipline
Desire: SDE @ Google USA
Motto: Do what i Love <=> Love what i do
If you don't use your brain 100%, it deteriorates gradually
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class A {
static StringBuffer str=new StringBuffer();
static int n;
static List<List<Integer>> l;
static long la[];
static long ra[];
static long ans=0;
static long[] dfs(int u, int p){
long min=0, max=0;
for(int v:l.get(u)){
if(v!=p){
long a[]=dfs(v, u);
min+=a[0];
max+=a[1];
}
}
if(max<la[u]){
ans++;
return new long[]{la[u], ra[u]};
}
min=Math.max(min, la[u]);
max=Math.min(max, ra[u]);
return new long[]{min, max};
}
static void solve(){
ans=0;
dfs(1, 0);
str.append(ans).append("\n");
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf;
PrintWriter pw;
boolean lenv=false;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
int q1 = Integer.parseInt(bf.readLine().trim());
while (q1-- > 0) {
n=Integer.parseInt(bf.readLine().trim());
l=new ArrayList<>();
for(int i=0;i<=n;i++) l.add(new ArrayList<>());
String s[]=bf.readLine().trim().split("\\s+");
for(int i=0;i<n-1;i++){
int u=Integer.parseInt(s[i]);
l.get(i+2).add(u);
l.get(u).add(i+2);
}
la=new long[n+1];
ra=new long[n+1];
for(int i=0;i<n;i++){
s=bf.readLine().trim().split("\\s+");
la[i+1]=Integer.parseInt(s[0]);
ra[i+1]=Integer.parseInt(s[1]);
}
solve();
}
pw.println(str);
pw.flush();
// System.outin.print(str);
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
70559097c9bf871ee9884bbb2ac42d5c
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class R800D1B {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream input;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
input = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) {
try {
input = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
} catch (IOException e) { e.printStackTrace(); }
}
public String readLine() {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() {
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(){
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() {
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;
}
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;
}
private void fillBuffer() {
try {
bytesRead = input.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
} catch(IOException e) { e.printStackTrace(); }
}
private byte read() {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() {
try {
if (input == null)
return;
input.close();
} catch(IOException e) { e.printStackTrace(); }
}
}
static class FastWriter {
BufferedWriter output;
public FastWriter() {
output = new BufferedWriter(
new OutputStreamWriter(System.out));
}
void write(String s) {
try {
output.write(s);
} catch (IOException e) { e.printStackTrace(); }
}
void endLine() {
try {
output.write("\n");
output.flush();
} catch (IOException e) { e.printStackTrace(); }
}
void writeInt(int x) {
write(Integer.toString(x));
endLine();
}
void writeLong(long x) {
write(Long.toString(x));
endLine();
}
void writeLine(String line) {
write(line);
endLine();
}
void writeIntArray(int[] a) {
write(Integer.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Integer.toString(a[i]));
}
endLine();
}
void writeLongArray(long[] a) {
write(Long.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Long.toString(a[i]));
}
endLine();
}
}
public static class Utility {
public static void safeSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void safeSort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
public static void shuffle(long[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
public static List<Integer>[] tree;
public static int[][] lr;
public static long[] max;
public static int c;
static long maxFlow(int i) {
max[i] = 0;
if(tree[i] == null) {
c ++;
return lr[i][1];
}
for(int j : tree[i])
max[i] += maxFlow(j);
if(max[i] < lr[i][0])
c++;
if(max[i] < lr[i][0] || max[i] > lr[i][1])
max[i] = lr[i][1];
return max[i];
}
public static void main(String[] args)
{
Reader r = new Reader();
FastWriter w = new FastWriter();
int cases = r.nextInt();
for(int test = 0; test < cases; test ++) {
//INPUT
int n = r.nextInt();
//int k = r.nextInt();
int[] a = r.nextIntArray(n-1);
lr = new int[n][2];
for(int i = 0; i < n; i ++) {
lr[i][0] = r.nextInt();
lr[i][1] = r.nextInt();
}
//CODE
tree = new LinkedList[n];
max = new long[n];
for(int i = 0; i < n-1; i ++) {
if(tree[a[i]-1] == null)
tree[a[i]-1] = new LinkedList<>();
tree[a[i] - 1].add(i + 1);
}
c = 0;
maxFlow(0);
//END CODE
//OUTPUT
w.writeInt(c);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
0ea23a63e9b5616fd4182edb59abfd0f
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
//package kg.my_algorithms.Codeforces;
//import static kg.my_algorithms.Mathematics.*;
import java.io.*;
import java.util.*;
public class Solution {
private static long moves = 0;
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int test_cases = fr.nextInt();
for(int test=1;test<=test_cases;test++){
int n = fr.nextInt();
moves = 0;
List<List<Integer>> tree = new ArrayList<>();
for(int i=0;i<n;i++) tree.add(new ArrayList<>());
for(int i=1;i<n;i++){
tree.get(fr.nextInt()-1).add(i);
}
int[][] range = new int[n][2];
for(int i=0;i<n;i++) {
range[i][0] = fr.nextInt();
range[i][1] = fr.nextInt();
}
// System.out.println(tree);
fun(0,range,tree);
output.write(moves+"\n");
}
output.flush();
}
private static long fun(int node, int[][] range, List<List<Integer>> tree){
long sum = 0L;
for(int c: tree.get(node)) sum += fun(c,range,tree);
if(range[node][0] <= sum && sum <= range[node][1]) return sum;
else if(sum > range[node][1]) return range[node][1];
moves++;
return range[node][1];
}
}
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
94528cd2e1081b9b88655d697f419b12
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
import java.io.*;
// cd C:\Users\Lenovo\Desktop\New
//ArrayList<Integer> a=new ArrayList<>();
//List<Integer> lis=new ArrayList<>();
//StringBuilder ans = new StringBuilder();
//HashMap<Integer,Integer> map=new HashMap<>();
public class cf {
static FastReader in=new FastReader();
static final Random random=new Random();
//static long m=1000000007l;
static long mod=1000000007l;
//static long dp[]=new long[200002];
//static ArrayList<Integer> ans;
//static ArrayList<ArrayList<String>> ans;
static long ans;
public static void main(String args[]) throws IOException {
FastReader sc=new FastReader();
//Scanner s=new Scanner(System.in);
int tt=sc.nextInt();
//int tt=1;
while(tt-->0){
int n=sc.nextInt();
ArrayList<ArrayList<Integer>> arr=new ArrayList<>();
for(int i=0;i<=n;i++){
arr.add(new ArrayList<Integer>());
}
for(int i=2;i<=n;i++){
arr.get(sc.nextInt()).add(i);
}
int left[]=new int[n+1];
int right[]=new int[n+1];
for(int i=1;i<=n;i++){
left[i]=sc.nextInt();
right[i]=sc.nextInt();
}
ans=0;
dfs(arr,1,left,right);
System.out.println(ans);
}
}
public static long dfs(ArrayList<ArrayList<Integer>>arr,int idx,int[]l,int[]r){
long sum=0;
ArrayList<Integer> list=arr.get(idx);
for(int key:arr.get(idx)){
sum+=dfs(arr,key,l,r);
}
if(sum<l[idx]){
ans++;
return r[idx];
}
return Math.min(sum,1l*r[idx]);
}
public static boolean isPal(String temp){
for(int i=0;i<temp.length();i++){
if(temp.charAt(i)!=temp.charAt(temp.length()-1-i)){
return false;
}
}
return true;
}
/*static void bfs(){
dist[1]=0;
for(int i=2;i<dist.length;i++){
dist[i]=-1;
}
Queue<Integer> q=new LinkedList<>();
q.add(1);
while(q.size()!=0){
int cur=q.peek();
q.remove();
for(int i=1;i<dist.length;i++ ){
int next=cur+cur/i;
int ndis=dist[cur]+1;
if(next<dist.length && dist[next]==-1){
dist[next]=ndis;
q.add(next);
}
}
}
}*/
static long comb(int n,int k){
return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod;
}
static long pow(long a, long b) {
// long mod=1000000007;
long res = 1;
while (b != 0) {
if ((b & 1) != 0) {
res = (res * a) % mod;
}
a = (a * a) % mod;
b /= 2;
}
return res;
}
static boolean powOfTwo(long n){
while(n%2==0){
n=n/2;
}
if(n!=1){
return false;
}
return true;
}
static int upper_bound(long arr[], long key)
{
int mid, N = arr.length;
int low = 0;
int high = N;
// Till low is less than high
while (low < high && low != N) {
mid = low + (high - low) / 2;
if (key >= arr[mid]) {
low = mid + 1;
}
else {
high = mid;
}
}
return low;
}
static boolean prime(int n){
for(int i=2;i<=Math.sqrt(n);i++){
if(n%i==0){
return false;
}
}
return true;
}
static long factorial(int n){
long ret = 1;
while(n > 0){
ret = ret * n % mod;
n--;
}
return ret;
}
static long find(ArrayList<Long> arr,long n){
int l=0;
int r=arr.size();
while(l+1<r){
int mid=(l+r)/2;
if(arr.get(mid)<n){
l=mid;
}
else{
r=mid;
}
}
return arr.get(l);
}
static void rotate(int ans[]){
int last=ans[0];
for(int i=0;i<ans.length-1;i++){
ans[i]=ans[i+1];
}
ans[ans.length-1]=last;
}
static int countprimefactors(int n){
int ans=0;
int z=(int)Math.sqrt(n);
for(int i=2;i<=z;i++){
while(n%i==0){
ans++;
n=n/i;
}
}
if(n>1){
ans++;
}
return ans;
}
static String reverse_String(String s){
String ans="";
for(int i=s.length()-1;i>=0;i--){
ans+=s.charAt(i);
}
return ans;
}
static void reverse_array(int arr[]){
int l=0;
int r=arr.length-1;
while(l<r){
int temp=arr[l];
arr[l]=arr[r];
arr[r]=temp;
l++;
r--;
}
}
static int msb(int x){
int ans=0;
while(x!=0){
x=x/2;
ans++;
}
return ans;
}
static void ruffleSort(int[] a) {
int n=a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
int temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static long gcd(long a,long b)
{
if(b==0)
{
return a;
}
return gcd(b,a%b);
}
/* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<Integer, Integer> entry = iterator.next();
int value = entry.getValue();
if(value==1){
iterator.remove();
}
else{
entry.setValue(value-1);
}
}
*/
static class Pair //implements Comparable
{
char a;
int b;
public String toString()
{
return a+" " + b;
}
public Pair(char x , int y)
{
a=x;b=y;
}
//@Override
/*public int compareTo(Object o) {
Pair p = (Pair)o;
if(b!=p.b){
return b-p.b;
}
else{
return a-p.a;
}
/*if(p.a!=a){
return a-p.a;//in
}
else{
return b-p.b;//
}
}*/
}
public static boolean checkAP(List<Integer> lis){
for(int i=1;i<lis.size()-1;i++){
if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){
return false;
}
}
return true;
}
/* public static int minBS(int[]arr,int val){
int l=-1;
int r=arr.length;
while(r>l+1){
int mid=(l+r)/2;
if(arr[mid]>=val){
r=mid;
}
else{
l=mid;
}
}
return r;
}
public static int maxBS(int[]arr,int val){
int l=-1;
int r=arr.length;
while(r>l+1){
int mid=(l+r)/2;
if(arr[mid]<=val){
l=mid;
}
else{
r=mid;
}
}
return l;
}
*/
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
ba80f549ac6d8a1a3ab119c3ba940e1a
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args) {
new Thread(null, new Main(), "", 256 * (1L << 20)).start();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
if (System.getProperty("ONLINE_JUDGE") != null) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
Locale.setDefault(Locale.US);
solve();
in.close();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readIntArray(int n) throws IOException {
int [] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = readInt();
}
return a;
}
long[] readLongArray(int n) throws IOException {
long [] a = new long[n];
for(int i = 0; i < n; i++) {
a[i] = readLong();
}
return a;
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
class EdgeList {
public ArrayList<Integer> edges = new ArrayList<>();
public long l;
public long r;
}
EdgeList[] tree;
int count;
long dfs(int node) {
if (tree[node].edges.size() == 0) {
count++;
return tree[node].r;
}
long sum = 0;
for(int i=0;i<tree[node].edges.size();i++) {
long c = dfs(tree[node].edges.get(i));
sum += c;
}
if(sum >= tree[node].l) {
return Math.min(tree[node].r, sum);
} else {
count++;
return tree[node].r;
}
}
void solveTest() throws IOException {
int n = readInt();
tree = new EdgeList[n];
for(int i=0;i<n;i++) {
tree[i] = new EdgeList();
}
for(int i=0;i<n-1;i++) {
int p = readInt();
p--;
tree[p].edges.add(i+1);
}
for(int i=0;i<n;i++) {
tree[i].l = readLong();
tree[i].r = readLong();
}
if (n == 1) {
out.println(1);
return;
}
count = 0;
dfs(0);
out.println(count);
}
void solve() throws IOException {
int numTests = readInt();
while(numTests-->0) {
solveTest();
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
a5c3332a77967be69007035e233d0853
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.util.Comparator.*;
public class Solution {
public static boolean useInFile = false;
public static boolean useOutFile = false;
public static void main(String args[]) throws IOException {
InOut inout = new InOut();
Resolver resolver = new Resolver(inout);
// long time = System.currentTimeMillis();
resolver.solve();
// resolver.print("\n" + (System.currentTimeMillis() - time));
inout.flush();
}
private static class Resolver {
final long LONG_INF = (long) 1e18;
final int INF = (int) (1e9 + 7);
final int MOD = 998244353;
long f[], inv[];
InOut inout;
Resolver(InOut inout) {
this.inout = inout;
}
void initF(int n, int mod) {
f = new long[n + 1];
f[1] = 1;
for (int i = 2; i <= n; i++) {
f[i] = (f[i - 1] * i) % mod;
}
}
void initInv(int n, int mod) {
inv = new long[n + 1];
inv[n] = pow(f[n], mod - 2, mod);
for (int i = inv.length - 2; i >= 0; i--) {
inv[i] = inv[i + 1] * (i + 1) % mod;
}
}
long cmn(int n, int m, int mod) {
return f[n] * inv[m] % mod * inv[n - m] % mod;
}
int d[] = {0, -1, 0, 1, 0};
boolean legal(int r, int c, int n, int m) {
return r >= 0 && r < n && c >= 0 && c < m;
}
int[] getBits(int n) {
int b[] = new int[31];
for (int i = 0; i < 31; i++) {
if ((n & (1 << i)) != 0) {
b[i] = 1;
}
}
return b;
}
private char ask1(int i) throws IOException {
format("? 1 %d\n", i);
flush();
return next(10).charAt(0);
}
int ans = 0;
int dfs(int f, int l[], int r[]) {
List<Integer> es = adj[f];
if (es.size() == 0) {
ans++;
return r[f];
}
long max = 0;
for (int i = 0; i < es.size(); i++) {
int t = es.get(i);
max += dfs(t, l, r);
}
if (max >= l[f]) {
return (int) Math.min(max, r[f]);
}
ans++;
return r[f];
}
void solve() throws IOException {
int tt = 1;
boolean hvt = true;
if (hvt) {
tt = nextInt();
// tt = Integer.parseInt(nextLine());
}
// initF(300001, MOD);
// initInv(300001, MOD);
// boolean pri[] = generatePrime(40000);
for (int cs = 1; cs <= tt; cs++) {
long rs = 0;
int n = nextInt();
int p[] = anInt(2, n);
int l[] = new int[n + 1];
int r[] = new int[n + 1];
for (int i = 0; i < n; i++) {
l[i + 1] = nextInt();
r[i + 1] = nextInt();
}
adj = new List[n + 1];
for (int i = 1; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 2; i <= n; i++) {
adj[p[i]].add(i);
}
ans = 0;
dfs(1, l, r);
rs = ans;
print("" + rs);
if (cs < tt) {
format("\n");
// format(" ");
}
// flush();
}
}
private void updateSegTree(int n, long l, SegmentTree lft) {
long lazy;
lazy = 1;
for (int j = 1; j <= l; j++) {
lazy = (lazy + cmn((int) l, j, INF)) % INF;
lft.modify(1, j, j, lazy);
}
lft.modify(1, (int) (l + 1), n, lazy);
}
String next() throws IOException {
return inout.next();
}
String next(int n) throws IOException {
return inout.next(n);
}
String nextLine() throws IOException {
return inout.nextLine();
}
int nextInt() throws IOException {
return inout.nextInt();
}
long nextLong(int n) throws IOException {
return inout.nextLong(n);
}
int[] anInt(int i, int j) throws IOException {
int a[] = new int[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextInt();
}
return a;
}
long[] anLong(int i, int j, int len) throws IOException {
long a[] = new long[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextLong(len);
}
return a;
}
void print(String s) {
inout.print(s, false);
}
void print(String s, boolean nextLine) {
inout.print(s, nextLine);
}
void format(String format, Object... obj) {
inout.format(format, obj);
}
void flush() {
inout.flush();
}
void swap(int a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
void swap(long a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
int getP(int x, int p[]) {
if (p[x] == 0 || p[x] == x) {
return x;
}
return p[x] = getP(p[x], p);
}
void union(int x, int y, int p[]) {
if (x < y) {
p[y] = x;
} else {
p[x] = y;
}
}
boolean topSort() {
int n = adj2.length - 1;
int d[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < adj2[i].size(); j++) {
d[adj2[i].get(j)[0]]++;
}
}
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (d[i] == 0) {
list.add(i);
}
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < adj2[list.get(i)].size(); j++) {
int t = adj2[list.get(i)].get(j)[0];
d[t]--;
if (d[t] == 0) {
list.add(t);
}
}
}
return list.size() == n;
}
class SegmentTreeNode {
long defaultVal = 0;
int l, r;
long val = defaultVal, lazy = defaultVal;
SegmentTreeNode(int l, int r) {
this.l = l;
this.r = r;
}
}
class SegmentTree {
SegmentTreeNode tree[];
long inf = Long.MIN_VALUE;
// long c[];
SegmentTree(int n) {
assert n > 0;
tree = new SegmentTreeNode[n * 3 + 1];
}
void setAn(long cn[]) {
// c = cn;
}
SegmentTree build(int k, int l, int r) {
if (l > r) {
return this;
}
if (null == tree[k]) {
tree[k] = new SegmentTreeNode(l, r);
}
if (l == r) {
return this;
}
int mid = (l + r) >> 1;
build(k << 1, l, mid);
build(k << 1 | 1, mid + 1, r);
return this;
}
void pushDown(int k) {
if (tree[k].l == tree[k].r) {
return;
}
long lazy = tree[k].lazy;
// tree[k << 1].val = ((c[tree[k << 1].l] - c[tree[k << 1].r + 1] + MOD) % MOD * lazy) % MOD;
tree[k << 1].val = lazy;
tree[k << 1].lazy = lazy;
// tree[k << 1 | 1].val = ((c[tree[k << 1 | 1].l] - c[tree[k << 1 | 1].r + 1] + MOD) % MOD * lazy) % MOD;
tree[k << 1 | 1].val = lazy;
tree[k << 1 | 1].lazy = lazy;
tree[k].lazy = 0;
}
void modify(int k, int l, int r, long val) {
if (tree[k].l >= l && tree[k].r <= r) {
// tree[k].val = ((c[tree[k].l] - c[tree[k].r + 1] + MOD) % MOD * val) % MOD;
tree[k].val = val;
tree[k].lazy = val;
return;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (tree[k].lazy != 0) {
pushDown(k);
}
if (mid >= l) {
modify(k << 1, l, r, val);
}
if (mid + 1 <= r) {
modify(k << 1 | 1, l, r, val);
}
// tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
tree[k].val = Math.max(tree[k << 1].val, tree[k << 1 | 1].val);
}
long query(int k, int l, int r) {
if (tree[k].l > r || tree[k].r < l) {
return 0;
}
if (tree[k].lazy != 0) {
pushDown(k);
}
if (tree[k].l >= l && tree[k].r <= r) {
return tree[k].val;
}
long ans = (query(k << 1, l, r) + query(k << 1 | 1, l, r)) % MOD;
if (tree[k].l < tree[k].r) {
// tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
tree[k].val = Math.max(tree[k << 1].val, tree[k << 1 | 1].val);
}
return ans;
}
}
class BitMap {
boolean[] vis = new boolean[32];
List<Integer> g[];
void init() {
for (int i = 0; i < 32; i++) {
g = new List[32];
g[i] = new ArrayList<>();
}
}
void dfs(int p) {
if (vis[p]) return;
vis[p] = true;
for (int it : g[p]) dfs(it);
}
boolean connected(int a[], int n) {
int m = 0;
for (int i = 0; i < n; i++) if (a[i] == 0) return false;
for (int i = 0; i < n; i++) m |= a[i];
for (int i = 0; i < 31; i++) g[i].clear();
for (int i = 0; i < n; i++) {
int last = -1;
for (int j = 0; j < 31; j++)
if ((a[i] & (1 << j)) > 0) {
if (last != -1) {
g[last].add(j);
g[j].add(last);
}
last = j;
}
}
Arrays.fill(vis, false);
for (int j = 0; j < 31; j++)
if (((1 << j) & m) > 0) {
dfs(j);
break;
}
for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0 && !vis[j]) return false;
return true;
}
}
class BinaryIndexedTree {
int n = 1;
long C[];
BinaryIndexedTree(int sz) {
while (n <= sz) {
n <<= 1;
}
n = sz + 1;
C = new long[n];
}
int lowbit(int x) {
return x & -x;
}
void add(int x, long val) {
while (x < n) {
C[x] += val;
x += lowbit(x);
}
}
long getSum(int x) {
long res = 0;
while (x > 0) {
res += C[x];
x -= lowbit(x);
}
return res;
}
int binSearch(long sum) {
if (sum == 0) {
return 0;
}
int n = C.length;
int mx = 1;
while (mx < n) {
mx <<= 1;
}
int res = 0;
for (int i = mx / 2; i >= 1; i >>= 1) {
if (C[res + i] < sum) {
sum -= C[res + i];
res += i;
}
}
return res + 1;
}
}
static class TrieNode {
int cnt = 0;
TrieNode next[];
TrieNode() {
next = new TrieNode[2];
}
private void insert(TrieNode trie, int ch[], int i) {
while (i < ch.length) {
int idx = ch[i];
if (null == trie.next[idx]) {
trie.next[idx] = new TrieNode();
}
trie.cnt++;
trie = trie.next[idx];
i++;
}
}
private static int query(TrieNode trie) {
if (null == trie) {
return 0;
}
int ans[] = new int[2];
for (int i = 0; i < trie.next.length; i++) {
if (null == trie.next[i]) {
continue;
}
ans[i] = trie.next[i].cnt;
}
if (ans[0] == 0 && ans[0] == ans[1]) {
return 0;
}
if (ans[0] == 0) {
return query(trie.next[1]);
}
if (ans[1] == 0) {
return query(trie.next[0]);
}
return Math.min(ans[0] - 1 + query(trie.next[1]), ans[1] - 1 + query(trie.next[0]));
}
}
//Binary tree
class TreeNode {
int val;
int tier = -1;
TreeNode parent;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
//binary tree dfs
void tierTree(TreeNode root) {
if (null == root) {
return;
}
if (null != root.parent) {
root.tier = root.parent.tier + 1;
} else {
root.tier = 0;
}
tierTree(root.left);
tierTree(root.right);
}
//LCA start
TreeNode[][] lca;
TreeNode[] tree;
void lcaDfsTree(TreeNode root) {
if (null == root) {
return;
}
tree[root.val] = root;
TreeNode nxt = root.parent;
int idx = 0;
while (null != nxt) {
lca[root.val][idx] = nxt;
nxt = lca[nxt.val][idx];
idx++;
}
lcaDfsTree(root.left);
lcaDfsTree(root.right);
}
TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException {
if (null == root) {
return null;
}
if (-1 == root.tier) {
tree = new TreeNode[n + 1];
tierTree(root);
}
if (null == lca) {
lca = new TreeNode[n + 1][31];
lcaDfsTree(root);
}
int z = Math.abs(x.tier - y.tier);
int xx = x.tier > y.tier ? x.val : y.val;
while (z > 0) {
final int zz = z;
int l = (int) BinSearch.bs(0, 31
, k -> zz < (1 << k));
xx = lca[xx][l].val;
z -= 1 << l;
}
int yy = y.val;
if (x.tier <= y.tier) {
yy = x.val;
}
while (xx != yy) {
final int xxx = xx;
final int yyy = yy;
int l = (int) BinSearch.bs(0, 31
, k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]);
xx = lca[xx][l].val;
yy = lca[yy][l].val;
}
return tree[xx];
}
//LCA end
//graph
List<Integer> adj[];
List<int[]> adj2[];
void initGraph(int n, int m, boolean hasW, boolean directed, int type) throws IOException {
if (type == 1) {
adj = new List[n + 1];
} else {
adj2 = new List[n + 1];
}
for (int i = 1; i <= n; i++) {
if (type == 1) {
adj[i] = new ArrayList<>();
} else {
adj2[i] = new ArrayList<>();
}
}
for (int i = 0; i < m; i++) {
int f = nextInt();
int t = nextInt();
if (type == 1) {
adj[f].add(t);
if (!directed) {
adj[t].add(f);
}
} else {
int w = hasW ? nextInt() : 0;
adj2[f].add(new int[]{t, w});
if (!directed) {
adj2[t].add(new int[]{f, w});
}
}
}
}
void getDiv(Map<Integer, Integer> map, long n) {
int sqrt = (int) Math.sqrt(n);
for (int i = 2; i <= sqrt; i++) {
int cnt = 0;
while (n % i == 0) {
cnt++;
n /= i;
}
if (cnt > 0) {
map.put(i, cnt);
}
}
if (n > 1) {
map.put((int) n, 1);
}
}
boolean[] generatePrime(int n) {
boolean p[] = new boolean[n + 1];
p[2] = true;
for (int i = 3; i <= n; i += 2) {
p[i] = true;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (!p[i]) {
continue;
}
for (int j = i * i; j <= n; j += i << 1) {
p[j] = false;
}
}
return p;
}
boolean isPrime(long n) { //determines if n is a prime number
int p[] = {2, 3, 5, 233, 331};
int pn = p.length;
long s = 0, t = n - 1;//n - 1 = 2^s * t
while ((t & 1) == 0) {
t >>= 1;
++s;
}
for (int i = 0; i < pn; ++i) {
if (n == p[i]) {
return true;
}
long pt = pow(p[i], t, n);
for (int j = 0; j < s; ++j) {
long cur = llMod(pt, pt, n);
if (cur == 1 && pt != 1 && pt != n - 1) {
return false;
}
pt = cur;
}
if (pt != 1) {
return false;
}
}
return true;
}
long[] llAdd2(long a[], long b[], long mod) {
long c[] = new long[2];
c[1] = (a[1] + b[1]) % (mod * mod);
c[0] = (a[1] + b[1]) / (mod * mod) + a[0] + b[0];
return c;
}
long[] llMod2(long a, long b, long mod) {
long x1 = a / mod;
long y1 = a % mod;
long x2 = b / mod;
long y2 = b % mod;
long c = (x1 * y2 + x2 * y1) / mod;
c += x1 * x2;
long d = (x1 * y2 + x2 * y1) % mod * mod + y1 * y2;
return new long[]{c, d};
}
long llMod(long a, long b, long mod) {
if (a > mod || b > mod) {
return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod;
}
return a * b % mod;
// long r = 0;
// a %= mod;
// b %= mod;
// while (b > 0) {
// if ((b & 1) == 1) {
// r = (r + a) % mod;
// }
// b >>= 1;
// a = (a << 1) % mod;
// }
// return r;
}
long pow(long a, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = ans * a;
}
a = a * a;
n >>= 1;
}
return ans;
}
long pow(long a, long n, long mod) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = llMod(ans, a, mod);
}
a = llMod(a, a, mod);
n >>= 1;
}
return ans;
}
private long[][] initC(int n) {
long c[][] = new long[n][n];
for (int i = 0; i < n; i++) {
c[i][0] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
return c;
}
/**
* ps: n >= m, choose m from n;
*/
// private int cmn(long n, long m) {
// if (m > n) {
// n ^= m;
// m ^= n;
// n ^= m;
// }
// m = Math.min(m, n - m);
//
// long top = 1;
// long bot = 1;
// for (long i = n - m + 1; i <= n; i++) {
// top = (top * i) % MOD;
// }
// for (int i = 1; i <= m; i++) {
// bot = (bot * i) % MOD;
// }
//
// return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD);
// }
long[] exGcd(long a, long b) {
if (b == 0) {
return new long[]{a, 1, 0};
}
long[] ans = exGcd(b, a % b);
long x = ans[2];
long y = ans[1] - a / b * ans[2];
ans[1] = x;
ans[2] = y;
return ans;
}
long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b != 0) {
long tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int[] unique(int a[], Map<Integer, Integer> idx) {
int tmp[] = a.clone();
Arrays.sort(tmp);
int j = 0;
for (int i = 0; i < tmp.length; i++) {
if (i == 0 || tmp[i] > tmp[i - 1]) {
idx.put(tmp[i], j++);
}
}
int rs[] = new int[j];
j = 0;
for (int key : idx.keySet()) {
rs[j++] = key;
}
Arrays.sort(rs);
return rs;
}
boolean isEven(long n) {
return (n & 1) == 0;
}
static class BinSearch {
static long bs(long l, long r, IBinSearch sort) throws IOException {
while (l < r) {
long m = l + (r - l) / 2;
if (sort.binSearchCmp(m)) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
interface IBinSearch {
boolean binSearchCmp(long k) throws IOException;
}
}
}
private static class InOut {
private BufferedReader br;
private StreamTokenizer st;
private PrintWriter pw;
InOut() throws FileNotFoundException {
if (useInFile) {
System.setIn(new FileInputStream("resources/inout/in.text"));
}
if (useOutFile) {
System.setOut(new PrintStream("resources/inout/out.text"));
}
br = new BufferedReader(new InputStreamReader(System.in));
st = new StreamTokenizer(br);
pw = new PrintWriter(new OutputStreamWriter(System.out));
st.ordinaryChar('\'');
st.ordinaryChar('\"');
st.ordinaryChar('/');
}
private boolean hasNext() throws IOException {
return st.nextToken() != StreamTokenizer.TT_EOF;
}
private long[] anLong(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
private String next() throws IOException {
if (st.nextToken() == StreamTokenizer.TT_EOF) {
throw new IOException();
}
return st.sval;
}
private String next(int n) throws IOException {
return next(n, false);
}
private String next(int len, boolean isDigit) throws IOException {
char ch[] = new char[len];
int cur = 0;
char c;
while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t'
|| (isDigit && (c < '0' || c > '9'))) ;
do {
ch[cur++] = c;
} while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t')
&& (!isDigit || c >= '0' && c <= '9'));
return String.valueOf(ch, 0, cur);
}
private int nextInt() throws IOException {
if (st.nextToken() == StreamTokenizer.TT_EOF) {
throw new IOException();
}
return (int) st.nval;
}
private long nextLong(int n) throws IOException {
return Long.parseLong(next(n, true));
}
private double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
private String[] nextSS(String reg) throws IOException {
return br.readLine().split(reg);
}
private String nextLine() throws IOException {
return br.readLine();
}
private void print(String s, boolean newLine) {
if (null != s) {
pw.print(s);
}
if (newLine) {
pw.println();
}
}
private void format(String format, Object... obj) {
pw.format(format, obj);
}
private void flush() {
pw.flush();
}
}
private static class FFT {
double[] roots;
int maxN;
public FFT(int maxN) {
this.maxN = maxN;
initRoots();
}
public long[] multiply(int[] a, int[] b) {
int minSize = a.length + b.length - 1;
int bits = 1;
while (1 << bits < minSize) bits++;
int N = 1 << bits;
double[] aa = toComplex(a, N);
double[] bb = toComplex(b, N);
fftIterative(aa, false);
fftIterative(bb, false);
double[] c = new double[aa.length];
for (int i = 0; i < N; i++) {
c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1];
c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i];
}
fftIterative(c, true);
long[] ret = new long[minSize];
for (int i = 0; i < ret.length; i++) {
ret[i] = Math.round(c[2 * i]);
}
return ret;
}
static double[] toComplex(int[] arr, int size) {
double[] ret = new double[size * 2];
for (int i = 0; i < arr.length; i++) {
ret[2 * i] = arr[i];
}
return ret;
}
void initRoots() {
roots = new double[2 * (maxN + 1)];
double ang = 2 * Math.PI / maxN;
for (int i = 0; i <= maxN; i++) {
roots[2 * i] = Math.cos(i * ang);
roots[2 * i + 1] = Math.sin(i * ang);
}
}
int bits(int N) {
int ret = 0;
while (1 << ret < N) ret++;
if (1 << ret != N) throw new RuntimeException();
return ret;
}
void fftIterative(double[] array, boolean inv) {
int bits = bits(array.length / 2);
int N = 1 << bits;
for (int from = 0; from < N; from++) {
int to = Integer.reverse(from) >>> (32 - bits);
if (from < to) {
double tmpR = array[2 * from];
double tmpI = array[2 * from + 1];
array[2 * from] = array[2 * to];
array[2 * from + 1] = array[2 * to + 1];
array[2 * to] = tmpR;
array[2 * to + 1] = tmpI;
}
}
for (int n = 2; n <= N; n *= 2) {
int delta = 2 * maxN / n;
for (int from = 0; from < N; from += n) {
int rootIdx = inv ? 2 * maxN : 0;
double tmpR, tmpI;
for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) {
tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1];
tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx];
array[arrIdx + n] = array[arrIdx] - tmpR;
array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI;
array[arrIdx] += tmpR;
array[arrIdx + 1] += tmpI;
rootIdx += (inv ? -delta : delta);
}
}
}
if (inv) {
for (int i = 0; i < array.length; i++) {
array[i] /= N;
}
}
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
b9863b5528e8159296ce81bb030a3b53
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
//make sure to make new file!
import java.io.*;
import java.util.*;
public class B800{
public static ArrayList<ArrayList<Integer>> adj;
public static int[] p;
public static long[] l;
public static long[] r;
public static int answer;
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(f.readLine());
for(int q = 1; q <= t; q++){
int n = Integer.parseInt(f.readLine());
adj = new ArrayList<ArrayList<Integer>>(n+1);
for(int k = 0; k <= n; k++){
adj.add(new ArrayList<Integer>());
}
p = new int[n+1];
StringTokenizer st = new StringTokenizer(f.readLine());
for(int k = 2; k <= n; k++){
p[k] = Integer.parseInt(st.nextToken());
adj.get(p[k]).add(k);
adj.get(k).add(p[k]);
}
l = new long[n+1];
r = new long[n+1];
for(int k = 1; k <= n; k++){
st = new StringTokenizer(f.readLine());
l[k] = Long.parseLong(st.nextToken());
r[k] = Long.parseLong(st.nextToken());
}
answer = 0;
long i = dfs(1,-1);
out.println(answer);
}
out.close();
}
public static long dfs(int v, int p){
long sum = 0L;
for(int nei : adj.get(v)){
if(nei == p) continue;
sum += dfs(nei,v);
}
if(sum < l[v]){
answer++;
return r[v];
}
if(sum < r[v]){
return sum;
}
return r[v];
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
ed625f0aeaa8cca469e0ab6fc1ec03cb
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int T=fs.nextInt();
// int T=1;
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
Node[] nodes=new Node[n];
for (int i=0; i<n; i++) nodes[i]=new Node();
for (int i=1; i<n; i++) {
int par=fs.nextInt()-1;
nodes[par].children.add(nodes[i]);
}
for (int i=0; i<n; i++) {
int min=fs.nextInt(), max=fs.nextInt();
nodes[i].minVal=min;
nodes[i].maxVal=max;
}
nodes[0].go();
// for (Node nn:nodes) {
// System.out.println(nn.minCost+" "+nn.maxForMinPrice+" "+nn.maxCost);
// }
System.out.println(nodes[0].minCost);
}
out.close();
}
static class Node {
int minVal, maxVal;
ArrayList<Node> children=new ArrayList<>();
int minCost, maxCost;
long maxForMinPrice;
void go() {
if (children.size()==0) {
minCost=1;
maxCost=1;
maxForMinPrice=maxVal;
return;
}
for (Node nn:children) {
nn.go();
minCost+=nn.minCost;
maxForMinPrice+=nn.maxForMinPrice;
}
maxForMinPrice=Math.min(maxForMinPrice, maxVal);
if (maxForMinPrice<minVal) {
minCost++;
maxCost=minCost;
maxForMinPrice=maxVal;
}
else {
maxCost=minCost+1;
}
}
}
static final Random random=new Random();
static final int mod=1_000_000_007;
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static long add(long a, long b) {
return (a+b)%mod;
}
static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
static long mul(long a, long b) {
return (a*b)%mod;
}
static long exp(long base, long exp) {
if (exp==0) return 1;
long half=exp(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static long[] factorials=new long[2_000_001];
static long[] invFactorials=new long[2_000_001];
static void precompFacts() {
factorials[0]=invFactorials[0]=1;
for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i);
invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2);
for (int i=invFactorials.length-2; i>=0; i--)
invFactorials[i]=mul(invFactorials[i+1], i+1);
}
static long nCk(int n, int k) {
return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k]));
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
203c8c1ac60f5c0281263722deeb0f45
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class FakePlasticTrees {
public static void main(String[] args) throws IOException {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
int T = in.nextInt();
for (int t = 0; t < T; t++) {
int N = in.nextInt();
int[] parent = new int[N];
List<Integer>[] adj = new ArrayList[N];
for (int i = 0; i < N; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 1; i < N; i++) {
parent[i] = in.nextInt() - 1;
adj[parent[i]].add(i);
}
int[] lo = new int[N], hi = new int[N];
for (int i = 0; i < N; i++) {
lo[i] = in.nextInt();
hi[i] = in.nextInt();
}
int[] depth = new int[N];
Queue<Integer> q = new LinkedList<>();
q.offer(0);
while (!q.isEmpty()) {
int current = q.poll();
for (int i : adj[current]) {
depth[i] = depth[current] + 1;
q.offer(i);
}
}
List<Integer> sort = new ArrayList<>();
for (int i = 0; i < N; i++) {
sort.add(i);
}
Collections.sort(sort, (a, b) -> depth[b] - depth[a]);
long[] arr = new long[N], count = new long[N];
for (int i : sort) {
for (int j : adj[i]) {
arr[i] += arr[j];
count[i] += count[j];
}
if (arr[i] > hi[i]) {
arr[i] = hi[i];
} else if (arr[i] < lo[i]) {
arr[i] = hi[i];
count[i]++;
}
}
out.println(count[0]);
}
out.close();
}
static class Reader {
BufferedReader in;
StringTokenizer st;
public Reader() {
in = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
public String next() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
}
public static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i : arr) {
list.add(i);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 8
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
c4fce26a444166b7dcee60153b57525b
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.Scanner;
import java.util.ArrayList;
public class Q1693B {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner k = new Scanner(System.in);
int t = k.nextInt();
for(int i=1; i<=t; i++)
{
int n = k.nextInt();
int par[] = new int[n];
for(int j=2;j<=n;j++)
{
par[j-1] = k.nextInt();
}
int min[] = new int[n];
int max[] = new int[n];
long value[] = new long[n];
int ans=0;
for(int j=1;j<=n;j++)
{
min[j-1] = k.nextInt();
max[j-1] = k.nextInt();
}
for(int v=n; v>=2; v--)
{
if(value[v-1]<min[v-1])
{
value[v-1] = max[v-1];
ans++;
}
else if(value[v-1]>max[v-1])
{
value[v-1] = max[v-1];
}
value[par[v-1]-1]+=value[v-1];
}
if(value[0]<min[0]) ans++;
System.out.println(ans);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
b1739eaab3553e3f490ab92b5b415176
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static AReader scan = new AReader();
static int N = 200010;
static int[] h = new int[N];
static int[] e = new int[N];
static int[] ne = new int[N];
static int[] L = new int[N];
static int[] R = new int[N];
static int[] dp = new int[N];
static int idx;
static void add(int a,int b){
e[idx] = b;ne[idx] = h[a];h[a] = idx++;
}
static long dfs(int u){
dp[u] = 0;
long sum = 0;
for(int i = h[u];i!=-1;i=ne[i]){
int j = e[i];
sum += dfs(j);
dp[u] += dp[j];
}
if(L[u] > sum){
dp[u]++;
sum = R[u];
}
return Math.min(sum,R[u]);
}
static void solve() {
int n = scan.nextInt();
for(int i = 1;i<=n;i++) h[i] = -1;
idx = 0;
for(int i = 2;i<=n;i++){
int fa = scan.nextInt();
add(fa,i);
}
for(int i = 1;i<=n;i++) {
L[i] = scan.nextInt();
R[i] = scan.nextInt();
}
dfs(1);
System.out.println(dp[1]);
}
public static void main(String[] args) {
int T = scan.nextInt();
while (T-- > 0) {
solve();
}
}
}
class AReader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
c25e82a125aab913f62718ee6cdfd917
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static AReader scan = new AReader();
static int N = 200010;
static int[] h = new int[N];
static int[] e = new int[N];
static int[] ne = new int[N];
static int[] L = new int[N];
static int[] R = new int[N];
static int[] dp = new int[N];
static int idx;
static void add(int a,int b){
e[idx] = b;ne[idx] = h[a];h[a] = idx++;
}
static long dfs(int u){
dp[u] = 0;
long sum = 0;
boolean flag = false;
for(int i = h[u];i!=-1;i=ne[i]){
int j = e[i];
sum += dfs(j);
dp[u] += dp[j];
flag = true;
}
if(L[u] > sum){
dp[u]++;
sum = R[u];
}
if(!flag) return R[u];
else return Math.min(sum,R[u]);
}
static void solve() {
int n = scan.nextInt();
for(int i = 1;i<=n;i++) h[i] = -1;
idx = 0;
for(int i = 2;i<=n;i++){
int fa = scan.nextInt();
add(fa,i);
}
for(int i = 1;i<=n;i++) {
L[i] = scan.nextInt();
R[i] = scan.nextInt();
}
dfs(1);
System.out.println(dp[1]);
}
public static void main(String[] args) {
int T = scan.nextInt();
while (T-- > 0) {
solve();
}
}
}
class AReader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
938a0bc3bb6ecce5d1708613b6a030bd
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class FakePlasticTrees {
static int MAXN = 1123456;
static boolean[] prime = new boolean[MAXN];
static boolean[] used = new boolean[MAXN];
public static void seive() {
for (int i = 2; i < MAXN; ++i) if (!used[i]){
prime[i] = true;
for (int j = i; j < MAXN; j += i) {
used[j] = true;
}
}
prime[1] = false;
}
// pair
// class Pair implements Comparable<Pair>{
// int ind,val;
// Pair(int i,int v){ ind=i;val=v;}
// @Override
// public int compareTo(Pair o) {return o.val-val ;}
// }
static ArrayList<ArrayList<Integer>> al = new ArrayList<>();
static long ans = 0;
static long[] left;
static long[] right;
public static void main (String[] args ) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String[] st = br.readLine().split(" ");
int n = Integer.parseInt(st[0]);
for(int i = 0; i <= n; i++) al.add(new ArrayList<>());
String[] str = br.readLine().split(" ");
int p[] = new int[n-1];
for(int i = 0; i < n-1; i++) {
p[i] = Integer.parseInt(str[i]);
}
for(int i = 0; i < n-1; i++) {
al.get(p[i]).add(i+2);
}
left = new long[n+1];
right = new long[n+1];
for(int i = 1; i <= n; i++) {
String[] s = br.readLine().split(" ");
left[i] = Integer.parseInt(s[0]);
right[i] = Integer.parseInt(s[1]);
}
dfs(1);
System.out.println(ans);
for(int i = 0; i <= n; i++) {
al.get(i).clear();
}
ans = 0;
}
}
static long dfs(int node) {
long sub = 0;
for(int child: al.get(node)) sub += dfs(child);
if(sub < left[node]) {
ans++;
return right[node];
}
return Math.min(sub, right[node]);
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
57e59b5fd16f727f909f36d5f641d4c5
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
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.StringTokenizer;
public class Solution {
static class FastReader {
private final BufferedReader br;
private StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
public long nextLong() { return Long.parseLong(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public String nextLine() {
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
int[] p,l,r;
int n;
Solution() {
n = sc.nextInt();
p = new int[n];l = new int[n];r = new int[n];
for (int i = 1;i < n;i++) {
p[i] = sc.nextInt();
p[i]--;
}
for (int i = 0;i < n;i++) {
l[i] = sc.nextInt();
r[i] = sc.nextInt();
}
}
ArrayList<Integer>[] G;
int[] dp;
int ans = 0;
void dfs(int u,int pa) {
int val = r[u];
long sum = 0;
for (int v : G[u]) if (v != pa) {
dfs(v,u);
sum += dp[v];
}
if (sum < l[u]) {
ans += 1;
dp[u] = r[u];
} else {
dp[u] = (int) Math.min(r[u],sum);
}
}
void solve() {
G = new ArrayList[n];
dp = new int[n];
for (int i = 0;i < n;i++) {
G[i] = new ArrayList<>();
}
for (int i = 1;i < n;i++) {
G[p[i]].add(i);
}
dfs(0,0);
System.out.println(ans);
}
static FastReader sc = new FastReader();
public static void main(String[] args) {
int t = sc.nextInt();
for (int i = 0;i < t;i++) {
new Solution().solve();
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
a90894329497beb886101231259e937e
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer>[] adj;
static int[] left;
static int[] right;
static int answer;
public static void main(String[] args) throws IOException {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while(t-- > 0) {
int n = in.nextInt();
adj = new ArrayList[n + 1];
for(int i = 0; i <= n; i++) {
adj[i] = new ArrayList<Integer>();
}
for(int i = 2; i <= n; i++) {
adj[in.nextInt()].add(i);
}
left = new int[n + 1];
right = new int[n + 1];
for(int i = 1; i <= n; i++) {
left[i] = in.nextInt();
right[i] = in.nextInt();
}
answer = 0;
DFS(1);
out.println(answer);
}
in.close();
out.close();
}
static long DFS(int v) {
long sum = 0;
for(int u : adj[v]) {
sum += DFS(u);
}
if(sum < left[v]) {
answer++;
return right[v];
}
return Math.min(right[v], sum);
}
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];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
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
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
7545d008d9e42657dbcf274886aca88a
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.lang.Math;
import java.util.*;
import java.util.regex.Pattern;
import javax.swing.text.DefaultStyledDocument.ElementSpec;
public final class Solution {
private static class FastScanner {
private final int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
private FastScanner(boolean usingFile) throws IOException {
if (usingFile) din =
new DataInputStream(new FileInputStream("path")); else din =
new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private short nextShort() throws IOException {
short ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do ret = (short) (ret * 10 + c - '0'); while (
(c = read()) >= '0' && c <= '9'
);
if (neg) return (short) -ret;
return ret;
}
private 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;
}
private char nextChar() throws IOException {
byte c = read();
while (c <= ' ') c = read();
return (char) c;
}
private String nextString() throws IOException {
StringBuilder ret = new StringBuilder();
byte c = read();
while (c <= ' ') c = read();
do {
ret.append((char) c);
} while ((c = read()) > ' ');
return ret.toString();
}
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++];
}
}
static StringTokenizer st;
static BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
static BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(System.out)
);
static int mod = 1000000007;
static String is(int no) {
return Integer.toString(no);
}
static String ls(long no) {
return Long.toString(no);
}
static int pi(String s) {
return Integer.parseInt(s);
}
static long pl(String s) {
return Long.parseLong(s);
}
/*write your constructor and global variables here*/
static class Rec<f, s, t> {
f a;
s b;
t c;
Rec(f a, s b, t c) {
this.a = a;
this.b = b;
this.c = c;
}
}
static class Quad<f, s, t, fo> {
f a;
s b;
t c;
fo d;
Quad(f a, s b, t c, fo d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
static class Pair<f, s> {
f a;
s b;
Pair(f a, s b) {
this.a = a;
this.b = b;
}
}
static int findPow(int a, int b, int mod) {
int res = 1;
while (b > 0) {
if ((b & 1) != 0) {
res = modMul.mod(res, a, mod);
}
a = modMul.mod(a, a, mod);
b = b / 2;
}
return res;
}
interface modOperations {
int mod(int a, int b, int mod);
}
static modOperations modAdd = (int a, int b, int mod) -> {
return (a % mod + b % mod) % mod;
};
static modOperations modSub = (int a, int b, int mod) -> {
return ((a % mod - b % mod + mod) % mod);
};
static modOperations modMul = (int a, int b, int mod) -> {
return (int) ((1l * a % mod * b % mod)) % mod;
};
static modOperations modDiv = (int a, int b, int mod) -> {
return modMul.mod(a, findPow(b, mod - 2, mod), mod);
};
static int gcd(int a, int b) {
int div = b;
int rem = a % b;
while (rem != 0) {
int temp = rem;
rem = div % rem;
div = temp;
}
return div;
}
static HashSet<Integer> primeList(int MAXI) {
int[] prime = new int[MAXI + 1];
HashSet<Integer> list = new HashSet<>();
for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) {
if (prime[i] == 0) {
list.add(i);
for (int j = i * i; j <= MAXI; j += i) {
prime[j] = 1;
}
}
}
for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) {
if (prime[i] == 0) {
list.add(i);
}
}
return list;
}
static int[] factorialList(int MAXI, int mod) {
int[] factorial = new int[MAXI + 1];
factorial[0] = 1;
for (int i = 1; i < MAXI + 1; i++) {
factorial[i] = modMul.mod(factorial[i - 1], i, mod);
}
return factorial;
}
static void put(HashMap<Integer, Integer> cnt, int key) {
if (cnt.containsKey(key)) {
cnt.replace(key, cnt.get(key) + 1);
} else {
cnt.put(key, 1);
}
}
static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getKey());
}
return vals;
}
static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) {
ArrayList<Integer> vals = new ArrayList<>();
for (Map.Entry<Integer, Integer> map : maps.entrySet()) {
vals.add(map.getValue());
}
return vals;
}
static int getMax(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) > max) {
max = arr.get(i);
}
}
return max;
}
static int getMin(ArrayList<Integer> arr) {
int max = arr.get(0);
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) < max) {
max = arr.get(i);
}
}
return max;
}
static int[][] fill_arr(int m, int n, int fill) {
int arr[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = fill;
}
}
return arr;
}
static class sortCond implements Comparator<Pair<Integer, Long>> {
@Override
public int compare(Pair<Integer, Long> p1, Pair<Integer, Long> p2) {
if (p1.b >= p2.b) {
return 1;
} else {
return -1;
}
}
}
static class sortCondRec
implements Comparator<Rec<Integer, Integer, Integer>> {
@Override
public int compare(
Rec<Integer, Integer, Integer> p1,
Rec<Integer, Integer, Integer> p2
) {
return p1.b - p2.b;
}
}
/*write your methods and classes here*/
static int cnt = 0;
static long dfs(
ArrayList<ArrayList<Integer>> tree,
ArrayList<Pair<Integer, Integer>> rec,
int root
) {
long tot = 0l;
for (int i = 0; i < tree.get(root).size(); i++) {
tot += dfs(tree, rec, tree.get(root).get(i));
}
if (tot < rec.get(root).a) {
cnt++;
return rec.get(root).b;
} else {
return Math.min(tot, rec.get(root).b);
}
}
public static void main(String[] args) throws IOException {
FastScanner ip = new FastScanner(false);
PrintWriter out = new PrintWriter(System.out);
int cases = ip.nextInt(), n, i;
while (cases-- != 0) {
n = ip.nextInt();
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
for (i = 0; i < n; i++) {
arr.add(new ArrayList<>());
}
for (i = 2; i <= n; i++) {
int par = ip.nextInt();
arr.get(par - 1).add(i - 1);
}
ArrayList<Pair<Integer, Integer>> pr = new ArrayList<>();
for (i = 0; i < n; i++) {
pr.add(new Pair<>(ip.nextInt(), ip.nextInt()));
}
cnt = 0;
dfs(arr, pr, 0);
out.println(cnt);
}
out.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
f381381c0f8c3ec3061eec956abca393
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
//package kg.my_algorithms.Codeforces;
//import static kg.my_algorithms.Mathematics.*;
import java.io.*;
import java.util.*;
public class Solution {
private static long moves = 0;
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int test_cases = fr.nextInt();
for(int test=1;test<=test_cases;test++){
int n = fr.nextInt();
moves = 0;
List<List<Integer>> tree = new ArrayList<>();
for(int i=0;i<n;i++) tree.add(new ArrayList<>());
for(int i=1;i<n;i++){
tree.get(fr.nextInt()-1).add(i);
}
int[][] range = new int[n][2];
for(int i=0;i<n;i++) {
range[i][0] = fr.nextInt();
range[i][1] = fr.nextInt();
}
// System.out.println(tree);
fun(0,range,tree);
output.write(moves+"\n");
}
output.flush();
}
private static long fun(int node, int[][] range, List<List<Integer>> tree){
long sum = 0L;
for(int c: tree.get(node)) sum += fun(c,range,tree);
if(range[node][0] <= sum && sum <= range[node][1]) return sum;
else if(sum > range[node][1]) return range[node][1];
moves++;
return range[node][1];
}
}
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
8492aaf757784bd395bfaabd2f46badb
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
//package kg.my_algorithms.Codeforces;
//import static kg.my_algorithms.Mathematics.*;
import java.io.*;
import java.util.*;
public class Solution {
private static long moves = 0;
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int test_cases = fr.nextInt();
for(int test=1;test<=test_cases;test++){
int n = fr.nextInt();
moves = 0;
List<List<Integer>> tree = new ArrayList<>();
for(int i=0;i<n;i++) tree.add(new ArrayList<>());
for(int i=1;i<n;i++){
tree.get(fr.nextInt()-1).add(i);
}
long[][] range = new long[n][2];
for(int i=0;i<n;i++) {
range[i][0] = fr.nextLong();
range[i][1] = fr.nextLong();
}
// System.out.println(tree);
fun(0,range,tree);
output.write(moves+"\n");
}
output.flush();
}
private static long fun(int node, long[][] range, List<List<Integer>> tree){
long sum = 0L;
for(int c: tree.get(node)) sum += fun(c,range,tree);
if(range[node][0] <= sum && sum <= range[node][1]) return sum;
else if(sum > range[node][1]) return range[node][1];
moves++;
return range[node][1];
}
}
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
c2e74b66679a4290efde9d32bea5682b
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.StringTokenizer;
public class D {
{
MULTI_TEST = true;
FILE_NAME = "";
NEED_FILE_IO = false;
INF = (long) 1e18;
} // fields
static class Vertex {
int to;
long left, right;
public Vertex(int to, int left, int right) {
this.to = to;
this.left = left;
this.right = right;
}
}
long[] dp;
ArrayList<Vertex>[] g;
Vertex[] vert;
boolean[] used;
long answer = 0;
long dfs(int v) {
used[v] = true;
long sum = 0;
for(var to : g[v]) {
if(!used[to.to])
sum += dfs(to.to);
}
if(sum < vert[v].left) {
answer++;
return vert[v].right;
} else {
return Math.min(vert[v].right, sum);
}
}
void solve() {
int n = ri();
g = new ArrayList[n];
for(int i = 0; i < n; i++) g[i] = new ArrayList<>();
dp = new long[n];
int[] p = new int[n];
p[0] = -1;
for(int i = 1; i < n; i++) p[i] = ri() - 1;
vert = new Vertex[n];
for(int i = 0; i < n; i++) {
vert[i] = new Vertex(i, ri(), ri());
}
for(int i = 1; i < n; i++) {
int v = i;
int u = p[i];
g[v].add(vert[u]);
g[u].add(vert[v]);
}
used = new boolean[n];
dfs(0);
out.println(answer);
answer = 0;
}
public static void main(String[] args) {
new D().run();
} //main
@SuppressWarnings("unused")
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
@SuppressWarnings("unused")
long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
@SuppressWarnings("unused")
int gcd(int a, int b) {
return (int) gcd((long) a, b);
}
@SuppressWarnings("unused")
int lcm(int a, int b) {
return (int) lcm(a, (long) b);
}
@SuppressWarnings("unused")
int sqrtInt(int x) {
return (int) sqrtLong(x);
}
@SuppressWarnings("unused")
long sqrtLong(long x) {
long root = (long) Math.sqrt(x);
while (root * root > x) --root;
while ((root + 1) * (root + 1) <= x) ++root;
return root;
}
@SuppressWarnings("unused")
int cbrtLong(long x) {
int cbrt = (int) Math.cbrt(x);
while ((long) cbrt * cbrt >= x) {
cbrt--;
}
while ((long) (cbrt + 1) * (cbrt + 1) <= x) cbrt++;
return cbrt;
}
@SuppressWarnings("unused")
long binpow(long a, long power) {
return binpow(a, power, Long.MAX_VALUE);
}
@SuppressWarnings("unused")
long binpow(long a, long power, long modulo) {
if (power == 0) return 1 % modulo;
if (power % 2 == 1) {
long b = binpow(a, power - 1, modulo) % modulo;
return ((a % modulo) * b) % modulo;
} else {
long b = binpow(a, power / 2, modulo) % modulo;
return (b * b) % modulo;
}
}
@SuppressWarnings("unused")
long fastMod(String s1, long n2) {
long num = 0;
for (int i = 0; i < s1.length() - 1; i++) {
num += Integer.parseInt(String.valueOf(s1.charAt(i)));
num *= 10;
if (num >= n2) {
num = num % n2;
}
}
return (num + Integer.parseInt(String.valueOf(s1.charAt(s1.length() - 1)))) % n2;
}
@SuppressWarnings("unused")
long factorialMod(long n, long p) {
long res = 1;
while (n > 1) {
res = (res * ((n / p) % 2 == 1 ? p - 1 : 1)) % p;
for (int i = 2; i <= n % p; ++i)
res = (res * i) % p;
n /= p;
}
return res % p;
}
@SuppressWarnings("unused")
boolean isPrime(int number) {
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return number > 1;
}
@SuppressWarnings("unused")
boolean[] primes(int border) {
boolean[] isPrimes = new boolean[border + 1];
Arrays.fill(isPrimes, true);
isPrimes[0] = false;
isPrimes[1] = false;
for (int i = 2; i < border + 1; i++) {
if (!isPrimes[i]) continue;
for (int k = i * 2; k < border; k += i) {
isPrimes[k] = false;
}
}
return isPrimes;
} //Number theory
@SuppressWarnings("unused")
void sort(int[] a) {
int n = a.length;
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++) {
arr[i] = a[i];
}
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
a[i] = arr[i];
}
}
@SuppressWarnings("unused")
void sort(long[] a) {
int n = a.length;
Long[] arr = new Long[n];
for (int i = 0; i < n; i++) {
arr[i] = a[i];
}
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
a[i] = arr[i];
}
}
@SuppressWarnings("unused")
int max(int... a) {
int n = a.length;
int max = Integer.MIN_VALUE;
for (int j : a) {
if (j > max) max = j;
}
return max;
}
@SuppressWarnings("unused")
long max(long... a) {
int n = a.length;
long max = Long.MIN_VALUE;
for (long l : a) {
if (l > max) max = l;
}
return max;
}
@SuppressWarnings("unused")
int maxIndex(int... a) {
int n = a.length;
int max = Integer.MIN_VALUE;
int index = 0;
for (int i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
index = i;
}
}
return index;
}
@SuppressWarnings("unused")
int maxIndex(long... a) {
int n = a.length;
long max = Long.MIN_VALUE;
int index = 0;
for (int i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
index = i;
}
}
return index;
}
@SuppressWarnings("unused")
int min(int... a) {
int n = a.length;
int min = Integer.MAX_VALUE;
for (int j : a) {
if (j < min) min = j;
}
return min;
}
@SuppressWarnings("unused")
int minIndex(int... a) {
int n = a.length;
int min = Integer.MAX_VALUE;
int index = 0;
for (int i = 0; i < n; i++) {
if (a[i] < min) {
min = a[i];
index = i;
}
}
return index;
}
@SuppressWarnings("unused")
int minIndex(long... a) {
int n = a.length;
long min = Long.MAX_VALUE;
int index = 0;
for (int i = 0; i < n; i++) {
if (a[i] < min) {
min = a[i];
index = i;
}
}
return index;
}
@SuppressWarnings("unused")
long min(long... a) {
int n = a.length;
long min = Long.MAX_VALUE;
for (long l : a) {
if (l < min) min = l;
}
return min;
}
@SuppressWarnings("unused")
long sum(int... a) {
int n = a.length;
long sum = 0;
for (int j : a) {
sum += j;
}
return sum;
}
@SuppressWarnings("unused")
long sum(long... a) {
int n = a.length;
long sum = 0;
for (long l : a) {
sum += l;
}
return sum;
} //Arrays Operations
@SuppressWarnings("unused")
String readLine() {
try {
return in.readLine();
} catch (Exception e) {
throw new InputMismatchException();
}
}
@SuppressWarnings("unused")
String rs() {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(readLine());
}
return tok.nextToken();
}
@SuppressWarnings("unused")
int ri() {
return Integer.parseInt(rs());
}
@SuppressWarnings("unused")
long rl() {
return Long.parseLong(rs());
}
@SuppressWarnings("unused")
double rd() {
return Double.parseDouble(rs());
}
@SuppressWarnings("unused")
int[] ria(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ri();
}
return a;
}
@SuppressWarnings("unused")
int[] riawd(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ri() - 1;
}
return a;
}
@SuppressWarnings("unused")
long[] rla(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = rl();
}
return a;
}
@SuppressWarnings("unused")
private boolean yesNo(boolean yes, String yesString, String noString) {
out.println(yes ? yesString : noString);
return yes;
} //fastIO
void run() {
try {
long start = System.currentTimeMillis();
initIO();
if (MULTI_TEST) {
long t = rl();
while (t-- > 0) {
solve();
}
} else {
solve();
}
out.close();
System.err.println("Time(ms) - " + (System.currentTimeMillis() - start));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
void initConsoleIO() {
out = new PrintWriter(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
}
void initFileIO(String inName, String outName) throws FileNotFoundException {
out = new PrintWriter(outName);
in = new BufferedReader(new FileReader(inName));
}
void initIO() throws FileNotFoundException {
if (!FILE_NAME.isEmpty()) {
initFileIO(FILE_NAME + ".in", FILE_NAME + ".out");
} else {
if (NEED_FILE_IO && new File("input.txt").exists()) {
initFileIO("input.txt", "output.txt");
} else {
initConsoleIO();
}
}
tok = new StringTokenizer("");
} //initIO
private final String FILE_NAME;
private final boolean MULTI_TEST;
private final boolean NEED_FILE_IO;
private final long INF;
BufferedReader in;
PrintWriter out;
StringTokenizer tok; //fields
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
364b5a1f77ff1a21c904b63385843bd2
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
long[] maxUp = new long[N + 1];
int moves = 0;
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new LinkedList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
95343c4a2a93ec174758560491bdd784
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
public class faketree {
public static long ans = 0;
public static int N = 2 * 100000 + 10;
public static List<List<Integer>> tree;
public static int[] l = new int[N], r = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
tree = new ArrayList<List<Integer>>();
for (int i = 0; i <= n; i++) {
tree.add(new ArrayList<Integer>());
}
for (int i = 2; i <= n; i++) {
int p = sc.nextInt();
tree.get(p).add(i);
}
for (int i = 1; i <= n; i++) {
l[i] = sc.nextInt();
r[i] = sc.nextInt();
}
ans = 0;
dfs(1);
System.out.println(ans);
for (int i = 1; i <= n; i++) {
tree.get(i).clear();
}
}
}
public static long dfs(int node) {
long s = 0;
for (int child : tree.get(node)) {
s += dfs(child);
}
if (s < l[node]) {
ans += 1;
return r[node];
}
return Math.min(r[node], s);
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
dabb4c7f4ff4b525c8525653f2308794
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
getOrDefault
valueOf
toCharArray()
System.out.println();
*/
public class Solution{
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int T=Integer.parseInt(st.nextToken());
//char[] arr=st.nextToken().toCharArray();
for(int z=0;z<T;z++){
st = new StringTokenizer(infile.readLine());
int V=Integer.parseInt(st.nextToken());
Map<Integer,List<Integer>> map=new HashMap<>();
for(int i=1;i<=V;i++) map.put(i,new ArrayList<>());
st = new StringTokenizer(infile.readLine());
for(int i=2;i<=V;i++){
int cur=Integer.parseInt(st.nextToken());
map.get(cur).add(i);
}
List<int[]> range=new ArrayList<>();
range.add(new int[]{-1,-1});
for(int i=0;i<V;i++){
st = new StringTokenizer(infile.readLine());
int l=Integer.parseInt(st.nextToken());
int r=Integer.parseInt(st.nextToken());
range.add(new int[]{l,r});
}
System.out.println(dfs(1,map,range)[0]);
//System.out.println("Case #"+(z+1)+": "+res);
}
}
public static long[] dfs(int cur,Map<Integer,List<Integer>> map,List<int[]> range){
if(map.get(cur).size()==0){
return new long[]{1,range.get(cur)[1]};
}
long cnt=0;
long sum=0;
for(int next:map.get(cur)){
long[] n=dfs(next,map,range);
cnt+=n[0];
sum+=n[1];
}
if(sum>=range.get(cur)[0]) return new long[]{cnt,Math.min(sum,range.get(cur)[1])};
else return new long[]{cnt+1,range.get(cur)[1]};
}
public static void build(long[] arr, StringTokenizer st, int lo){
for(int i=lo;i<arr.length;i++) arr[i]=Long.parseLong(st.nextToken());
}
public static void build(int[] arr, StringTokenizer st, int lo){
for(int i=lo;i<arr.length;i++) arr[i]=Integer.parseInt(st.nextToken());
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
b453e1882c9a80d723843d32978a90df
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
public class FakeTree {
public static long ans = 0;
public static int N = 2 * 100000 + 10;
public static List<List<Integer>> tree;
public static int[] l = new int[N], r = new int[N];
public static long dfs(int node) {
long s = 0;
for (int child: tree.get(node)) {
s += dfs(child);
}
if (s < l[node]) {
ans += 1;
return r[node];
}
return Math.min(r[node], s);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
tree = new ArrayList<List<Integer>>();
for (int i = 0; i <=n;i++) {
tree.add(new ArrayList<Integer>());
}
for (int i = 2; i <= n; i++) {
int p = sc.nextInt();
tree.get(p).add(i);
}
for (int i = 1; i <= n; i++) {
l[i] = sc.nextInt();
r[i] = sc.nextInt();
}
ans = 0;
dfs(1);
System.out.println(ans);
for (int i = 1; i <= n; i++) {
tree.get(i).clear();
}
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
8d630eb05f58bcf73fd69b032156cba2
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
void pre() throws Exception{}
void solve(int TC) throws Exception {
int N = ni();
int[] from = new int[N-1], to = new int[N-1];
for(int i = 0; i< N-1; i++){
from[i] = ni()-1;
to[i] = i+1;
}
int[][] tree = make(N, N-1, from, to, false);
int[][] rng = new int[N][];
for(int i = 0; i< N; i++)rng[i] = new int[]{ni(), ni()};
long[] val = new long[N];
pn(dfs(tree, rng, val, 0));
}
int dfs(int[][] tree, int[][] rng, long[] val, int u){
int ans = 0;
long sum = 0;
for(int v:tree[u]){
ans += dfs(tree, rng, val, v);
sum += val[v];
}
sum = Math.min(sum, rng[u][1]);
if(sum < rng[u][0]){
ans++;
sum = rng[u][1];
}
val[u] = sum;
return ans;
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
void exit(boolean b){if(!b)System.exit(0);}
final long IINF = Long.MAX_VALUE/2;
final int INF = Integer.MAX_VALUE/2;
DecimalFormat df = new DecimalFormat("0.000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-9;
static boolean multipleTC = true, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = multipleTC? ni():1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println("Runtime: " + (System.currentTimeMillis() - ct));
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 26).start();
else new Main().run();
}
int[][] make(int n, int e, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int[][] make(int n, int[] par, boolean f){
int[][] g = new int[n][];
int[] cnt = new int[n];
for(int x:par)cnt[x]++;
if(f)for(int i = 1; i< n; i++)cnt[i]++;
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 1; i< n-1; i++){
g[par[i]][--cnt[par[i]]] = i;
if(f)g[i][--cnt[i]] = par[i];
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int brute = 0;while(s>0){s/=10;brute++;}return brute;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object... o){for(Object oo:o)out.print(oo+" ");}
void pn(Object... o){
if(o.length == 0)out.println("");
for(int i = 0; i< o.length; i++){
out.print(o[i]);
out.print((i+1 == o.length?"\n":" "));
}
}
void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 11
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
3352bb8912dc13aa6fb348a5e63236ba
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class R800D1B {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream input;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
input = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) {
try {
input = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
} catch (IOException e) { e.printStackTrace(); }
}
public String readLine() {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() {
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(){
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() {
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;
}
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;
}
private void fillBuffer() {
try {
bytesRead = input.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
} catch(IOException e) { e.printStackTrace(); }
}
private byte read() {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() {
try {
if (input == null)
return;
input.close();
} catch(IOException e) { e.printStackTrace(); }
}
}
static class FastWriter {
BufferedWriter output;
public FastWriter() {
output = new BufferedWriter(
new OutputStreamWriter(System.out));
}
void write(String s) {
try {
output.write(s);
} catch (IOException e) { e.printStackTrace(); }
}
void endLine() {
try {
output.write("\n");
output.flush();
} catch (IOException e) { e.printStackTrace(); }
}
void writeInt(int x) {
write(Integer.toString(x));
endLine();
}
void writeLong(long x) {
write(Long.toString(x));
endLine();
}
void writeLine(String line) {
write(line);
endLine();
}
void writeIntArray(int[] a) {
write(Integer.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Integer.toString(a[i]));
}
endLine();
}
void writeLongArray(long[] a) {
write(Long.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Long.toString(a[i]));
}
endLine();
}
}
public static class Utility {
public static void safeSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void safeSort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
public static void shuffle(long[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
public static List<Integer>[] tree;
public static int[][] lr;
public static long[] max;
public static int c;
static long maxFlow(int i) {
max[i] = 0;
if(tree[i] == null) {
c ++;
return lr[i][1];
}
for(int j : tree[i])
max[i] += maxFlow(j);
if(max[i] < lr[i][0])
c++;
if(max[i] < lr[i][0] || max[i] > lr[i][1])
max[i] = lr[i][1];
return max[i];
}
public static void main(String[] args)
{
Reader r = new Reader();
FastWriter w = new FastWriter();
int cases = r.nextInt();
for(int test = 0; test < cases; test ++) {
//INPUT
int n = r.nextInt();
//int k = r.nextInt();
int[] a = r.nextIntArray(n-1);
lr = new int[n][2];
for(int i = 0; i < n; i ++) {
lr[i][0] = r.nextInt();
lr[i][1] = r.nextInt();
}
//CODE
tree = new LinkedList[n];
max = new long[n];
for(int i = 0; i < n-1; i ++) {
if(tree[a[i]-1] == null)
tree[a[i]-1] = new LinkedList<>();
tree[a[i] - 1].add(i + 1);
}
c = 0;
maxFlow(0);
//END CODE
//OUTPUT
w.writeInt(c);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 17
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
03cf3d95cb426761505f965088166760
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class R800D1B {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream input;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
input = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) {
try {
input = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
} catch (IOException e) { e.printStackTrace(); }
}
public String readLine() {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() {
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(){
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() {
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;
}
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;
}
private void fillBuffer() {
try {
bytesRead = input.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
} catch(IOException e) { e.printStackTrace(); }
}
private byte read() {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() {
try {
if (input == null)
return;
input.close();
} catch(IOException e) { e.printStackTrace(); }
}
}
static class FastWriter {
BufferedWriter output;
public FastWriter() {
output = new BufferedWriter(
new OutputStreamWriter(System.out));
}
void write(String s) {
try {
output.write(s);
} catch (IOException e) { e.printStackTrace(); }
}
void endLine() {
try {
output.write("\n");
output.flush();
} catch (IOException e) { e.printStackTrace(); }
}
void writeInt(int x) {
write(Integer.toString(x));
endLine();
}
void writeLong(long x) {
write(Long.toString(x));
endLine();
}
void writeLine(String line) {
write(line);
endLine();
}
void writeIntArray(int[] a) {
write(Integer.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Integer.toString(a[i]));
}
endLine();
}
void writeLongArray(long[] a) {
write(Long.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Long.toString(a[i]));
}
endLine();
}
}
public static class Utility {
public static void safeSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void safeSort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
public static void shuffle(long[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
public static List<Integer>[] tree;
public static int[][] lr;
public static long[] max;
public static int c;
static long maxFlow(int i) {
max[i] = 0;
if(tree[i] == null) {
c ++;
return lr[i][1];
}
for(int j : tree[i])
max[i] += maxFlow(j);
if(max[i] < lr[i][0])
c++;
if(max[i] < lr[i][0] || max[i] > lr[i][1])
max[i] = lr[i][1];
return max[i];
}
public static void main(String[] args)
{
Reader r = new Reader();
FastWriter w = new FastWriter();
int cases = r.nextInt();
for(int test = 0; test < cases; test ++) {
//INPUT
int n = r.nextInt();
//int k = r.nextInt();
int[] a = r.nextIntArray(n-1);
lr = new int[n][2];
for(int i = 0; i < n; i ++) {
lr[i][0] = r.nextInt();
lr[i][1] = r.nextInt();
}
//CODE
tree = new LinkedList[n];
max = new long[n];
for(int i = 0; i < n-1; i ++) {
if(tree[a[i]-1] == null)
tree[a[i]-1] = new LinkedList<>();
tree[a[i] - 1].add(i + 1);
}
c = 0;
maxFlow(0);
//END CODE
//OUTPUT
w.writeInt(c);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 17
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
40a3f66a38ffd8af7e858631255a4206
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class FakePlasticTrees {
private static final int START_TEST_CASE = 1;
public static void solveCase(FastIO io, int testCase) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 2; i <= N; ++i) {
final int P = io.nextInt();
nodes[P].next.add(nodes[i]);
}
final int[] L = new int[N + 1];
final int[] R = new int[N + 1];
for (int i = 1; i <= N; ++i) {
L[i] = io.nextInt();
R[i] = io.nextInt();
}
ArrayList<List<Node>> nodesByDepth = new ArrayList<>();
dfs(nodes[1], 0, nodesByDepth);
long[] maxUp = new long[N + 1];
int moves = 0;
for (int d = nodesByDepth.size() - 1; d >= 0; --d) {
for (Node u : nodesByDepth.get(d)) {
long childSum = 0;
for (Node v : u.next) {
childSum += maxUp[v.id];
}
if (childSum >= L[u.id]) {
maxUp[u.id] = Math.min(childSum, R[u.id]);
} else {
maxUp[u.id] = R[u.id];
++moves;
}
}
}
io.println(moves);
}
private static void dfs(Node u, int d, ArrayList<List<Node>> nodesByDepth) {
while (nodesByDepth.size() <= d) {
nodesByDepth.add(new LinkedList<>());
}
List<Node> lst = nodesByDepth.get(d);
lst.add(u);
for (Node v : u.next) {
dfs(v, d + 1, nodesByDepth);
}
}
private static class Node {
public int id;
public LinkedList<Node> next = new LinkedList<>();
public Node(int id) {
this.id = id;
}
}
public static void solve(FastIO io) {
final int T = io.nextInt();
for (int t = 0; t < T; ++t) {
solveCase(io, START_TEST_CASE + t);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 17
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
a82468be84e4d07069d9fb0f137d009f
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
/*
* Author Name: Raj Kumar
* IDE: IntelliJ IDEA Ultimate Edition
* JDK: 18 version
* Date: 07-Jul-22
*/
import java.io.*;
import java.util.*;
public class R800D1B {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream input;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
input = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) {
try {
input = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
} catch (IOException e) { e.printStackTrace(); }
}
public String readLine() {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() {
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(){
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() {
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;
}
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;
}
private void fillBuffer() {
try {
bytesRead = input.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
} catch(IOException e) { e.printStackTrace(); }
}
private byte read() {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() {
try {
if (input == null)
return;
input.close();
} catch(IOException e) { e.printStackTrace(); }
}
}
static class FastWriter {
BufferedWriter output;
public FastWriter() {
output = new BufferedWriter(
new OutputStreamWriter(System.out));
}
void write(String s) {
try {
output.write(s);
} catch (IOException e) { e.printStackTrace(); }
}
void endLine() {
try {
output.write("\n");
output.flush();
} catch (IOException e) { e.printStackTrace(); }
}
void writeInt(int x) {
write(Integer.toString(x));
endLine();
}
void writeLong(long x) {
write(Long.toString(x));
endLine();
}
void writeLine(String line) {
write(line);
endLine();
}
void writeIntArray(int[] a) {
write(Integer.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Integer.toString(a[i]));
}
endLine();
}
void writeLongArray(long[] a) {
write(Long.toString(a[0]));
for (int i = 1; i < a.length; i++) {
write(" "+Long.toString(a[i]));
}
endLine();
}
}
public static class Utility {
public static void safeSort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void safeSort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(int[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
public static void shuffle(long[] a) {
Random r = new Random();
for(int i = 0; i < a.length-2; i ++) {
int j = i + r.nextInt(a.length - i);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
public static List<Integer>[] tree;
public static int[][] lr;
public static long[] max;
public static int c;
static long maxFlow(int i) {
max[i] = 0;
if(tree[i] == null) {
c ++;
return lr[i][1];
}
for(int j : tree[i])
max[i] += maxFlow(j);
if(max[i] < lr[i][0])
c++;
if(max[i] < lr[i][0] || max[i] > lr[i][1])
max[i] = lr[i][1];
return max[i];
}
public static void main(String[] args)
{
Reader r = new Reader();
FastWriter w = new FastWriter();
int cases = r.nextInt();
for(int test = 0; test < cases; test ++) {
//INPUT
int n = r.nextInt();
//int k = r.nextInt();
int[] a = r.nextIntArray(n-1);
lr = new int[n][2];
for(int i = 0; i < n; i ++) {
lr[i][0] = r.nextInt();
lr[i][1] = r.nextInt();
}
//CODE
tree = new LinkedList[n];
max = new long[n];
for(int i = 0; i < n-1; i ++) {
if(tree[a[i]-1] == null)
tree[a[i]-1] = new LinkedList<>();
tree[a[i] - 1].add(i + 1);
}
c = 0;
maxFlow(0);
//END CODE
//OUTPUT
w.writeInt(c);
}
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 17
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
83b47c24d76545dd094290d26546c83a
|
train_109.jsonl
|
1655390100
|
We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following: Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?
|
256 megabytes
|
//package kg.my_algorithms.Codeforces;
//import static kg.my_algorithms.Mathematics.*;
import java.io.*;
import java.util.*;
public class Solution {
private static long moves = 0;
public static void main(String[] args) throws IOException {
FastReader fr = new FastReader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int test_cases = fr.nextInt();
for(int test=1;test<=test_cases;test++){
int n = fr.nextInt();
moves = 0;
List<List<Integer>> tree = new ArrayList<>();
for(int i=0;i<n;i++) tree.add(new ArrayList<>());
for(int i=1;i<n;i++){
tree.get(fr.nextInt()-1).add(i);
}
int[][] range = new int[n][2];
for(int i=0;i<n;i++) {
range[i][0] = fr.nextInt();
range[i][1] = fr.nextInt();
}
// System.out.println(tree);
fun(0,range,tree);
output.write(moves+"\n");
}
output.flush();
}
private static long fun(int node, int[][] range, List<List<Integer>> tree){
long sum = 0L;
for(int c: tree.get(node)) sum += fun(c,range,tree);
if(range[node][0] <= sum && sum <= range[node][1]) return sum;
else if(sum > range[node][1]) return range[node][1];
moves++;
return range[node][1];
}
}
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["4\n\n2\n\n1\n\n1 5\n\n2 9\n\n3\n\n1 1\n\n4 5\n\n2 4\n\n6 10\n\n4\n\n1 2 1\n\n6 9\n\n5 6\n\n4 5\n\n2 4\n\n5\n\n1 2 3 4\n\n5 5\n\n4 4\n\n3 3\n\n2 2\n\n1 1"]
|
1 second
|
["1\n2\n2\n5"]
|
NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.
|
Java 17
|
standard input
|
[
"dfs and similar",
"dp",
"greedy",
"trees"
] |
130fdf010c228564611a380b6dd37a34
|
The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$ — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.
| 1,700
|
For each test case output the minimum number of operations needed.
|
standard output
| |
PASSED
|
a88089f304622afa7f01605ce221a51b
|
train_109.jsonl
|
1655390100
|
Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int[] p = new int[n+1];
for(int i=1;i<=n;i++) {
p[i] = cin.nextInt();
}
int[][] dp = new int[n+1][2];
long ans = 0;
int last = n+1;
for(int i =n;i>0;i--) {
dp[i][0] = n+1;
dp[i][1] = 0;
for(int j = i+1;j<=n;j++) {
int dp0 =0,dp1=n+1;
if(dp[j-1][1]<p[j]) {
dp0 = Math.max(dp0,p[j-1]);
}
if(p[j-1]<p[j]) {
dp0 = Math.max(dp0,dp[j-1][0]);
}
if(p[j] < dp[j-1][0]) {
dp1 = Math.min(dp1,p[j-1]);
}
if(p[j-1]>p[j]) {
dp1 = Math.min(dp1,dp[j-1][1]);
}
if(dp0==dp[j][0] && dp1==dp[j][1]) {
break;
}
dp[j][0] = dp0;
dp[j][1] = dp1;
if(dp0==0&&dp1==n+1) {
last = j;
break;
}
}
ans = ans+ last-i;
}
System.out.println(ans);
}
}
|
Java
|
["3\n2 3 1", "6\n4 5 2 6 1 3", "10\n7 10 1 8 3 9 2 4 6 5"]
|
2 seconds
|
["6", "19", "39"]
|
NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
|
Java 8
|
standard input
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] |
669a34bfb07b82cfed8abccd8ab25f1e
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
| 2,800
|
Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
|
standard output
| |
PASSED
|
845c6d4ad576e3bc10fac497ba68e80f
|
train_109.jsonl
|
1655390100
|
Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner inp = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
inp.close();
}
private static void solve() {
int n = inp.nextInt();
int[] p = new int[n+1];
for(int i=1;i<=n;i++) {
p[i] = inp.nextInt();
}
int[][] dp = new int[n+1][2];
long ans = 0;
int last = n+1;
for(int i =n;i>0;i--) {
dp[i][0] = n+1;
dp[i][1] = 0;
for(int j = i+1;j<=n;j++) {
int dp0 =0,dp1=n+1;
if(dp[j-1][1]<p[j]) {
dp0 = Math.max(dp0,p[j-1]);
}
if(p[j-1]<p[j]) {
dp0 = Math.max(dp0,dp[j-1][0]);
}
if(p[j] < dp[j-1][0]) {
dp1 = Math.min(dp1,p[j-1]);
}
if(p[j-1]>p[j]) {
dp1 = Math.min(dp1,dp[j-1][1]);
}
if(dp0==dp[j][0] && dp1==dp[j][1]) {
break;
}
dp[j][0] = dp0;
dp[j][1] = dp1;
if(dp0==0&&dp1==n+1) {
last = j;
break;
}
}
ans = ans+ last-i;
}
System.out.println(ans);
}
}
|
Java
|
["3\n2 3 1", "6\n4 5 2 6 1 3", "10\n7 10 1 8 3 9 2 4 6 5"]
|
2 seconds
|
["6", "19", "39"]
|
NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
|
Java 8
|
standard input
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] |
669a34bfb07b82cfed8abccd8ab25f1e
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
| 2,800
|
Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
|
standard output
| |
PASSED
|
9d6ab9645a634a063a0f9a6058918104
|
train_109.jsonl
|
1655390100
|
Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner inp = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
inp.close();
}
private static void solve() {
int n = inp.nextInt();
int[] p = new int[n+1];
for(int i=1;i<=n;i++) {
p[i] = inp.nextInt();
}
int[][] dp = new int[n+1][2];
long ans = 0;
int last = n+1;
for(int i =n;i>0;i--) {
dp[i][0] = n+1;
dp[i][1] = 0;
for(int j = i+1;j<=n;j++) {
int dp0 =0,dp1=n+1;
if(dp[j-1][1]<p[j]) {
dp0 = Math.max(dp0,p[j-1]);
}
if(p[j-1]<p[j]) {
dp0 = Math.max(dp0,dp[j-1][0]);
}
if(p[j] < dp[j-1][0]) {
dp1 = Math.min(dp1,p[j-1]);
}
if(p[j-1]>p[j]) {
dp1 = Math.min(dp1,dp[j-1][1]);
}
if(dp0==dp[j][0] && dp1==dp[j][1]) {
break;
}
dp[j][0] = dp0;
dp[j][1] = dp1;
if(dp0==0&&dp1==n+1) {
last = j;
break;
}
}
ans = ans+ last-i;
}
System.out.println(ans);
}
}
|
Java
|
["3\n2 3 1", "6\n4 5 2 6 1 3", "10\n7 10 1 8 3 9 2 4 6 5"]
|
2 seconds
|
["6", "19", "39"]
|
NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
|
Java 8
|
standard input
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] |
669a34bfb07b82cfed8abccd8ab25f1e
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
| 2,800
|
Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
|
standard output
| |
PASSED
|
4bd0b3b4b382ef5d79d2165b98da91e3
|
train_109.jsonl
|
1655390100
|
Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner inp = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
inp.close();
}
private static void solve() {
int n = inp.nextInt();
int[] p = new int[n+1];
for(int i=1;i<=n;i++) {
p[i] = inp.nextInt();
}
int[][] dp = new int[n+1][2];
long ans = 0;
int last = n+1;
for(int i =n;i>0;i--) {
dp[i][0] = n+1;
dp[i][1] = 0;
for(int j = i+1;j<=n;j++) {
int dp0 =0,dp1=n+1;
if(dp[j-1][1]<p[j]) {
dp0 = Math.max(dp0,p[j-1]);
}
if(p[j-1]<p[j]) {
dp0 = Math.max(dp0,dp[j-1][0]);
}
if(p[j] < dp[j-1][0]) {
dp1 = Math.min(dp1,p[j-1]);
}
if(p[j-1]>p[j]) {
dp1 = Math.min(dp1,dp[j-1][1]);
}
if(dp0==dp[j][0] && dp1==dp[j][1]) {
break;
}
dp[j][0] = dp0;
dp[j][1] = dp1;
if(dp0==0&&dp1==n+1) {
last = j;
break;
}
}
ans = ans+ last-i;
}
System.out.println(ans);
}
}
|
Java
|
["3\n2 3 1", "6\n4 5 2 6 1 3", "10\n7 10 1 8 3 9 2 4 6 5"]
|
2 seconds
|
["6", "19", "39"]
|
NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
|
Java 8
|
standard input
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] |
669a34bfb07b82cfed8abccd8ab25f1e
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
| 2,800
|
Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
|
standard output
| |
PASSED
|
2c58ea5601a17db9601aab9023f8b15d
|
train_109.jsonl
|
1655390100
|
Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int[] p = new int[n+1];
for(int i=1;i<=n;i++) {
p[i] = cin.nextInt();
}
int[][] dp = new int[n+1][2];
long ans = 0;
int last = n+1;
for(int i =n;i>0;i--) {
dp[i][0] = n+1;
dp[i][1] = 0;
for(int j = i+1;j<=n;j++) {
int dp0 =0,dp1=n+1;
if(dp[j-1][1]<p[j]) {
dp0 = Math.max(dp0,p[j-1]);
}
if(p[j-1]<p[j]) {
dp0 = Math.max(dp0,dp[j-1][0]);
}
if(p[j] < dp[j-1][0]) {
dp1 = Math.min(dp1,p[j-1]);
}
if(p[j-1]>p[j]) {
dp1 = Math.min(dp1,dp[j-1][1]);
}
if(dp0==dp[j][0] && dp1==dp[j][1]) {
break;
}
dp[j][0] = dp0;
dp[j][1] = dp1;
if(dp0==0&&dp1==n+1) {
last = j;
break;
}
}
ans = ans+ last-i;
}
System.out.println(ans);
}
}
|
Java
|
["3\n2 3 1", "6\n4 5 2 6 1 3", "10\n7 10 1 8 3 9 2 4 6 5"]
|
2 seconds
|
["6", "19", "39"]
|
NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
|
Java 8
|
standard input
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] |
669a34bfb07b82cfed8abccd8ab25f1e
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
| 2,800
|
Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
|
standard output
| |
PASSED
|
c245c796db5d95b23f9c657a780faf79
|
train_109.jsonl
|
1655390100
|
Let's call an array $$$a$$$ of $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ Decinc if $$$a$$$ can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if $$$a = [3, 2, 4, 1, 5]$$$, we can remove the decreasing subsequence $$$[a_1, a_4]$$$ from $$$a$$$ and obtain $$$a = [2, 4, 5]$$$, which is increasing.You are given a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ with $$$1 \le l \le r \le n$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner inp = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
inp.close();
}
private static void solve() {
int n = inp.nextInt();
int[] p = new int[n+1];
for(int i=1;i<=n;i++) {
p[i] = inp.nextInt();
}
int[][] dp = new int[n+1][2];
long ans = 0;
int last = n+1;
for(int i =n;i>0;i--) {
dp[i][0] = n+1;
dp[i][1] = 0;
for(int j = i+1;j<=n;j++) {
int dp0 =0,dp1=n+1;
if(dp[j-1][1]<p[j]) {
dp0 = Math.max(dp0,p[j-1]);
}
if(p[j-1]<p[j]) {
dp0 = Math.max(dp0,dp[j-1][0]);
}
if(p[j] < dp[j-1][0]) {
dp1 = Math.min(dp1,p[j-1]);
}
if(p[j-1]>p[j]) {
dp1 = Math.min(dp1,dp[j-1][1]);
}
if(dp0==dp[j][0] && dp1==dp[j][1]) {
break;
}
dp[j][0] = dp0;
dp[j][1] = dp1;
if(dp0==0&&dp1==n+1) {
last = j;
break;
}
}
ans = ans+ last-i;
}
System.out.println(ans);
}
}
|
Java
|
["3\n2 3 1", "6\n4 5 2 6 1 3", "10\n7 10 1 8 3 9 2 4 6 5"]
|
2 seconds
|
["6", "19", "39"]
|
NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except $$$p[1 \ldots 6]$$$ and $$$p[2 \ldots 6]$$$ are Decinc.
|
Java 11
|
standard input
|
[
"brute force",
"data structures",
"divide and conquer",
"dp",
"greedy"
] |
669a34bfb07b82cfed8abccd8ab25f1e
|
The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct) — elements of the permutation.
| 2,800
|
Output the number of pairs of integers $$$(l, r)$$$ such that $$$p[l \ldots r]$$$ (the subarray of $$$p$$$ from $$$l$$$ to $$$r$$$) is a Decinc array. $$$(1 \le l \le r \le n)$$$
|
standard output
| |
PASSED
|
387dab107b13e3f167d2c03fe919c771
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class GayAf {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// BufferedReader in = new BufferedReader(new FileReader("Input.in"));
StringTokenizer st = new StringTokenizer(in.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
// keeps track of the cost it takes to block inefficient paths (weight should be
// k - i)
// intialized to k;
int[] block_cost = new int[n];
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < m; i++) {
st = new StringTokenizer(in.readLine());
int v = Integer.parseInt(st.nextToken()) - 1;
int u = Integer.parseInt(st.nextToken()) - 1;
if (!map.containsKey(u)) {
map.put(u, new ArrayList<>());
}
map.get(u).add(v);
block_cost[v]++;
}
System.out.println(dijkstra(map, block_cost, n, n - 1));
in.close();
}
static int dijkstra(Map<Integer, List<Integer>> map, int[] block_cost, int n, int source) {
boolean[] visited = new boolean[n];
int[] dist = new int[n];
dist[source] = 0;
PriorityQueue<node> pq = new PriorityQueue<node>((o1, o2) -> o1.d - o2.d);
pq.add(new node(0, source));
while (!pq.isEmpty()) {
node curr = pq.poll();
if (visited[curr.i]) {
continue;
}
visited[curr.i] = true;
dist[curr.i] = curr.d;
if(map.containsKey(curr.i)){
for (int neighbor : map.get(curr.i)) {
// dist[neighbor] = dist[curr.i] + block_cost[neighbor];
pq.add(new node(dist[curr.i] + block_cost[neighbor], neighbor));
block_cost[neighbor]--;
}
}
}
// return the minimum cost of visiting the first node
return dist[0];
}
static class node/* implements Comparable<node> */{
int d;
int i;
public node(int _d, int _i) {
d = _d;
i = _i;
}
// public int compareTo(node other) {
// return this.d - other.d;
// }
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
c3a4994671e76628be27d724cdbabd2a
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Better {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
03a759a31b35b903d3d37ffcea086bb5
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class AmShZ {
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m= Integer.parseInt(st.nextToken());
ArrayList<Integer>[] edges = new ArrayList[n];
for(int j=0; j<n; j++)edges[j] = new ArrayList<>();
int[] d = new int[n];
for(int j=0; j<m; j++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
edges[b].add(a);
d[a]++;
}
boolean[] visit = new boolean[n];
int[] dist = new int[n];
PriorityQueue<Integer> que = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer arg0, Integer arg1) {
// TODO Auto-generated method stub
return dist[arg0]-dist[arg1];
}
});
Arrays.fill(dist, 1000000000);
que.add(n-1);
dist[n-1]=0;
while(!que.isEmpty()) {
int num = que.poll();
if(visit[num])continue;
visit[num] = true;
for(int tar: edges[num]) {
if(dist[num]+d[tar]<dist[tar]) {
dist[tar]=dist[num]+d[tar];
que.add(tar);
}
d[tar]--;
}
}
out.write(dist[0]+"\n");
out.flush();
out.close();
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
4d46892be3bbe2ddceaeee7c7db3f766
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
ad8aa5a231379bf82a166e9741ed1051
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.util.Comparator.*;
public class Solution {
public static boolean useInFile = false;
public static boolean useOutFile = false;
public static void main(String args[]) throws IOException {
InOut inout = new InOut();
Resolver resolver = new Resolver(inout);
// long time = System.currentTimeMillis();
resolver.solve();
// resolver.print("\n" + (System.currentTimeMillis() - time));
inout.flush();
}
private static class Resolver {
final long LONG_INF = (long) 1e18;
final int INF = (int) (1e9 + 7);
final int MOD = 998244353;
long f[], inv[];
InOut inout;
Resolver(InOut inout) {
this.inout = inout;
}
void initF(int n, int mod) {
f = new long[n + 1];
f[1] = 1;
for (int i = 2; i <= n; i++) {
f[i] = (f[i - 1] * i) % mod;
}
}
void initInv(int n, int mod) {
inv = new long[n + 1];
inv[n] = pow(f[n], mod - 2, mod);
for (int i = inv.length - 2; i >= 0; i--) {
inv[i] = inv[i + 1] * (i + 1) % mod;
}
}
long cmn(int n, int m, int mod) {
return f[n] * inv[m] % mod * inv[n - m] % mod;
}
int d[] = {0, -1, 0, 1, 0};
boolean legal(int r, int c, int n, int m) {
return r >= 0 && r < n && c >= 0 && c < m;
}
int[] getBits(int n) {
int b[] = new int[31];
for (int i = 0; i < 31; i++) {
if ((n & (1 << i)) != 0) {
b[i] = 1;
}
}
return b;
}
private char ask1(int i) throws IOException {
format("? 1 %d\n", i);
flush();
return next(10).charAt(0);
}
void solve() throws IOException {
int tt = 1;
boolean hvt = false;
if (hvt) {
tt = nextInt();
// tt = Integer.parseInt(nextLine());
}
// initF(300001, MOD);
// initInv(300001, MOD);
// boolean pri[] = generatePrime(40000);
for (int cs = 1; cs <= tt; cs++) {
long rs = 0;
int n = nextInt();
int m = nextInt();
initGraph(n, m);
int cnt[] = new int[n + 1];
for (int i = 0; i < m; i++) {
int f = nextInt();
int t = nextInt();
adj[t].add(f);
cnt[f]++;
}
int dst[] = new int[n + 1];
Arrays.fill(dst, m);
dst[n] = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(comparingInt(o -> dst[o]));
boolean vis[] = new boolean[n + 1];
pq.offer(n);
while (pq.size() > 0) {
int x = pq.size();
for (int i = 0; i < x; i++) {
int y = pq.poll();
if (vis[y]) continue;
vis[y] = true;
List<Integer> es = adj[y];
for (int j = 0; j < es.size(); j++) {
int t = es.get(j);
if (dst[y] + cnt[t] < dst[t]) {
dst[t] = dst[y] + cnt[t];
}
cnt[t]--;
pq.offer(t);
}
}
}
rs = dst[1];
print("" + rs);
if (cs < tt) {
format("\n");
// format(" ");
}
// flush();
}
}
private void updateSegTree(int n, long l, SegmentTree lft) {
long lazy;
lazy = 1;
for (int j = 1; j <= l; j++) {
lazy = (lazy + cmn((int) l, j, INF)) % INF;
lft.modify(1, j, j, lazy);
}
lft.modify(1, (int) (l + 1), n, lazy);
}
String next() throws IOException {
return inout.next();
}
String next(int n) throws IOException {
return inout.next(n);
}
String nextLine() throws IOException {
return inout.nextLine();
}
int nextInt() throws IOException {
return inout.nextInt();
}
long nextLong(int n) throws IOException {
return inout.nextLong(n);
}
int[] anInt(int i, int j) throws IOException {
int a[] = new int[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextInt();
}
return a;
}
long[] anLong(int i, int j) throws IOException {
long a[] = new long[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextInt();
}
return a;
}
long[] anLong(int i, int j, int len) throws IOException {
long a[] = new long[j + 1];
for (int k = i; k <= j; k++) {
a[k] = nextLong(len);
}
return a;
}
void print(String s) {
inout.print(s, false);
}
void print(String s, boolean nextLine) {
inout.print(s, nextLine);
}
void format(String format, Object... obj) {
inout.format(format, obj);
}
void flush() {
inout.flush();
}
void swap(int a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
void swap(long a[], int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
int getP(int x, int p[]) {
if (p[x] == 0 || p[x] == x) {
return x;
}
return p[x] = getP(p[x], p);
}
void union(int x, int y, int p[]) {
if (x < y) {
p[y] = x;
} else {
p[x] = y;
}
}
boolean topSort() {
int n = adj2.length - 1;
int d[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 0; j < adj2[i].size(); j++) {
d[adj2[i].get(j)[0]]++;
}
}
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (d[i] == 0) {
list.add(i);
}
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < adj2[list.get(i)].size(); j++) {
int t = adj2[list.get(i)].get(j)[0];
d[t]--;
if (d[t] == 0) {
list.add(t);
}
}
}
return list.size() == n;
}
class SegmentTreeNode {
long defaultVal = 0;
int l, r;
long val = defaultVal, lazy = defaultVal;
SegmentTreeNode(int l, int r) {
this.l = l;
this.r = r;
}
}
class SegmentTree {
SegmentTreeNode tree[];
long inf = Long.MIN_VALUE;
// long c[];
SegmentTree(int n) {
assert n > 0;
tree = new SegmentTreeNode[n * 3 + 1];
}
void setAn(long cn[]) {
// c = cn;
}
SegmentTree build(int k, int l, int r) {
if (l > r) {
return this;
}
if (null == tree[k]) {
tree[k] = new SegmentTreeNode(l, r);
}
if (l == r) {
return this;
}
int mid = (l + r) >> 1;
build(k << 1, l, mid);
build(k << 1 | 1, mid + 1, r);
return this;
}
void pushDown(int k) {
if (tree[k].l == tree[k].r) {
return;
}
long lazy = tree[k].lazy;
// tree[k << 1].val = ((c[tree[k << 1].l] - c[tree[k << 1].r + 1] + MOD) % MOD * lazy) % MOD;
tree[k << 1].val = lazy;
tree[k << 1].lazy = lazy;
// tree[k << 1 | 1].val = ((c[tree[k << 1 | 1].l] - c[tree[k << 1 | 1].r + 1] + MOD) % MOD * lazy) % MOD;
tree[k << 1 | 1].val = lazy;
tree[k << 1 | 1].lazy = lazy;
tree[k].lazy = 0;
}
void modify(int k, int l, int r, long val) {
if (tree[k].l >= l && tree[k].r <= r) {
// tree[k].val = ((c[tree[k].l] - c[tree[k].r + 1] + MOD) % MOD * val) % MOD;
tree[k].val = val;
tree[k].lazy = val;
return;
}
int mid = (tree[k].l + tree[k].r) >> 1;
if (tree[k].lazy != 0) {
pushDown(k);
}
if (mid >= l) {
modify(k << 1, l, r, val);
}
if (mid + 1 <= r) {
modify(k << 1 | 1, l, r, val);
}
// tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
tree[k].val = Math.max(tree[k << 1].val, tree[k << 1 | 1].val);
}
long query(int k, int l, int r) {
if (tree[k].l > r || tree[k].r < l) {
return 0;
}
if (tree[k].lazy != 0) {
pushDown(k);
}
if (tree[k].l >= l && tree[k].r <= r) {
return tree[k].val;
}
long ans = (query(k << 1, l, r) + query(k << 1 | 1, l, r)) % MOD;
if (tree[k].l < tree[k].r) {
// tree[k].val = (tree[k << 1].val + tree[k << 1 | 1].val) % MOD;
tree[k].val = Math.max(tree[k << 1].val, tree[k << 1 | 1].val);
}
return ans;
}
}
class BitMap {
boolean[] vis = new boolean[32];
List<Integer> g[];
void init() {
for (int i = 0; i < 32; i++) {
g = new List[32];
g[i] = new ArrayList<>();
}
}
void dfs(int p) {
if (vis[p]) return;
vis[p] = true;
for (int it : g[p]) dfs(it);
}
boolean connected(int a[], int n) {
int m = 0;
for (int i = 0; i < n; i++) if (a[i] == 0) return false;
for (int i = 0; i < n; i++) m |= a[i];
for (int i = 0; i < 31; i++) g[i].clear();
for (int i = 0; i < n; i++) {
int last = -1;
for (int j = 0; j < 31; j++)
if ((a[i] & (1 << j)) > 0) {
if (last != -1) {
g[last].add(j);
g[j].add(last);
}
last = j;
}
}
Arrays.fill(vis, false);
for (int j = 0; j < 31; j++)
if (((1 << j) & m) > 0) {
dfs(j);
break;
}
for (int j = 0; j < 31; j++) if (((1 << j) & m) > 0 && !vis[j]) return false;
return true;
}
}
class BinaryIndexedTree {
int n = 1;
long C[];
BinaryIndexedTree(int sz) {
while (n <= sz) {
n <<= 1;
}
n = sz + 1;
C = new long[n];
}
int lowbit(int x) {
return x & -x;
}
void add(int x, long val) {
while (x < n) {
C[x] += val;
x += lowbit(x);
}
}
long getSum(int x) {
long res = 0;
while (x > 0) {
res += C[x];
x -= lowbit(x);
}
return res;
}
int binSearch(long sum) {
if (sum == 0) {
return 0;
}
int n = C.length;
int mx = 1;
while (mx < n) {
mx <<= 1;
}
int res = 0;
for (int i = mx / 2; i >= 1; i >>= 1) {
if (C[res + i] < sum) {
sum -= C[res + i];
res += i;
}
}
return res + 1;
}
}
static class TrieNode {
int cnt = 0;
TrieNode next[];
TrieNode() {
next = new TrieNode[2];
}
private void insert(TrieNode trie, int ch[], int i) {
while (i < ch.length) {
int idx = ch[i];
if (null == trie.next[idx]) {
trie.next[idx] = new TrieNode();
}
trie.cnt++;
trie = trie.next[idx];
i++;
}
}
private static int query(TrieNode trie) {
if (null == trie) {
return 0;
}
int ans[] = new int[2];
for (int i = 0; i < trie.next.length; i++) {
if (null == trie.next[i]) {
continue;
}
ans[i] = trie.next[i].cnt;
}
if (ans[0] == 0 && ans[0] == ans[1]) {
return 0;
}
if (ans[0] == 0) {
return query(trie.next[1]);
}
if (ans[1] == 0) {
return query(trie.next[0]);
}
return Math.min(ans[0] - 1 + query(trie.next[1]), ans[1] - 1 + query(trie.next[0]));
}
}
//Binary tree
class TreeNode {
int val;
int tier = -1;
TreeNode parent;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
//binary tree dfs
void tierTree(TreeNode root) {
if (null == root) {
return;
}
if (null != root.parent) {
root.tier = root.parent.tier + 1;
} else {
root.tier = 0;
}
tierTree(root.left);
tierTree(root.right);
}
//LCA start
TreeNode[][] lca;
TreeNode[] tree;
void lcaDfsTree(TreeNode root) {
if (null == root) {
return;
}
tree[root.val] = root;
TreeNode nxt = root.parent;
int idx = 0;
while (null != nxt) {
lca[root.val][idx] = nxt;
nxt = lca[nxt.val][idx];
idx++;
}
lcaDfsTree(root.left);
lcaDfsTree(root.right);
}
TreeNode lcaTree(TreeNode root, int n, TreeNode x, TreeNode y) throws IOException {
if (null == root) {
return null;
}
if (-1 == root.tier) {
tree = new TreeNode[n + 1];
tierTree(root);
}
if (null == lca) {
lca = new TreeNode[n + 1][31];
lcaDfsTree(root);
}
int z = Math.abs(x.tier - y.tier);
int xx = x.tier > y.tier ? x.val : y.val;
while (z > 0) {
final int zz = z;
int l = (int) BinSearch.bs(0, 31
, k -> zz < (1 << k));
xx = lca[xx][l].val;
z -= 1 << l;
}
int yy = y.val;
if (x.tier <= y.tier) {
yy = x.val;
}
while (xx != yy) {
final int xxx = xx;
final int yyy = yy;
int l = (int) BinSearch.bs(0, 31
, k -> (1 << k) <= tree[xxx].tier && lca[xxx][(int) k] != lca[yyy][(int) k]);
xx = lca[xx][l].val;
yy = lca[yy][l].val;
}
return tree[xx];
}
//LCA end
//graph
List<Integer> adj[];
List<int[]> adj2[];
void initGraph(int n, int m) throws IOException {
initGraph(n, m, false, false, 1, false);
}
void initGraph(int n, int m, boolean hasW, boolean directed, int type, boolean useInput) throws IOException {
if (type == 1) {
adj = new List[n + 1];
} else {
adj2 = new List[n + 1];
}
for (int i = 1; i <= n; i++) {
if (type == 1) {
adj[i] = new ArrayList<>();
} else {
adj2[i] = new ArrayList<>();
}
}
if (!useInput) return;
for (int i = 0; i < m; i++) {
int f = nextInt();
int t = nextInt();
if (type == 1) {
adj[f].add(t);
if (!directed) {
adj[t].add(f);
}
} else {
int w = hasW ? nextInt() : 0;
adj2[f].add(new int[]{t, w});
if (!directed) {
adj2[t].add(new int[]{f, w});
}
}
}
}
void getDiv(Map<Integer, Integer> map, long n) {
int sqrt = (int) Math.sqrt(n);
for (int i = 2; i <= sqrt; i++) {
int cnt = 0;
while (n % i == 0) {
cnt++;
n /= i;
}
if (cnt > 0) {
map.put(i, cnt);
}
}
if (n > 1) {
map.put((int) n, 1);
}
}
boolean[] generatePrime(int n) {
boolean p[] = new boolean[n + 1];
p[2] = true;
for (int i = 3; i <= n; i += 2) {
p[i] = true;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (!p[i]) {
continue;
}
for (int j = i * i; j <= n; j += i << 1) {
p[j] = false;
}
}
return p;
}
boolean isPrime(long n) { //determines if n is a prime number
int p[] = {2, 3, 5, 233, 331};
int pn = p.length;
long s = 0, t = n - 1;//n - 1 = 2^s * t
while ((t & 1) == 0) {
t >>= 1;
++s;
}
for (int i = 0; i < pn; ++i) {
if (n == p[i]) {
return true;
}
long pt = pow(p[i], t, n);
for (int j = 0; j < s; ++j) {
long cur = llMod(pt, pt, n);
if (cur == 1 && pt != 1 && pt != n - 1) {
return false;
}
pt = cur;
}
if (pt != 1) {
return false;
}
}
return true;
}
long[] llAdd2(long a[], long b[], long mod) {
long c[] = new long[2];
c[1] = (a[1] + b[1]) % (mod * mod);
c[0] = (a[1] + b[1]) / (mod * mod) + a[0] + b[0];
return c;
}
long[] llMod2(long a, long b, long mod) {
long x1 = a / mod;
long y1 = a % mod;
long x2 = b / mod;
long y2 = b % mod;
long c = (x1 * y2 + x2 * y1) / mod;
c += x1 * x2;
long d = (x1 * y2 + x2 * y1) % mod * mod + y1 * y2;
return new long[]{c, d};
}
long llMod(long a, long b, long mod) {
if (a > mod || b > mod) {
return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod;
}
return a * b % mod;
// long r = 0;
// a %= mod;
// b %= mod;
// while (b > 0) {
// if ((b & 1) == 1) {
// r = (r + a) % mod;
// }
// b >>= 1;
// a = (a << 1) % mod;
// }
// return r;
}
long pow(long a, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = ans * a;
}
a = a * a;
n >>= 1;
}
return ans;
}
long pow(long a, long n, long mod) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = llMod(ans, a, mod);
}
a = llMod(a, a, mod);
n >>= 1;
}
return ans;
}
private long[][] initC(int n) {
long c[][] = new long[n][n];
for (int i = 0; i < n; i++) {
c[i][0] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
return c;
}
/**
* ps: n >= m, choose m from n;
*/
// private int cmn(long n, long m) {
// if (m > n) {
// n ^= m;
// m ^= n;
// n ^= m;
// }
// m = Math.min(m, n - m);
//
// long top = 1;
// long bot = 1;
// for (long i = n - m + 1; i <= n; i++) {
// top = (top * i) % MOD;
// }
// for (int i = 1; i <= m; i++) {
// bot = (bot * i) % MOD;
// }
//
// return (int) ((top * pow(bot, MOD - 2, MOD)) % MOD);
// }
long[] exGcd(long a, long b) {
if (b == 0) {
return new long[]{a, 1, 0};
}
long[] ans = exGcd(b, a % b);
long x = ans[2];
long y = ans[1] - a / b * ans[2];
ans[1] = x;
ans[2] = y;
return ans;
}
long gcd(long a, long b) {
if (a < b) {
return gcd(b, a);
}
while (b != 0) {
long tmp = a % b;
a = b;
b = tmp;
}
return a;
}
int[] unique(int a[], Map<Integer, Integer> idx) {
int tmp[] = a.clone();
Arrays.sort(tmp);
int j = 0;
for (int i = 0; i < tmp.length; i++) {
if (i == 0 || tmp[i] > tmp[i - 1]) {
idx.put(tmp[i], j++);
}
}
int rs[] = new int[j];
j = 0;
for (int key : idx.keySet()) {
rs[j++] = key;
}
Arrays.sort(rs);
return rs;
}
boolean isEven(long n) {
return (n & 1) == 0;
}
static class BinSearch {
static long bs(long l, long r, IBinSearch sort) throws IOException {
while (l < r) {
long m = l + (r - l) / 2;
if (sort.binSearchCmp(m)) {
l = m + 1;
} else {
r = m;
}
}
return l;
}
interface IBinSearch {
boolean binSearchCmp(long k) throws IOException;
}
}
}
private static class InOut {
private BufferedReader br;
private StreamTokenizer st;
private PrintWriter pw;
InOut() throws FileNotFoundException {
if (useInFile) {
System.setIn(new FileInputStream("resources/inout/in.text"));
}
if (useOutFile) {
System.setOut(new PrintStream("resources/inout/out.text"));
}
br = new BufferedReader(new InputStreamReader(System.in));
st = new StreamTokenizer(br);
pw = new PrintWriter(new OutputStreamWriter(System.out));
st.ordinaryChar('\'');
st.ordinaryChar('\"');
st.ordinaryChar('/');
}
private boolean hasNext() throws IOException {
return st.nextToken() != StreamTokenizer.TT_EOF;
}
private String next() throws IOException {
if (st.nextToken() == StreamTokenizer.TT_EOF) {
throw new IOException();
}
return st.sval;
}
private String next(int n) throws IOException {
return next(n, false);
}
private String next(int len, boolean isDigit) throws IOException {
char ch[] = new char[len];
int cur = 0;
char c;
while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t'
|| (isDigit && (c < '0' || c > '9') && c != '-')) ;
do {
ch[cur++] = c;
} while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t')
&& (!isDigit || c >= '0' && c <= '9'));
return String.valueOf(ch, 0, cur);
}
private int nextInt() throws IOException {
if (st.nextToken() == StreamTokenizer.TT_EOF) {
throw new IOException();
}
return (int) st.nval;
}
private long nextLong(int n) throws IOException {
return Long.parseLong(next(n, true));
}
private double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
private String[] nextSS(String reg) throws IOException {
return br.readLine().split(reg);
}
private String nextLine() throws IOException {
return br.readLine();
}
private void print(String s, boolean newLine) {
if (null != s) {
pw.print(s);
}
if (newLine) {
pw.println();
}
}
private void format(String format, Object... obj) {
pw.format(format, obj);
}
private void flush() {
pw.flush();
}
}
private static class FFT {
double[] roots;
int maxN;
public FFT(int maxN) {
this.maxN = maxN;
initRoots();
}
public long[] multiply(int[] a, int[] b) {
int minSize = a.length + b.length - 1;
int bits = 1;
while (1 << bits < minSize) bits++;
int N = 1 << bits;
double[] aa = toComplex(a, N);
double[] bb = toComplex(b, N);
fftIterative(aa, false);
fftIterative(bb, false);
double[] c = new double[aa.length];
for (int i = 0; i < N; i++) {
c[2 * i] = aa[2 * i] * bb[2 * i] - aa[2 * i + 1] * bb[2 * i + 1];
c[2 * i + 1] = aa[2 * i] * bb[2 * i + 1] + aa[2 * i + 1] * bb[2 * i];
}
fftIterative(c, true);
long[] ret = new long[minSize];
for (int i = 0; i < ret.length; i++) {
ret[i] = Math.round(c[2 * i]);
}
return ret;
}
static double[] toComplex(int[] arr, int size) {
double[] ret = new double[size * 2];
for (int i = 0; i < arr.length; i++) {
ret[2 * i] = arr[i];
}
return ret;
}
void initRoots() {
roots = new double[2 * (maxN + 1)];
double ang = 2 * Math.PI / maxN;
for (int i = 0; i <= maxN; i++) {
roots[2 * i] = Math.cos(i * ang);
roots[2 * i + 1] = Math.sin(i * ang);
}
}
int bits(int N) {
int ret = 0;
while (1 << ret < N) ret++;
if (1 << ret != N) throw new RuntimeException();
return ret;
}
void fftIterative(double[] array, boolean inv) {
int bits = bits(array.length / 2);
int N = 1 << bits;
for (int from = 0; from < N; from++) {
int to = Integer.reverse(from) >>> (32 - bits);
if (from < to) {
double tmpR = array[2 * from];
double tmpI = array[2 * from + 1];
array[2 * from] = array[2 * to];
array[2 * from + 1] = array[2 * to + 1];
array[2 * to] = tmpR;
array[2 * to + 1] = tmpI;
}
}
for (int n = 2; n <= N; n *= 2) {
int delta = 2 * maxN / n;
for (int from = 0; from < N; from += n) {
int rootIdx = inv ? 2 * maxN : 0;
double tmpR, tmpI;
for (int arrIdx = 2 * from; arrIdx < 2 * from + n; arrIdx += 2) {
tmpR = array[arrIdx + n] * roots[rootIdx] - array[arrIdx + n + 1] * roots[rootIdx + 1];
tmpI = array[arrIdx + n] * roots[rootIdx + 1] + array[arrIdx + n + 1] * roots[rootIdx];
array[arrIdx + n] = array[arrIdx] - tmpR;
array[arrIdx + n + 1] = array[arrIdx + 1] - tmpI;
array[arrIdx] += tmpR;
array[arrIdx + 1] += tmpI;
rootIdx += (inv ? -delta : delta);
}
}
}
if (inv) {
for (int i = 0; i < array.length; i++) {
array[i] /= N;
}
}
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
8bb780a67fedf3f9c2836ff9613e7029
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
/*
I am dead inside
Do you like NCT, sKz, BTS?
5 4 3 2 1 Moonwalk
Imma knock it down like domino
Is this what you want? Is this what you want?
Let's ttalkbocky about that :()
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
public class x1693C
{
static final int INF = Integer.MAX_VALUE/3;
static int[][] edges;
static HashSet<Integer>[] transpose;
public static void main(String followthekkathyoninsta[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
int M = infile.nextInt();
edges = new int[N+1][];
transpose = new HashSet[N+1];
int[] freq = new int[N+1];
int[] input = new int[2*M];
for(int i=1; i < 2*M; i+=2)
{
int a = infile.nextInt();
int b = infile.nextInt();
freq[a]++;
input[i-1] = a;
input[i] = b;
}
for(int i=1; i <= N; i++)
{
edges[i] = new int[freq[i]];
transpose[i] = new HashSet<Integer>();
}
for(int i=1; i < 2*M; i+=2)
{
int a = input[i-1];
int b = input[i];
edges[a][--freq[a]] = b;
transpose[b].add(a);
}
HashMap<Integer, Integer>[] maps = new HashMap[N+1];
for(int i=1; i <= N; i++)
{
maps[i] = new HashMap<Integer, Integer>();
for(int next: edges[i])
{
if(!maps[i].containsKey(next))
maps[i].put(next, 1);
else
maps[i].put(next, maps[i].get(next)+1);
}
}
boolean[] seen = new boolean[N+1];
int[] dist = new int[N+1];
Arrays.fill(dist, INF);
PriorityQueue<Node> pq = new PriorityQueue<Node>();
pq.add(new Node(N, 0));
dist[N] = 0;
int[] disabled = new int[N+1];
while(pq.size() > 0)
{
Node curr = pq.poll();
if(seen[curr.id])
continue;
seen[curr.id] = true;
for(int next: transpose[curr.id])
{
int cost = curr.dist+1;
int f = maps[next].get(curr.id);
cost += edges[next].length-f-disabled[next];
if(dist[next] > cost)
{
dist[next] = cost;
pq.add(new Node(next, dist[next]));
}
disabled[next] += f;
}
}
System.out.println(dist[1]);
}
}
/*
6 6
1 2
1 3
2 4
3 4
4 6
5 6
6 7
1 2
1 3
2 4
3 4
3 5
4 6
5 6
*/
class Node implements Comparable<Node>
{
public int id;
public int dist;
public Node(int a, int d)
{
id = a;
dist = d;
}
public int compareTo(Node oth)
{
return dist-oth.dist;
}
}
class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
8d533a6ac9004a01d605d6f4ef5ae9b1
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
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();
}
long mod=1000000007;
long gcd(long a,long b) {
return a==0?b:gcd(b%a,a);
}
final long inf=Long.MAX_VALUE/3;
ArrayList<Integer>[] graph;
int[] degree;
void work(){
int n=ni(),m=ni();
int[] dis=new int[n];
int[] count=new int[n];
degree=new int[n];
Arrays.fill(dis,-1);
graph=ng(n,m);
PriorityQueue<int[]> pq=new PriorityQueue<>((a1,a2)->a1[1]-a2[1]);
pq.add(new int[]{n-1,0});
while(pq.size()>0){
int[] q = pq.poll();
int node=q[0],d=q[1];
if(dis[node]!=-1){
continue;
}
dis[node]=d;
for(int nn:graph[node]){
count[nn]++;
pq.add(new int[]{nn,degree[nn]-count[nn]+d+1});//degree[nn]-count[nn]去除其他更大距离的路
}
}
out.println(dis[0]);
}
@SuppressWarnings("unused")
private ArrayList<Integer>[] ng(int n, int m) {
ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
int s=in.nextInt()-1,e=in.nextInt()-1;
// graph[s].add(e);
degree[s]++;
graph[e].add(s);
}
return graph;
}
private ArrayList<long[]>[] ngw(int n, int m) {
ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n];
for(int i=0;i<n;i++) {
graph[i]=new ArrayList<>();
}
for(int i=1;i<=m;i++) {
long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong();
graph[(int)s].add(new long[] {e,w});
graph[(int)e].add(new long[] {s,w});
}
return graph;
}
private int ni() {
return in.nextInt();
}
private long nl() {
return in.nextLong();
}
private double nd() {
return in.nextDouble();
}
private String ns() {
return in.next();
}
private long[] na(int n) {
long[] A=new long[n];
for(int i=0;i<n;i++) {
A[i]=in.nextLong();
}
return A;
}
private int[] nia(int n) {
int[] A=new int[n];
for(int i=0;i<n;i++) {
A[i]=in.nextInt();
}
return A;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
InputStreamReader input;//no buffer
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(boolean isBuffer)
{
if(!isBuffer){
input=new InputStreamReader(System.in);
}else{
br=new BufferedReader(new InputStreamReader(System.in));
}
}
public boolean hasNext(){
try{
String s=br.readLine();
if(s==null){
return false;
}
st=new StringTokenizer(s);
}catch(IOException e){
e.printStackTrace();
}
return true;
}
public String next()
{
if(input!=null){
try {
StringBuilder sb=new StringBuilder();
int ch=input.read();
while(ch=='\n'||ch=='\r'||ch==32){
ch=input.read();
}
while(ch!='\n'&&ch!='\r'&&ch!=32){
sb.append((char)ch);
ch=input.read();
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
}
}
while(st==null || !st.hasMoreElements())//回车,空行情况
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return (int)nextLong();
}
public long nextLong() {
try {
if(input!=null){
long ret=0;
int b=input.read();
while(b<'0'||b>'9'){
b=input.read();
}
while(b>='0'&&b<='9'){
ret=ret*10+(b-'0');
b=input.read();
}
return ret;
}
}catch (Exception e){
e.printStackTrace();
}
return Long.parseLong(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
664e798db24bec4be7c9f7f39b19b2c0
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
9be3b99a425a88bcaaaea14f12c1ed81
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
5e24d9f9ee3f8d0f26e264cabd81366c
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
/* || श्री राम समर्थ ||
|| जय जय रघुवीर समर्थ ||
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.*;
import static java.util.Arrays.sort;
/*
Think until you get Good idea And then Code Easily
Try Hard And Pay Attention to details (be positive always possible)
think smart
*/
public class CodeforcesTemp {
public static void main(String[] args) throws IOException {
Reader scan= new Reader();
FastPrinter out = new FastPrinter();
// int tt =scan.nextInt();
int tt=1;
for (int tc = 1; tc <= tt; tc++){
int n=scan.nextInt();
int m=scan.nextInt();
List<Integer>[] g=new List[n];
List<Integer>[] rg=new List[n];
for (int i = 0; i <n ; i++) {
List<Integer> li1 = new ArrayList<>();
List<Integer> li2 = new ArrayList<>();
g[i] = li1;
rg[i] = li2;
}
for (int i = 0; i < m; i++) {
int u= scan.nextInt();
int v= scan.nextInt();
u--;
v--;
g[u].add(v);
rg[v].add(u);
}
int[] cnt=new int[n];
for (int i = 0; i < n; i++) {
cnt[i]=g[i].size();
}
PriorityQueue<Pair> pq=new PriorityQueue<>(new SortByDays());
pq.add(new Pair(n-1,0));
boolean[] vis=new boolean[n];
int[] days=new int[n];
Arrays.fill(days,Integer.MAX_VALUE);
days[n-1]=0;
while (pq.size()>0){
Pair p=pq.poll();
if(vis[p.node])continue;
vis[p.node]=true;
for (int i = 0; i < rg[p.node].size(); i++) {
int v=rg[p.node].get(i);
if(days[v]>days[p.node]+cnt[v]){
days[v]=days[p.node]+cnt[v];
}
pq.add(new Pair(v,days[v]));
cnt[v]--;
}
}
out.println(days[0]);
out.flush();
}
out.close();
}
static class SortByDays implements Comparator<Pair>{
@Override
public int compare(Pair o1, Pair o2) {
return o1.days-o2.days;
}
}
static class Pair{
int node;
int days;
Pair(int n,int d)
{
this.node=n;
this.days=d;
}
}
static class Reader {
private final InputStream in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private static final long LONG_MAX_TENTHS = 922337203685477580L;
private static final int LONG_MAX_LAST_DIGIT = 7;
private static final int LONG_MIN_LAST_DIGIT = 8;
public Reader(InputStream in) {
this.in = in;
}
public Reader() {
this(System.in);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
public boolean hasNext() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
int digit = b - '0';
if (n >= LONG_MAX_TENTHS) {
if (n == LONG_MAX_TENTHS) {
if (minus) {
if (digit <= LONG_MIN_LAST_DIGIT) {
n = -n * 10 - digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("not number"));
}
}
} else {
if (digit <= LONG_MAX_LAST_DIGIT) {
n = n * 10 + digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("not number"));
}
}
}
}
throw new ArithmeticException(
String.format(" overflows long."));
}
n = n * 10 + digit;
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long[] nextLongArray(int length) {
long[] array = new long[length];
for (int i = 0; i < length; i++)
array[i] = this.nextLong();
return array;
}
public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) {
long[] array = new long[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsLong(this.nextLong());
return array;
}
public int[] nextIntArray(int length) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = this.nextInt();
return array;
}
public int[][] nextIntArrayMulti(int length, int width) {
int[][] arrays = new int[width][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++)
arrays[j][i] = this.nextInt();
}
return arrays;
}
public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsInt(this.nextInt());
return array;
}
public double[] nextDoubleArray(int length) {
double[] array = new double[length];
for (int i = 0; i < length; i++)
array[i] = this.nextDouble();
return array;
}
public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) {
double[] array = new double[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsDouble(this.nextDouble());
return array;
}
public long[][] nextLongMatrix(int height, int width) {
long[][] mat = new long[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextLong();
}
return mat;
}
public int[][] nextIntMatrix(int height, int width) {
int[][] mat = new int[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextInt();
}
return mat;
}
public double[][] nextDoubleMatrix(int height, int width) {
double[][] mat = new double[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextDouble();
}
return mat;
}
public char[][] nextCharMatrix(int height, int width) {
char[][] mat = new char[height][width];
for (int h = 0; h < height; h++) {
String s = this.next();
for (int w = 0; w < width; w++) {
mat[h][w] = s.charAt(w);
}
}
return mat;
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(PrintStream stream) {
super(stream);
}
public FastPrinter() {
super(System.out);
}
private static String dtos(double x, int n) {
StringBuilder sb = new StringBuilder();
if (x < 0) {
sb.append('-');
x = -x;
}
x += Math.pow(10, -n) / 2;
sb.append((long) x);
sb.append(".");
x -= (long) x;
for (int i = 0; i < n; i++) {
x *= 10;
sb.append((int) x);
x -= (int) x;
}
return sb.toString();
}
@Override
public void print(float f) {
super.print(dtos(f, 20));
}
@Override
public void println(float f) {
super.println(dtos(f, 20));
}
@Override
public void print(double d) {
super.print(dtos(d, 20));
}
@Override
public void println(double d) {
super.println(dtos(d, 20));
}
public void printArray(int[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(int[] array) {
this.printArray(array, " ");
}
public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsInt(array[i]));
super.print(separator);
}
super.println(map.applyAsInt(array[n - 1]));
}
public void printArray(int[] array, java.util.function.IntUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printArray(long[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(long[] array) {
this.printArray(array, " ");
}
public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsLong(array[i]));
super.print(separator);
}
super.println(map.applyAsLong(array[n - 1]));
}
public void printArray(long[] array, java.util.function.LongUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
this.printArray(arr[i]);
}
}
}
static Random __r = new Random();
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
6360af0d619dc338342520f370599765
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
/*
Set of known nodes
priority queue of options
take min option
update all adjant
Option: [node, cost]
*/
public class C {
public static void main(String[] args) {
FastScanner fs=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
// int T=fs.nextInt();
int T=1;
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), m=fs.nextInt();
Node[] nodes=new Node[n];
for (int i=0; i<n; i++) nodes[i]=new Node(i+1);
for (int i=0; i<m; i++) {
int a=fs.nextInt()-1, b=fs.nextInt()-1;
nodes[b].adj.add(nodes[a]);
nodes[a].adjSize++;
// nodes[b].adj.add(nodes[a]);
}
nodes[n-1].cost=0;
PriorityQueue<Option> pq=new PriorityQueue<>();
pq.add(new Option(nodes[n-1], 0));
while (!pq.isEmpty()) {
Option toTake=pq.remove();
if (toTake.n.included)
continue;
toTake.n.included=true;
//consider all of n's new options
for (Node nn:toTake.n.adj) {
if (nn.included) continue;
Option o = nn.onNewNodeLegal(toTake.n, toTake.cost);
pq.add(o);
}
}
// for (Node nn:nodes) {
// System.out.println(nn.id+" "+nn.cost);
// }
out.println(nodes[0].cost);
}
out.close();
}
static class Node {
boolean included;
long cost=Long.MAX_VALUE/2;
int id;
ArrayList<Node> adj=new ArrayList<>();
ArrayList<Long> options=new ArrayList<>();
int adjSize=0;
public Node(int id) {
this.id=id;
}
public Option onNewNodeLegal(Node next, long costToNext) {
options.add(costToNext);
//either keep the current cost, or take the worst of left
cost=Math.min(cost, costToNext+1+(adjSize-options.size()));
// System.out.println("At node "+id+" cost to "+next.id+" "+costToNext+" " +adj.size()+" "+options.size());
return new Option(this, cost);
}
}
static class Option implements Comparable<Option> {
Node n;
long cost;
public Option (Node n, long cost) {
this.n=n;
this.cost=cost;
}
public int compareTo(Option o) {
return Long.compare(cost, o.cost);
}
}
static final Random random=new Random();
static final int mod=1_000_000_007;
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static long add(long a, long b) {
return (a+b)%mod;
}
static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
static long mul(long a, long b) {
return (a*b)%mod;
}
static long exp(long base, long exp) {
if (exp==0) return 1;
long half=exp(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static long[] factorials=new long[2_000_001];
static long[] invFactorials=new long[2_000_001];
static void precompFacts() {
factorials[0]=invFactorials[0]=1;
for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i);
invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2);
for (int i=invFactorials.length-2; i>=0; i--)
invFactorials[i]=mul(invFactorials[i+1], i+1);
}
static long nCk(int n, int k) {
return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k]));
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 8
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
5e9d1a826ca5725ab458ac345e88f385
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
getOrDefault
valueOf
char[] arr=st.nextToken().toCharArray();
System.out.println();
List<Integer> l=new ArrayList<>();
List<int[]> l=new ArrayList<>();
Set<Integer> set=new HashSet<>();
Map<Integer,Integer> map=new HashMap<>();
Map<Integer,List<Integer>> map=new HashMap<>();
for(int i=1;i<=n;i++) map.put(i,new ArrayList<>());
Map<Integer,List<int[]>> map=new HashMap<>();
Deque<Integer> d=new ArrayDeque<>();
PriorityQueue<Integer> pq=new PriorityQueue<>();
st = new StringTokenizer(infile.readLine());
int x=Integer.parseInt(st.nextToken());
int y=Integer.parseInt(st.nextToken());
int z=Integer.parseInt(st.nextToken());
*/
public class Solution{
static Map<Integer,List<Integer>> map=new HashMap<>();
static int[] out;
static int[] dist;
static int n;
public static void main(String []args) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
//int T=Integer.parseInt(st.nextToken());
n=Integer.parseInt(st.nextToken());
dist=new int[n+1];
out=new int[n+1];
for(int i=1;i<=n;i++) map.put(i,new ArrayList<>());
int m=Integer.parseInt(st.nextToken());
for(int i=1;i<=m;i++){
st = new StringTokenizer(infile.readLine());
int x=Integer.parseInt(st.nextToken());
int y=Integer.parseInt(st.nextToken());
map.get(y).add(x);// 建反向邊
out[x]++;
}
dij();
System.out.println(dist[1]);
}
public static void dij(){
Arrays.fill(dist,Integer.MAX_VALUE/2);
dist[n]=0;
PriorityQueue<Node> pq=new PriorityQueue<>((a,b)->a.dis-b.dis);
pq.add(new Node(n,0));
while(!pq.isEmpty()){
Node cur=pq.poll();
if(cur.dis>dist[cur.id]) continue;
for(int next:map.get(cur.id)){
out[next]--;
int distonext=dist[cur.id]+out[next]+1;
if(distonext<dist[next]){
dist[next]=distonext;
pq.add(new Node(next,dist[next]));
}
}
}
}
public static void build(long[] arr, StringTokenizer st, int lo){
for(int i=lo;i<arr.length;i++) arr[i]=Long.parseLong(st.nextToken());
}
public static void build(int[] arr, StringTokenizer st, int lo){
for(int i=lo;i<arr.length;i++) arr[i]=Integer.parseInt(st.nextToken());
}
}
class Node{
int id;
int dis;
public Node(int id,int dis){
this.id=id;
this.dis=dis;
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
989ae2930bbb57104ecc0ae57f868d8d
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.util.*;
public class Main {
static class Node implements Comparable<Node> {
int n, cost;
public Node(int n, int cost) {
this.n = n;
this.cost = cost;
}
public int compareTo(Node o) {
return Integer.compare(cost, o.cost);
}
}
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] dis = new int[n + 1], degree = new int[n + 1];
Vector<Integer> adj[] = new Vector[n + 1];
for (int i = 1; i <= n; i++)
adj[i] = new Vector();
Arrays.fill(dis, -1);
while (m-- != 0) {
int a = sc.nextInt(), b = sc.nextInt();
adj[b].add(a);
degree[a]++;
}
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.offer(new Node(n, 0));
while (!pq.isEmpty()) {
Node temp = pq.poll();
if (dis[temp.n] >= 0)
continue;
dis[temp.n] = temp.cost;
for (int p : adj[temp.n]) {
pq.offer(new Node(p, temp.cost + degree[p]));
--degree[p];
}
}
System.out.println(dis[1]);
sc.close();
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
92b03ccb24d948a9f8d059aa16e0615c
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.util.*;
public class Main {
static class Node implements Comparable<Node> {
int n, cost;
public Node(int n, int cost) {
this.n = n;
this.cost = cost;
}
public int compareTo(Node o) {
return Integer.compare(cost, o.cost);
}
}
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] dis = new int[n + 1], degree = new int[n + 1];
LinkedList<Integer> adj[] = new LinkedList[n + 1];
for (int i = 1; i <= n; i++)
adj[i] = new LinkedList();
Arrays.fill(dis, -1);
while (m-- != 0) {
int a = sc.nextInt(), b = sc.nextInt();
adj[b].add(a);
degree[a]++;
}
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(n, 0));
while (!pq.isEmpty()) {
Node temp = pq.poll();
if (dis[temp.n] >= 0)
continue;
dis[temp.n] = temp.cost;
for (int p : adj[temp.n]) {
pq.add(new Node(p, temp.cost + degree[p]));
--degree[p];
}
}
System.out.println(dis[1]);
sc.close();
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
83bcc200594351de870768f8101192f0
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.util.*;
public class Main {
static class Node implements Comparable<Node> {
int n, cost;
public Node(int n, int cost) {
this.n = n;
this.cost = cost;
}
public int compareTo(Node o) {
return Integer.compare(cost, o.cost);
}
}
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] dis = new int[n + 1], degree = new int[n + 1];
ArrayList<Integer> adj[] = new ArrayList[n + 1];
for (int i = 1; i <= n; i++)
adj[i] = new ArrayList();
Arrays.fill(dis, -1);
while (m-- != 0) {
int a = sc.nextInt(), b = sc.nextInt();
adj[b].add(a);
degree[a]++;
}
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.add(new Node(n, 0));
while (!pq.isEmpty()) {
Node temp = pq.remove();
if (dis[temp.n] >= 0)
continue;
dis[temp.n] = temp.cost;
for (int p : adj[temp.n]) {
pq.add(new Node(p, temp.cost + degree[p]));
--degree[p];
}
}
System.out.println(dis[1]);
sc.close();
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
116b6921576a22db7a92c7f230b7ec26
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
int n = cin.nextInt();
int m = cin.nextInt();
int[] block = new int[n];
int[] ans = new int[n];
for(int i=0; i<n; i++) ans[i]=(int)1e9;
ans[n-1]=0;
List<Integer>[] in = new List[n];
for(int i=0; i<n; i++){
in[i]=new ArrayList<>();
}
for(int i=0; i<m; i++){
int v=cin.nextInt();
int u=cin.nextInt();
--u; --v;
in[u].add(v);
block[v]++;
}
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[0]));
pq.add(new int[]{0, n - 1});
while(!pq.isEmpty()){
int[] pop = pq.remove();
int cur_ans=pop[0];
int node = pop[1];
if(cur_ans!=ans[node]) continue;
for(int u:in[node]){
if (ans[u] > ans[node] + block[u]){
ans[u] = ans[node] + block[u];
pq.add(new int[]{ans[u], u});
}
block[u]--;
}
}
System.out.println(ans[0]);
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
39030e5a5685ea50809bc686f5fb5e40
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class KeshiSearch {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
76e5a68d3cc9534c2aa521002409dbeb
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
/*
* Author Name: Raj Kumar
* IDE: IntelliJ IDEA Ultimate Edition
* JDK: 18 version
* Date: 07-Jul-22
*/
import java.io.InputStreamReader;
import java.util.*;
public class KeshiSearch {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 17
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
5e8679ff3b30d0f29a508db206a2f2e7
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static Scanner cin = new Scanner(new InputStreamReader(System.in));
public static void main(String[] args) {
solve();
cin.close();
}
private static void solve() {
int n = cin.nextInt();
int m = cin.nextInt();
int v,u;
Map<Integer,List<Integer>> map = new HashMap<>();
int[] num = new int[n+1];
for(int i=1;i<=m;i++) {
u = cin.nextInt();
v = cin.nextInt();
if(!map.containsKey(v)) {
map.put(v,new ArrayList<>());
}
map.get(v).add(u);
num[u]++;
}
Queue<Point> queue = new PriorityQueue<>((o1, o2) -> o1.dis - o2.dis);
queue.add(new Point(0,n));
int[] visit = new int[n+1];
int[] d = new int[n+1];
while (!queue.isEmpty()) {
int pos = queue.peek().pos;
int dis = queue.peek().dis;
queue.poll();
if(visit[pos]==1) {
continue;
}
visit[pos]=1;
d[pos]=dis;
if(map.containsKey(pos)) {
for(int ele : map.get(pos)) {
queue.add(new Point(dis + num[ele],ele));
num[ele]--;
}
}
}
System.out.println(d[1]);
}
static class Point {
int dis;
int pos;
public Point(int dis, int pos) {
this.dis = dis;
this.pos = pos;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 11
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
68520f9582adfc5da1146709662bac44
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution {
static class FastReader {
private final BufferedReader br;
private StringTokenizer st;
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 {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
int n,m;
int[] u,v;
Solution() {
n = sc.nextInt();
m = sc.nextInt();
u = new int[m];
v = new int[m];
for (int i = 0;i < m;i++) {
u[i] = sc.nextInt();
v[i] = sc.nextInt();
u[i]--;v[i]--;
}
}
ArrayList<Integer>[] g;
ArrayList<Integer>[] rev_g;
void solve() {
g = new ArrayList[n];
rev_g = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
rev_g[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
g[u[i]].add(v[i]);
rev_g[v[i]].add(u[i]);
}
int[] dis = new int[n];
int[] cnt = new int[n];
for (int i = 0;i < n;i++) {
cnt[i] = g[i].size();
}
Arrays.fill(dis, Integer.MAX_VALUE);
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(o -> dis[o]));
pq.add(n - 1);
dis[n - 1] = 0;
boolean[] vis = new boolean[n];
while (!pq.isEmpty()) {
int u = pq.poll();
if (vis[u]) continue;
vis[u] = true;
for (int v : rev_g[u]) {
if (dis[v] > dis[u] + cnt[v]) {
dis[v] = dis[u] + cnt[v];
pq.add(v);
}
cnt[v] -= 1;
}
}
vis = new boolean[n];
System.out.println(dis[0]);
}
static FastReader sc = new FastReader();
public static void main(String[] args) {
new Solution().solve();
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 11
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
b2ba25742614de8a0271c590cf98c1c9
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.PriorityQueue;
import java.util.HashMap;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.Map;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
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);
EKeshiInSearchOfAmShZ solver = new EKeshiInSearchOfAmShZ();
solver.solve(1, in, out);
out.close();
}
static class EKeshiInSearchOfAmShZ {
int N = 200010;
int M = N;
int[] h2 = new int[N];
int[] e2 = new int[M];
int[] ne2 = new int[M];
int idx2;
int n;
int m;
int[] dist = new int[N];
int inf = 0x3f3f3f3f;
int[] cnt = new int[N];
Map<Long, Integer> map = new HashMap<>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
Arrays.fill(h2, -1);
n = in.nextInt();
m = in.nextInt();
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
add2(b, a);
cnt[a]++;
long key = (long) a * N + b;
map.put(key, map.getOrDefault(key, 0) + 1);
}
dijkstra();
out.println(dist[1]);
}
void dijkstra() {
Arrays.fill(dist, inf);
PriorityQueue<int[]> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
priorityQueue.add(new int[]{0, n});
while (!priorityQueue.isEmpty()) {
int[] poll = priorityQueue.poll();
int d = poll[0];
int v = poll[1];
if (dist[v] != inf) {
continue;
}
dist[v] = d;
for (int i = h2[v]; i != -1; i = ne2[i]) {
int j = e2[i];
cnt[j]--;
// if (dist[j] > d + cnt[j] + 1) {
// dist[j] = d + cnt[j] + 1;
priorityQueue.add(new int[]{d + cnt[j] + 1, j});
// }
}
}
}
void add2(int a, int b) {
e2[idx2] = b;
ne2[idx2] = h2[a];
h2[a] = idx2++;
}
}
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 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 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 UnknownError();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 11
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
595c2b0863b00ca8de262fd178183a81
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
import java.util.*;
public class JSA {
static class Node implements Comparable<Node> {
int n, cost;
public Node(int n, int cost) {
this.n = n;
this.cost = cost;
}
public int compareTo(Node o) {
return Integer.compare(cost, o.cost);
}
}
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] dis = new int[n + 1], degree = new int[n + 1];
Vector<Integer> adj[] = new Vector[n + 1];
for (int i = 1; i <= n; i++)
adj[i] = new Vector();
Arrays.fill(dis, -1);
while (m-- != 0) {
int a = sc.nextInt(), b = sc.nextInt();
adj[b].add(a);
degree[a]++;
}
PriorityQueue<Node> pq = new PriorityQueue<>();
pq.offer(new Node(n, 0));
while (!pq.isEmpty()) {
Node temp = pq.poll();
if (dis[temp.n] >= 0)
continue;
dis[temp.n] = temp.cost;
for (int p : adj[temp.n]) {
pq.offer(new Node(p, temp.cost + degree[p]));
--degree[p];
}
}
System.out.println(dis[1]);
sc.close();
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 11
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
caed8aa6bc40893017169e91972964b6
|
train_109.jsonl
|
1655390100
|
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $$$n$$$ cities in Italy indexed from $$$1$$$ to $$$n$$$ and $$$m$$$ directed roads indexed from $$$1$$$ to $$$m$$$. Initially, Keshi is located in the city $$$1$$$ and wants to go to AmShZ's house in the city $$$n$$$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $$$B$$$ is reachable from city $$$A$$$ if there's an out-going road from city $$$A$$$ to city $$$B$$$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer $$$d$$$ for which they can make sure that they will see each other after at most $$$d$$$ days. Help them find $$$d$$$.
|
256 megabytes
|
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.*;
import java.lang.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.io.*;
public class CodeForces {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.00000");
final static int MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE, mod = (int) (1e9 + 7);
final static long LMAX = Long.MAX_VALUE, LMIN = Long.MIN_VALUE;
final static long INF = (long) 1e18, Neg_INF = (long) -1e18;
static Random rand = new Random();
// ======================= MAIN ==================================
public static void main(String[] args) throws IOException {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// ==== start ====
input();
preprocess();
int t = 1;
// t = readInt();
while (t-- > 0) {
solve();
}
out.flush();
// ==== end ====
if (!oj)
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
private static void solve() throws IOException {
int n = readInt(), m = readInt();
int[] edges = new int[n], dist = new int[n];
List<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
dist[i] = m;
}
dist[n - 1] = 0;
for (int i = 0; i < m; i++) {
int u = readInt() - 1, v = readInt() - 1;
graph[v].add(u);
edges[u]++;
}
boolean[] vis = new boolean[n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
pq.add(new int[] { 0, n - 1 });
while (!pq.isEmpty()) {
int rem = pq.remove()[1];
if (vis[rem])
continue;
vis[rem] = true;
for (int nbr : graph[rem]) {
if (dist[rem] + edges[nbr] < dist[nbr]) {
dist[nbr] = dist[rem] + edges[nbr];
pq.add(new int[] { dist[nbr], nbr });
}
edges[nbr]--;
}
}
out.println(dist[0]);
}
private static void preprocess() throws IOException {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac CodeForces.java
// java CodeForces
// javac CodeForces.java && java CodeForces
// change Stack size -> java -Xss16M CodeForces.java
// ==================== CUSTOM CLASSES ================================
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int f, int s) {
first = f;
second = s;
}
public int compareTo(Pair o) {
if (this.first == o.first)
return this.second - o.second;
return this.first - o.first;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Pair other = (Pair) (obj);
if (this.first != other.first)
return false;
if (this.second != other.second)
return false;
return true;
}
@Override
public int hashCode() {
return this.first ^ this.second;
}
@Override
public String toString() {
return this.first + " " + this.second;
}
}
static class DequeNode {
DequeNode prev, next;
int val;
DequeNode(int val) {
this.val = val;
}
DequeNode(int val, DequeNode prev, DequeNode next) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
// ======================= FOR INPUT ==================================
private static void input() {
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
static int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = readInt();
return arr;
}
static int[][] read2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = readIntArray(m);
return arr;
}
static List<Integer> readIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readInt());
return list;
}
static long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = readLong();
return arr;
}
static long[][] read2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = readLongArray(m);
return arr;
}
static List<Long> readLongList(int n) throws IOException {
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readLong());
return list;
}
static char[] readCharArray() throws IOException {
return readString().toCharArray();
}
static char[][] readMatrix(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = readCharArray();
return mat;
}
// ========================= FOR OUTPUT ==================================
private static void printIList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIArray(arr[i]);
}
private static void printLArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLArray(arr[i]);
}
private static void yes() {
out.println("YES");
}
private static void no() {
out.println("NO");
}
// ====================== TO CHECK IF STRING IS NUMBER ========================
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// ==================== FASTER SORT ================================
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// ==================== MATHEMATICAL FUNCTIONS ===========================
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static int mod_pow(long a, long b, int mod) {
if (b == 0)
return 1;
int temp = mod_pow(a, b >> 1, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static int multiply(int a, int b) {
return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod);
}
private static int divide(int a, int b) {
return multiply(a, mod_pow(b, mod - 2, mod));
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
private static long nCr(long n, long r) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans *= i;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans;
}
private static List<Integer> factors(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 1; 1L * i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
private static List<Long> factors(long n) {
List<Long> list = new ArrayList<>();
for (long i = 1; i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
// ==================== Primes using Seive =====================
private static List<Integer> getPrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
for (int i = 2; 1L * i * i <= n; i++)
if (prime[i])
for (int j = i * i; j <= n; j += i)
prime[j] = false;
// return prime;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= n; i++)
if (prime[i])
list.add(i);
return list;
}
private static int[] SeivePrime(int n) {
int[] primes = new int[n];
for (int i = 0; i < n; i++)
primes[i] = i;
for (int i = 2; 1L * i * i < n; i++) {
if (primes[i] != i)
continue;
for (int j = i * i; j < n; j += i)
if (primes[j] == j)
primes[j] = i;
}
return primes;
}
// ==================== STRING FUNCTIONS ================================
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
// check if a is subsequence of b
private static boolean isSubsequence(String a, String b) {
int idx = 0;
for (int i = 0; i < b.length() && idx < a.length(); i++)
if (a.charAt(idx) == b.charAt(i))
idx++;
return idx == a.length();
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// ==================== LIS & LNDS ================================
private static int LIS(int arr[], int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// =============== Lower Bound & Upper Bound ===========
// less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(List<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(List<Long> list, long val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== UNION FIND =====================
private static int find(int x, int[] parent) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x], parent);
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly)
return false;
if (rank[lx] > rank[ly])
parent[ly] = lx;
else if (rank[lx] < rank[ly])
parent[lx] = ly;
else {
parent[lx] = ly;
rank[ly]++;
}
return true;
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
void insert(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
curr.children[ch - 'a'] = new Node();
curr = curr.children[ch - 'a'];
}
curr.isEnd = true;
}
boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
return false;
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ==================
public static class SegmentTree {
int n;
long[] arr, tree, lazy;
SegmentTree(long arr[]) {
this.arr = arr;
this.n = arr.length;
this.tree = new long[(n << 2)];
this.lazy = new long[(n << 2)];
build(1, 0, n - 1);
}
void build(int id, int start, int end) {
if (start == end)
tree[id] = arr[start];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
build(left, start, mid);
build(right, mid + 1, end);
tree[id] = tree[left] + tree[right];
}
}
void update(int l, int r, long val) {
update(1, 0, n - 1, l, r, val);
}
void update(int id, int start, int end, int l, int r, long val) {
distribute(id, start, end);
if (end < l || r < start)
return;
if (start == end)
tree[id] += val;
else if (l <= start && end <= r) {
lazy[id] += val;
distribute(id, start, end);
} else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
update(left, start, mid, l, r, val);
update(right, mid + 1, end, l, r, val);
tree[id] = tree[left] + tree[right];
}
}
long query(int l, int r) {
return query(1, 0, n - 1, l, r);
}
long query(int id, int start, int end, int l, int r) {
if (end < l || r < start)
return 0L;
distribute(id, start, end);
if (start == end)
return tree[id];
else if (l <= start && end <= r)
return tree[id];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r);
}
}
void distribute(int id, int start, int end) {
if (start == end)
tree[id] += lazy[id];
else {
tree[id] += lazy[id] * (end - start + 1);
lazy[(id << 1)] += lazy[id];
lazy[(id << 1) + 1] += lazy[id];
}
lazy[id] = 0;
}
}
// ==================== FENWICK TREE ================================
static class FT {
int n;
int[] arr;
int[] tree;
FT(int[] arr, int n) {
this.arr = arr;
this.n = n;
this.tree = new int[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
FT(int n) {
this.n = n;
this.tree = new int[n + 1];
}
// 1 based indexing
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
// 1 based indexing
long query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
long getSum(int idx) {
long ans = 0L;
while (idx > 0) {
ans += tree[idx];
idx -= idx & -idx;
}
return ans;
}
}
// ==================== BINARY INDEX TREE ================================
static class BIT {
long[][] tree;
int n, m;
BIT(int[][] mat, int n, int m) {
this.n = n;
this.m = m;
tree = new long[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
update(i, j, mat[i - 1][j - 1]);
}
}
}
void update(int x, int y, int val) {
while (x <= n) {
int t = y;
while (t <= m) {
tree[x][t] += val;
t += t & -t;
}
x += x & -x;
}
}
long query(int x1, int y1, int x2, int y2) {
return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1);
}
long getSum(int x, int y) {
long ans = 0L;
while (x > 0) {
int t = y;
while (t > 0) {
ans += tree[x][t];
t -= t & -t;
}
x -= x & -x;
}
return ans;
}
}
}
|
Java
|
["2 1\n1 2", "4 4\n1 2\n1 4\n2 4\n1 4", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1"]
|
2 seconds
|
["1", "2", "4"]
|
NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $$$1$$$ will be city $$$4$$$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
|
Java 11
|
standard input
|
[
"graphs",
"greedy",
"shortest paths"
] |
1a83878ec600c87e74b48d6fdda89d4e
|
The first line of the input contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$$$ — the number of cities and roads correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ $$$(1 \le v_i , u_i \le n,v_i \neq u_i)$$$, denoting a directed road going from city $$$v_i$$$ to city $$$u_i$$$. It is guaranteed that there is at least one route from city $$$1$$$ to city $$$n$$$. Note that there may be more than one road between a pair of cities in each direction.
| 2,300
|
Output the smallest possible integer $$$d$$$ to make sure that AmShZ and Keshi will see each other after at most $$$d$$$ days.
|
standard output
| |
PASSED
|
4d58c4e90232802f9f4101acad3cf93a
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 40 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
/*
TO LEARN
2-euler tour
*/
/*
TO SOLVE
codeforces 722 kavi on pairing duty
*/
/*
bit manipulation shit
1-Computer Systems: A Programmer's Perspective
2-hacker's delight
3-(02-03-bits-ints)
4-machine-basics
5-Bits Manipulation tutorialspoint
*/
/*
TO WATCH
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.util.stream.Collectors;
public class B{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static int ask(int l,int r)
{
System.out.println("? "+l+" "+r);
return scan.nextInt();
}
public static void main(String[] args) throws Exception
{
// scan=new FastScanner("D:\\usaco test data\\W.txt");
// out = new PrintWriter("D:\\usaco test data\\WW.txt");
/*
READING
3-Introduction to DP with Bitmasking codefoces
4-Bit Manipulation hackerearth
5-read more about mobious and inculsion-exclusion
*/
/*
if it has no Xs or Os then the answer is 0
*/
int tt=1;
//tt=scan.nextInt();
int T=1;
//System.out.println(8|9);
outer:while(tt-->0)
{
int n=scan.nextInt();
int idx=ask(1,n);
int second=-1,first=-1;
if(idx!=n)
first=ask(idx,n);
if(1!=idx) second=ask(1,idx);
int l=-1,r=-1;
if(first==idx)
{
l=idx;
r=n;
l++;
int ans=-1;
while(l<=r)
{
int mid=(l+r)/2;
int as=ask(idx,mid);
if(as==idx)
{
ans=mid;
r=mid-1;
}
else l=mid+1;
}
out.println("! "+ans);
}
else
{
l=1;
r=idx;
r--;
int ans=-1;
while(l<=r)
{
int mid=(l+r)/2;
int as=ask(mid,idx);
if(as==idx)
{
ans=mid;
l=mid+1;
}
else r=mid-1;
}
out.println("! "+ans);
}
}
out.close();
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(long[] arr) {
List<Long> list = new ArrayList<>();
for (Long object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
return (int)(z-o.z);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
958f6bc456e74adfd4ea3dd04df895d0
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 40 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.util.*;
import java.math.*;
import java.io.*;
public class B{
static int[] dx={-1,1,0,0};
static int[] dy={0,0,1,-1};
static FastReader scan=new FastReader();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static ArrayList<Pair>es;
static LinkedList<Integer>edges[];
static LinkedList<Integer>edges2[];
static boolean prime[];
static void sieve(int n)
{
prime = new boolean[n+1];
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
}
public static int lowerBound(long[] array, int length, long value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = (low + high) / 2;
//checks if the value is less than middle element of the array
if (value <= array[mid]) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
public static int upperBound(long[] array, int length, long value) {
int low = 0;
int high = length;
while (low < high) {
final int mid = low+(high-low) / 2;
if ( array[mid]>value) {
high = mid ;
} else {
low = mid+1;
}
}
return low;
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
static boolean isPowerOfTwo(long n)
{
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
static boolean isprime(long x)
{
for(long i=2;i*i<=x;i++)
if(x%i==0)
return false;
return true;
}
static int dist(int x1,int y1,int x2,int y2){
return Math.abs(x1-x2)+Math.abs(y1-y2);
}
static long cuberoot(long x)
{
long lo = 0, hi = 1000005;
while(lo<hi)
{
long m = (lo+hi+1)/2;
if(m*m*m>x)
hi = m-1;
else
lo = m;
}
return lo;
}
public static int log2(int N)
{
// calculate log2 N indirectly
// using log() method
int result = (int)(Math.log(N) / Math.log(2));
return result;
}
static long gcd(long a, long b) {
if(a!=0&&b!=0)
while((a%=b)!=0&&(b%=a)!=0);
return a^b;
}
static long LCM(long a,long b){
return (Math.abs(a*b))/gcd(a,b);
}
static int mid;
public static class comp1 implements Comparator<Pair>{
public int compare(Pair o1,Pair o2){
return (int)(o1.y-o2.y);
}
}
public static class comp2 implements Comparator<Pair>{
public int compare(Pair o1,Pair o2){
return (int)((o1.x+o1.y*mid)-(o2.x+o2.y*mid));
}
}
static boolean can(int m,int s)
{
return (s>=0&&s<=m*9);
}
static boolean collinear(long x1, long y1, long x2,
long y2, long x3, long y3)
{
long a = x1 * (y2 - y3) +
x2 * (y3 - y1) +
x3 * (y1 - y2);
if(a==0)
return true;
return false;
}
static void pythagoreanTriplets(int limit)
{
//ArrayList<Integer>res=new ArrayList<Integer>();
// triplet: a^2 + b^2 = c^2
int a, b, c = 0;
// loop from 2 to max_limitit
int m = 2;
// Limiting c would limit
// all a, b and c
int cnt=0;
int tmp=1;
while (c < limit) {
// now loop on j from 1 to i-1
//System.out.println("FUCK");
for ( int n=tmp; n < m; n++) {
// Evaluate and print
// triplets using
// the relation between
// a, b and c
a = m * m - n * n;
b = 2 * m * n;
c = m * m + n * n;
// System.out.println("FUCK");
if (c > limit)
break;
// System.out.println(a + " " + b + " " + c);
if(c+b==c*c-b*b){
// out.println(n);
/// out.println(a+" "+b+" "+c);
cnt++;
}
}
tmp++;
m++;
}
out.println(cnt);
}
static int res[];
static boolean vis[]=new boolean[101];
static int arr[];
static int n;
static void rec(int l,int r,int level)
{
int mx=-1;
int id=-1;
int mx2=-1,id2=-1;
if(l<0||r>n)
return;
for(int i=l;i<=r;i++)
{
// System.out.println(l);
if(arr[i]>mx)
{
id=i;
mx=arr[i];
}
}
if(id!=-1){
res[id]=level;
rec(l,id-1,level+1);
rec(id+1,r,level+1);
}
}
public static void main(String[] args) throws Exception
{
/*int xx=253;
for(int i=1;i*i<=xx;i++)
{
if(xx%i==0)
{
System.out.println(i);
System.out.println(xx/i);
}
}*/
//java.util.Scanner scan=new java.util.Scanner(new File("mootube.in"));
// PrintWriter out = new PrintWriter (new FileWriter("mootube.out"));
//Scannen=new FastReader("moocast.in");
//out = new PrintWriter ("moocast.out");
//System.out.println(3^2);
//System.out.println(19%4);
//StringBuilder news=new StringBuilder("ab");
//news.deleteCharAt(1);
//news.insert(0,'c');
//news.deleteCharAt(0);
//System.out.println(news);
//System.out.println(can(2,15));
//System.out.println(LCM(2,2));
// System.out.println(31^15);
//System.out.println("");
//System.out.println(824924296372176000L>(long)1e16);
int tt=1;
//rec(2020);
//int st=scan.nextInt();
//System.out.println(calc(91));
//sieve(21000);
//SNWNSENSNNSWNNW
// System.out.println(set.remove(new Pair(1,1)));
//System.out.println(count("cccccccccccccccccccccccccooooooooooooooooooooooooodddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffforrrrrrrrrrrrrcesssssssssssss","codeforces"));
//System.out.println(isPowerOfTwo(446265625L));
//System.out.println("daaa".compareTo("bccc"));
//System.out.println(2999000999L>1999982505L);
//tt=scan.nextInt();
outer:while(tt-->0)
{
int n=scan.nextInt();
int l=1,r=n;
//int arr[]={1 ,2};
//int arr[]={ 2, 6, 3, 4, 1, 5, 7, 9 ,10, 8,11};
//System.out.println("? "+(0)+" "+(n-1));
//System.out.flush();
//int tmp[]={5,1,4,2,3};
//Arrays.sort(tmp);
//int idx=scan.nextInt();
//int idx=-1;
/*for(int i=0;i<n;i++)
{
if(arr[i]==n-1)
idx=i;
*/
int idx=-1;
while(l<r)
{
int mid=(l+r)/2;
System.out.println("?"+" "+l+" "+r);
System.out.flush();
idx=scan.nextInt();
if(idx<=mid)
{
if(l==mid)
{
l=mid+1;
continue;
}
System.out.println("?"+" "+l+" "+mid);
System.out.flush();
int k=scan.nextInt();
if(idx==k)
r=mid;
else l=mid+1;
}
else
{
if(mid+1==r)
{
r=mid;
continue;
}
System.out.println("?"+" "+(mid+1)+" "+r);
System.out.flush();
int k=scan.nextInt();
if(idx==k)
l=mid+1;
else r=mid;
}
}
System.out.println("! "+(r));
//System.out.flush();
//out.println(cnt);
}
out.close();
}
static class dsu{
static int id[]=new int[101];
dsu()
{
for(int i=0;i<101;i++)
id[i]=i;
}
static int find(int x)
{
if(x==id[x])
return x;
return find(id[x]);
}
static void connect(int i,int j)
{
i=find(i);
j=find(j);
id[i]=j;
}
static boolean is(int i,int j)
{
return find(i)==find(j);
}
}
static long binexp(long a,long n,long mod)
{
if(n==0)
return 1;
long res=binexp(a,n/2,mod)%mod;
res=res*res;
if(n%2==1)
return (res*a)%mod;
else
return res%mod;
}
static class special{
Pair x;
Pair y;
special(Pair x,Pair y)
{
this.x=new Pair(x.x,x.y);
this.y=new Pair(y.x,y.y);
}
@Override
public int hashCode() {
return (int)(x.x + 31 * y.y);
}
public boolean equals(Object other)
{
if(other instanceof special)
{
special e =(special)other;
return this.x.x==e.x.x && this.x.y==e.x.y && this.y.x==e.y.x && this.y.y==e.y.y;
}
else return false;
}
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return base % mod;
long R = powMod(base, exp/2, mod) % mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return base * R % mod;
}
else return R % mod;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long object : arr) list.add(object);
Collections.sort(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
FastReader(String filename)throws Exception
{
br=new BufferedReader(new FileReader(filename));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.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 addd) {
addd.printStackTrace();
}
return str;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextInt();
}
return array;
}
}
public static class Pair implements Comparable<Pair>{
long x;
long y;
long ab;
long z;
public Pair(){}
public Pair(long x1, long y1,long z) {
x=x1;
y=y1;
this.z=z;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
this.ab=x+y;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y;
}
public int compareTo(Pair o)
{
return (int)(x-o.x);
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
36f9edc4b7159cba8b95b81ec00e2d87
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 40 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class C {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int res1 = query(0, n - 1, fs);
final boolean left = query(0, res1, fs) == res1;
int lo, hi;
if (left) {
lo = 0;
hi = res1;
// upperBound
while (lo < hi) {
final int mid = lo + hi + 1 >>> 1;
if (query(mid, res1, fs) == res1) {
lo = mid;
} else {
hi = mid - 1;
}
}
} else {
lo = res1;
hi = n - 1;
// lowerBound
while (lo < hi) {
final int mid = lo + hi >>> 1;
if (query(res1, mid, fs) != res1) {
lo = mid + 1;
} else {
hi = mid;
}
}
}
System.out.println("! " + (lo + 1));
System.out.close();
}
private static int query(int low, int high, FastScanner fs) {
if (low == high) {
return -1;
}
low++;
high++;
System.out.println("? " + low + ' ' + high);
return fs.nextInt() - 1;
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
56130ebf928e03a57f83a87a1a794dd6
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 40 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Random;
import java.util.StringTokenizer;
public final class C1 {
public static void main(String[] args) {
final FastScanner fs = new FastScanner();
final int n = fs.nextInt();
final int res1 = query(0, n - 1, fs);
final int res2 = query(0, res1, fs);
int lo;
int hi;
if (res2 == res1) {
lo = 0;
hi = res1;
while (lo < hi) {
final int mid = lo + hi + 1 >>> 1;
if (query(mid, res1, fs) == res1) {
lo = mid;
} else {
hi = mid - 1;
}
}
} else {
lo = res1;
hi = n - 1;
while (lo < hi) {
final int mid = lo + hi >>> 1;
if (query(res1, mid, fs) != res1) {
lo = mid + 1;
} else {
hi = mid;
}
}
}
System.out.println("! " + (lo + 1));
System.out.close();
}
private static int query(int low, int high, FastScanner fs) {
if (low == high) {
return -1;
}
low++;
high++;
System.out.println("? " + low + ' ' + high);
return fs.nextInt() - 1;
}
static final class Utils {
public static void shuffleSort(int[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffleSort(long[] x) {
shuffle(x);
Arrays.sort(x);
}
public static void shuffle(int[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void shuffle(long[] x) {
final Random r = new Random();
for (int i = 0; i <= x.length - 2; i++) {
final int j = i + r.nextInt(x.length - i);
swap(x, i, j);
}
}
public static void swap(int[] x, int i, int j) {
final int t = x[i];
x[i] = x[j];
x[j] = t;
}
public static void swap(long[] x, int i, int j) {
final long t = x[i];
x[i] = x[j];
x[j] = t;
}
private Utils() {}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
private String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
final int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = nextInt(); }
return a;
}
long[] nextLongArray(int n) {
final long[] a = new long[n];
for (int i = 0; i < n; i++) { a[i] = nextLong(); }
return a;
}
}
}
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
| |
PASSED
|
76746a9a12aaec73079ac70008ae5006
|
train_109.jsonl
|
1613658900
|
The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 40 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
|
256 megabytes
|
//@author->.....future_me......//
//..............Learning.........//
/*Compete against yourself*/
import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.BigInteger;
public class C {
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
try {
// int t = sc.nextInt();
// while (t-- > 0)
C.go();
out.flush();
} catch (Exception e) {
return;
}
}
static void go() {
int n=sc.nextInt();
int x=ask(1,n);
int ans=0;
if(x==ask(1,x)) {
int l=1;int r=x-1;
while(l<=r) {
int mid=(l+r)/2;
if(ask(mid,x)==x) {
ans=mid;
l=mid+1;
}else {
r=mid-1;
}
}
}else {
int l=x+1;int r=n;
while(l<=r) {
int mid=(l+r)/2;
if(ask(x,mid)==x) {
ans=mid;
r=mid-1;
}else {
l=mid+1;
}
}
}
out.println("! "+ans);
out.flush();
}
static int ask(int l ,int r) {
if(l==r) {
return -1;
}
out.println("? "+l+" "+r);
out.flush();
int x=sc.nextInt();
return x;
}
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Code Ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static int mod = (int) 1e9 + 7;
// Returns nCr % p using Fermat's
// little theorem.
static long fac[];
static long ncr(int n, int r, int p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
private static long modInverse(long l, int p) {
return pow(l,p-2);
}
static void sort(long[] a) {
ArrayList<Long> aa = new ArrayList<>();
for (long i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static long pow(long x, long y) {
long res = 1l;
while (y != 0) {
if (y % 2 == 1) {
res = x * res % mod;
}
y /= 2;
x = (x * x) % mod;
}
return res;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//use this for double quotes inside string
// " \"asdf\""
|
Java
|
["5\n\n3\n\n4"]
|
1 second
|
["? 1 5\n\n? 4 5\n\n! 1"]
|
NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.
|
Java 11
|
standard input
|
[
"binary search",
"interactive"
] |
b3e8fe76706ba17cb285c75459508334
|
The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.
| 1,600
| null |
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.