exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
1f402b0041cf3a67122884117e783425
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; import java.util.Collections; import java.util.ArrayList; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int e=0; e<t; e++) { int n=sc.nextInt(); ArrayList <Integer> spend= new ArrayList<Integer>(); ArrayList <Integer> budget= new ArrayList<Integer>(); ArrayList <Integer> difference= new ArrayList<Integer>(); for(int z=0; z<n; z++) { int a=sc.nextInt(); spend.add(a); } for(int b=0; b<n; b++) { int a=sc.nextInt(); budget.add(a); difference.add(budget.get(b)-spend.get(b)); } Collections.sort(difference); int sum=0; // {-8,-3,0,1,2,5} int y=difference.size()-1; int q=0; while(q<y) { if(difference.get(y)+difference.get(q)>=0) { sum++; q++; y--; } else{q++; } } System.out.println(sum); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
99004e69cd76de00e1482be93b11423c
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { static int solve(int [] x, int [] y, int n) { int g = 0; // group int[] diffs = new int[n]; for (int i = 0; i < n; i++) { diffs[i] = x[i] - y[i]; } Arrays.sort(diffs); // -5, -2, -1, 0, 3, 8 int index1 = 0; int index2 = n-1; // while (true) { // sum = diffs[index1] + diffs[n - index2]; // while (sum < 0) { // if (index1 >= n - index2) break; // index2++; // sum += diffs[n - index2]; // } // if (index1 >= n - index2) break; // g++; // index1++; // index2++; // } while (index1 < index2) { if (diffs[index1] + diffs[index2] <= 0) { g++; index2--; index1++; } else { index2--; } } return g; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int sets = s.nextInt(); for (int i = 0; i < sets; i++) { int n = s.nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int j = 0; j < n; j++) { x[j] = s.nextInt(); } for (int j = 0; j < n; j++) { y[j] = s.nextInt(); } System.out.println(Main.solve(x,y,n)); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
bacc01b259e6a1ec4da7e78cf6509f52
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
// package com.example.demo; import java.util.*; import java.util.stream.IntStream; import java.util.*; public class sol { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int ar[][]= new int[n][2]; for(int i=0;i<n;i++){ ar[i][0]=sc.nextInt(); } for(int i=0;i<n;i++){ ar[i][1]=sc.nextInt(); } Arrays.sort(ar,(i1,i2)->{ int v1=i1[1]-i1[0]; int v2=i2[1]-i2[0]; if(v1<v2) return -1; else if(v1>v2) return +1; else return 0; }); // Arrays.stream(ar).forEach(ii->{ // System.out.println(ii[0]+" "+ ii[1]); // }); int st=0; int en=n-1; int count=0; while(st<en){ int v1=ar[st][0]+ar[en][0]; int v2=ar[st][1]+ar[en][1]; if(v1<=v2){ st+=1; en-=1; count+=1; } else if(v1>v2){ st+=1; } } System.out.println(count); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
7f1a5532b33ae158a2bdd04a3780316e
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
//package com; import java.util.*; public class Main { public static void main(String[] args) { // write your code here Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-- >0){ int n = in.nextInt(); int prepareMoney[] = new int[n]; for(int i=0;i<n;i++){ prepareMoney[i] = in.nextInt(); } int spendMoney[] = new int[n]; for(int i=0;i<n;i++){ spendMoney[i] = in.nextInt(); } int p[] = new int[n]; for (int i = 0; i < n; i++) { p[i] = spendMoney[i] - prepareMoney[i]; } Arrays.sort(p); int l = 0 , r = n-1; int cnt = 0; while(l<r){ if(p[l] + p[r] >= 0){ l++; r--; cnt++; } else if(p[l]<0){ l++; } else{ r--; } } System.out.println(cnt); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
62781e83c21eacc927a40f827033cd3c
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class solution { public static void main(String[] args) { Scanner input = new Scanner(System.in); int testcases = input.nextInt(); while (--testcases >= 0) { solve(input); } input.close(); } private static void solve(Scanner input) { int n = input.nextInt(); long[] x = new long[n]; for (int i = 0; i < n; i++) x[i] = input.nextLong(); for (int i = 0; i < n; i++) x[i] = x[i] - input.nextLong(); Arrays.sort(x); int i = 0; n--; long count = 0; while(i<n){ if((x[i]+x[n])<=0) { count++; i++; n--; }else{ n--; } } System.out.println(count); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
d2c1f12a3bdffc380ca8bb08bfd76a6a
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import static java.lang.System.out; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.log10; import java.util.*; import java.lang.*; import java.io.*; public class a_Codeforces { public static void main(String[] args) throws java.lang.Exception { FastReader sc = new FastReader(); FastWriter out = new FastWriter(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int ans = 0; int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } int[] y = new int[n]; Integer[] d = new Integer[n]; for (int i = 0; i < n; i++) { y[i] = sc.nextInt(); d[i] = y[i] - x[i]; } Arrays.sort(d, Collections.reverseOrder()); int j = n - 1; for (int i = 0; i < n; i++) { while (j > i && d[i] + d[j] < 0) j--; if (j <= i) break; ans++; j--; } out.println(ans); } out.close(); } /* * int[] x = new int[n]; * for (int i=0; i<n; i++){ * x[i] = sc.nextInt(); * } */ static void no() { out.println("NO"); } static void yes() { out.println("YES"); } static void m1() { out.println("-1"); } static void print(int x[]) { for (int i = 0; i < x.length; i++) { out.print(x[i] + " "); } out.println(""); } static int[] input(int n) { FastReader sc = new FastReader(); int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } return x; } static int[] swap(int x[], int a, int b) { int temp = x[b]; x[b] = x[a]; x[a] = temp; return x; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
8d24d188dffaf56cc943ab2db282c8a3
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
// Input : Pratik import java.io.*; import java.util.*; public class JavaDeveoper { public static void main(String[] args) throws IOException { try { System.setIn(new FileInputStream("input.txt")); System.setOut (new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } Soumit sc = new Soumit(); int tc = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (tc-- > 0) { int n = sc.nextInt(); long[] x = sc.nextLongArray(n); long[] y = sc.nextLongArray(n); long[] diff = new long[n]; for (int i = 0; i < n; i++) { diff[i] = y[i] - x[i]; } Arrays.sort(diff); int l = 0, r = n - 1; int c = 0; while (diff[l] < 0 && l < r) { if (diff[l] + diff[r] >= 0) { c++; r--; } l++; } c += (r - l + 1) / 2; sb.append(c).append("\n"); } System.out.println(sb); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
bf8ef530a2c4f8edbcf1012fb377631d
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class practice { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t-- > 0){ int n = in.nextInt(); int[]arr1= new int[n]; int[]arr2= new int[n]; for (int i = 0;i< n;i++) arr1[i] = in.nextInt(); for (int i = 0;i< n;i++) arr2[i] = in.nextInt(); int[]dif = new int[n]; for (int i = 0;i< n;i++) dif[i] = arr2[i]-arr1[i]; Arrays.sort(dif); int i = 0; int j = dif.length-1; int ans = 0; while (j< dif.length && i<j){ if(dif[i]+dif[j]>=0) { i++; j--; ans++; } else{ i++; } } System.out.println(ans); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
9d0b459f73626c306872d584e87fd0c4
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0){ int n = scn.nextInt(); int[] x=new int[n]; Integer[] y=new Integer[n]; for(int i=0;i<n;i++){ x[i]=scn.nextInt(); } for(int i=0;i<n;i++){ y[i]=scn.nextInt(); } for(int i=0;i<n;i++){ y[i]-=x[i]; } Arrays.sort(y, Collections.reverseOrder()); int ans=0; // boolean[] vis = new boolean[n]; int i=0; int j=n-1; while(i<j){ if(y[i]+y[j]>=0){ ans++; i++; j--; }else{ j--; } } System.out.println(ans); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
ef0f7ee8e0562aafa5f5d3c8feb0a022
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Question4 { static Scanner in = new Scanner(System.in); static int numOfGroups(int arr[]){ int pair = 0; int l=0; int r=arr.length-1; while (true){ while(l<r && arr[l]+arr[r]<0){ l++; } if(l>=r){ break; } pair++; l++; r--; } return pair; } static void ans(){ int n = in.nextInt(); int spend[] = new int[n]; int budget[] = new int[n]; for(int i=0; i<n;i++){ spend[i]=in.nextInt(); } for(int i=0;i<n;i++){ budget[i]=in.nextInt(); } for(int i=0;i<n;i++){ int mon =spend[i]; int budg =budget[i]; spend[i]=budg-mon; } Arrays.sort(spend); int groups = numOfGroups(spend); System.out.println(groups); return; } public static void main(String[] args) { int test = in.nextInt(); for(int i =0;i<test;i++){ ans(); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
3536ea93077aa83618fda722aacc17d6
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; // Code by: @Oscar-gg // Problem from: public class FriendsAndRestaurant { // FastReader template from: // https://www.geeksforgeeks.org/java-competitive-programming-setup-in-vs-code-with-fast-i-o-and-snippets/ // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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; } } // end of fast i/o code public static void main(String[] args) { FastReader reader = new FastReader(); int t = reader.nextInt(); for (int i = 0; i < t; i++) { solve(reader); } } public static void solve(FastReader reader) { int n = reader.nextInt(); int xi[] = new int[n]; for (int i = 0; i < n; i++) { xi[i] = -1 * reader.nextInt(); } for (int i = 0; i < n; i++) { xi[i] += reader.nextInt(); } Arrays.sort(xi); int index = 0, total = 0, last = n-1; while (index < last){ if (xi[index] + xi[last] >= 0){ total++; index++; last--; } else { index++; } } System.out.println(total); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
9662ce3740fd3b131500f4aa97306042
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Scanner; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { int n = sc.nextInt(); int[] x = new int[n]; for (int i = 0; i < x.length; ++i) { x[i] = sc.nextInt(); } int[] y = new int[n]; for (int i = 0; i < y.length; ++i) { y[i] = sc.nextInt(); } System.out.println(solve(x, y)); } sc.close(); } static int solve(int[] x, int[] y) { int result = 0; int[] diffs = IntStream.range(0, x.length).map(i -> y[i] - x[i]).sorted().toArray(); int leftIndex = 0; int rightIndex = x.length - 1; while (true) { while (leftIndex < rightIndex && diffs[leftIndex] + diffs[rightIndex] < 0) { ++leftIndex; } if (leftIndex >= rightIndex) { break; } ++result; ++leftIndex; --rightIndex; } return result; } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
06d189a48f6227d0bac37f5847ab77c5
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class cf_820d { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while (tc-- > 0) { int n = sc.nextInt(); int x[] = new int[n]; int y[] = new int[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { y[i] = sc.nextInt(); y[i]-=x[i]; } Arrays.sort(y); int countOfPairs=0, left=0,right=n-1; while(left<right) { if(y[right]+y[left]>=0) { countOfPairs++; right--; } left++; } System.out.println(countOfPairs); } sc.close(); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
4c03ed2f391576171fe70caf9aeeca73
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Pset44 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while (t-- > 0) { int n = sc.nextInt(); int[] x = new int[n]; int[] y = new int[n]; Integer[] friends = new Integer[n]; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { y[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { friends[i] = y[i] - x[i]; } Arrays.sort(friends, Collections.reverseOrder()); // search the richest from front int j = n - 1; int count = 0; for (int i = 0; i < n; i++) { while (j >= 0 && friends[i] + friends[j] < 0) { j--; } if (j <= i) { break; } count++; j--; } System.out.println(count); } sc.close(); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
46f988738e92ff64654b060eed6441cd
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public final class Code { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int[] parent = new int[100000]; static int[] rank = new int[100000]; static void makeset() { for (int i = 1; i < 100000; i++) { parent[i] = i; rank[i] = 0; } } //Uses path compression static int findpar(int node) { if (node == parent[node]) return node; return parent[node] = findpar(parent[node]); } //Uses union by rank static void union(int u, int v) { u = findpar(u); v = findpar(v); if (rank[u] < rank[v]) parent[u] = v; if (rank[u] > rank[v]) parent[v] = u; else { parent[v] = u; rank[u]++; } } static boolean areConnected(int a, int b) { return findpar(a) == findpar(b); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return a * b / gcd(a, b); } static boolean isPrime(int n) { // Check if n=1 or n=0 if (n <= 1) return false; // Check if n=2 or n=3 if (n == 2 || n == 3) return true; // Check whether n is divisible by 2 or 3 if (n % 2 == 0 || n % 3 == 0) return false; // Check from 5 to square root of n // Iterate i by (i+6) for (int i = 5; i <= Math.sqrt(n); i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static int hsb(int x) { return (int) (Math.log(x) / Math.log(2)); } public static void main(String[] args) { try { FastReader y = new FastReader(); int t = y.nextInt(); while (t-- > 0) { int n = y.nextInt(); int[] X = new int[n], Y = new int[n],arr=new int[n]; for (int i = 0; i < n; i++) X[i] = y.nextInt(); for (int i = 0; i < n; i++) Y[i] = y.nextInt(); for (int i = 0; i < n; i++) arr[i] = Y[i]-X[i]; Arrays.sort(arr); int i=0,j=n-1,ans=0; while(i<j) { if(arr[i]+arr[j]>=0) { ans++; i++; j--; } else i++; } System.out.println(ans); } } catch (Exception e) { e.printStackTrace(); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
6051047cde8b08aed54cebe61d4f60b5
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.lang.reflect.Parameter; import java.util.*; public class Solution { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); while (t-- > 0) { int ans = solve(); System.out.println(ans); } } private static int solve() { int n = scanner.nextInt(); int[] x = new int[n]; int[] y = new int[n]; for(int i = 0 ; i < n ; i++) x[i] = scanner.nextInt(); for(int j = 0 ; j < n ; j++) { y[j] = scanner.nextInt(); y[j] = y[j] - x[j]; } Arrays.sort(y); reverse(y); int j = n - 1; int ans = 0; for(int i = 0 ; i < n ; i++){ while(j > i && y[i] + y[j] < 0) j--; if(j <= i) break; j--; ans++; } return ans; } private static void reverse(int[] y) { for (int i = 0; i < y.length / 2; i++) { int t = y[i]; y[i] = y[y.length - i - 1]; y[y.length - i - 1] = t; } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
28c3db3f9f87bf7e567d784c22af5660
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
/** * * @author AshwinA */ import java.util.*; import java.lang.*; import java.io.*; import java.util.stream.*; import java.util.function.*; public class CP_IMP_2{ public static void main (String[] args) throws java.lang.Exception{ Reader in = new Reader(); Writer out = new Writer(); int t = in.nextInt(); while(t-->0){ int n = in.nextInt(); ArrayList<Integer> want = new ArrayList<Integer>(convertStringToInt(Arrays.asList(in.nextLine().split(" ")), Integer::parseInt)); ArrayList<Integer> bud = new ArrayList<Integer>(convertStringToInt(Arrays.asList(in.nextLine().split(" ")), Integer::parseInt)); ArrayList<Integer> diff = new ArrayList<Integer>(); for(int i=0;i<n;i++) diff.add(bud.get(i) - want.get(i)); Collections.sort(diff); int st=0, end=n-1, ans = 0; while(st<end){ if(diff.get(end) + diff.get(st) >= 0){ ans++; st++; end--; }else{ st++; } } out.println(ans); } out.close(); } static class Reader { private final BufferedReader br; private StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String string = ""; try { string = br.readLine().trim(); } catch (IOException e) { e.printStackTrace(); } return string; } } static class Writer { private final BufferedWriter bw; public Writer() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { this.print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static <T, U> List<U> convertStringToInt(List<T> listOfString, Function<T, U> function){ return listOfString.stream() .map(function) .collect(Collectors.toList()); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
6e13371f3824da7b289ba82ec1b12ea8
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class D_Friends_and_the_Restaurant { final int mod = 1000000007; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void main(String[] args) { // TODO Auto-generated method stub FastReader t = new FastReader(); PrintWriter o = new PrintWriter(System.out); int test = t.nextInt(); while (test-- > 0) { long min = Integer.MIN_VALUE, max = Integer.MAX_VALUE; long ans =0 ; int n = t.nextInt(); //long k = t.nextLong(); int[] a = new int[n]; for (int i=0; i<n; i++) { a[i] = t.nextInt(); } for (int i=0; i<n; i++) { a[i] = t.nextInt()-a[i]; } Arrays.sort(a); //int ans = 0; int j = 0; int k = n-1; while(j<k) { if (a[j]+a[k]>=0) { ans++; j++; k--; } else { j++; } } o.println(ans); // long m = t.nextLong(); // ArrayList<Integer> al = new ArrayList<>(); // HashSet<Integer> set = new HashSet<>(); // HashMap<Integer, Integer> map = new HashMap<>(); // TreeMap<Integer, Integer> map = new TreeMap<>(); // for (int i = 0; i < n; ++i) { // for (int j = 0; j < n; ++j) { // } // } } o.flush(); o.close(); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
d1c1f02e58f00fb23ce0b8ad45fbb43e
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class prog { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); long arr1[]=new long[n]; long arr2[]=new long[n]; for(int i=0;i<n;i++) { arr1[i]=sc.nextLong(); } for(int i=0;i<n;i++) { arr2[i]=sc.nextLong(); arr2[i]=arr2[i]-arr1[i]; } Arrays.sort(arr2); int res=0; int i=0,j=n-1; while(i<j) { if(arr2[i]+arr2[j]>=0) {res++;i++;j--;} else i++; } System.out.println(res); } } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
0eefa7a9e68a6a644f7991c7cfc8f842
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it. *******************************************************************************/ import java.util.*; public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0){ int n = scn.nextInt(); int []a = new int[n]; for(int i = 0;i<n;i++){ a[i] = scn.nextInt(); } int []b = new int[n]; for(int i = 0;i<n;i++){ b[i] = scn.nextInt(); } ArrayList<Integer>f = new ArrayList<>(); for(int i = 0;i<n;i++){ f.add( (b[i]-a[i])); } Collections.sort(f,Collections.reverseOrder()); int ans = 0; int i = 0; int j = n-1; while(i<j){ while(j>=0 && (f.get(i)+f.get(j))<0){ j--; } if(i<j){ ans++; i++; j--; } } System.out.println(ans); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
d28c27ebc4a035a7165def310a697e85
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int j = 0; j < n; j++) { a[j] = in.nextInt(); } for (int j = 0; j < n; j++) { b[j] = in.nextInt(); } int[] c = new int[n]; for (int j = 0; j < n; j++) { c[j] = b[j] - a[j]; } Arrays.sort(c); int l = 0, r = n - 1, count = 0; while (l < r) { if(c[r] < 0) break; if(c[l] >= 0) { count++; l++; r--; } else { if(Math.abs(c[l]) > c[r]) { l++; } else { l++; r--; count++; } } } System.out.println(count); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
75eeef784ec5477fb6eae6f38d235fa8
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int k = scn.nextInt(); while (k-- > 0) { int n = scn.nextInt(); int[] v = new int[n+1]; v[0] = Integer.MIN_VALUE; for (int i = 1 ; i <= n ; i++) v[i] = scn.nextInt(); for (int i = 1 ; i <= n ; i++) { int x = scn.nextInt(); v[i] = x - v[i]; } Arrays.sort(v); int i = n , j = 1, ans = 0; for ( ; ;ans++ , i-- ,j++) { for (; j <= n && v[j] < -v[i];) j++; if (j >= i) break; } System.out.println(ans); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
36786a623d1ce43691b3d8a9edd46147
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Codechef { 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;}BufferedReader in;StringTokenizer st; 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 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 {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 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();}} static Reader in = new Reader();static PrintWriter out = new PrintWriter(System.out);static long mod = (long)(1e9+7); static class TreeMultiset<T> {NavigableMap<T,Integer> h; public TreeMultiset() {h = new TreeMap<>();}private boolean has(T key) {return h.containsKey(key);} private void add(T key) {h.put(key,h.getOrDefault(key,0)+1);}private int get(T key) {return h.get(key);} public void del(T key) {if(h.containsKey(key)) {if(h.get(key)==1) h.remove(key);else h.put(key,h.getOrDefault(key,0)-1);}} private T down(T key) { Map.Entry<T, Integer> val;val=h.lowerEntry(key );if(val!=null) {return val.getKey();}return null;} public T up(T key) { Map.Entry<T, Integer> val;val=h.ceilingEntry(key);if(val!=null) {return val.getKey();}return null;} public int size(){int s=0; for(int k:h.values()) s+=k; return s; }} //-----------------------------INPUT-------------------------------------------------// public static int ni() throws IOException {return in.nextInt();} public static long nl() throws IOException {return in.nextLong();} public static String rl() throws IOException {return in.next();} public static char nc() throws IOException {return in.next().charAt(0);} //----------------------------ARRAYS INPUT--------------------------------------------// public static int[] ai(long n) throws IOException {int[] arr = new int[(int)n]; for (int i = 0; i < n; i++) {arr[i] = in.nextInt();}return arr;} public static long[] al(long n) throws IOException {long[] arr = new long[(int)n]; for (int i = 0; i < n; i++) {arr[i] = in.nextLong();}return arr;} public static char[] ac() throws IOException {String s = in.next();return s.toCharArray();} //----------------------------Print---------------------------------------------------// public static void pt(int a) {out.println(a + " ");} public static void pt(long a) {out.println(a + " ");} public static void pt(double a) {out.println(a + " ");} public static void pt(char a) {out.println(a + " ");} public static void pt(int[] arr) {for (int j : arr) out.print(j + " ");out.println();} public static void pt(long[] arr) {for (long l : arr) out.print(l + " ");out.println();} public static void pt(char[] arr) {for (char l : arr) out.print(l );out.println();} public static void pt(String s) {out.println(s + " ");} public static void y() {out.println("YES");} public static void n() {out.println("NO");} //--------------------------------------------Other Functions----------------------------------------------------// public static long gcd(long a, long b) {BigInteger x = BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)); return Long.parseLong(String.valueOf(x));} public static long expo(long a, long b) {long res = 1; while (b > 0) {if ((b & 1) != 0) res = res * a;a = a * a;b >>= 1;}return res;} public static long modexp(long a, long b) {long res = 1; while (b > 0) {if ((b & 1) != 0) res = (res * a % mod) % mod;a = (a % mod * a % mod) % mod;b >>= 1;}return res % mod;} public static int[] permute(int n) {int[] arr = new int[n];for (int i = 0; i < n; i++) {arr[i] = i;}return arr;} public static long min(long[] arr) {long min = Long.MAX_VALUE;for (long l : arr) {if (l < min) min = l;}return min;} public static long max(long[] arr) {long max = Long.MIN_VALUE;for (long l : arr) {if (l > max) max = l;}return max;} public static void sort(long[] arr) { List<Long> list = new ArrayList<>();for (long i : arr) {list.add(i);}Collections.sort(list); for (int i = 0; i < arr.length; i++) {arr[i] = list.get(i);}} 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);}} public static long countfactors(long n) {long ans = 0;for (long i = 1; i * i <= n; i++) {if (n % i == 0) {ans += 2;if (n / i == i) ans--;}} return ans;} public static boolean isprime(long n) {for (long i = 2; i * i <= n; i++) {if (n % i == 0) return false;}return true;} public static long [] copy(long[] arr) {long []brr=new long[arr.length];System.arraycopy(arr, 0, brr, 0, arr.length);return brr;} public static long countDigit(long n) {long count = 0;while (n != 0) {n = n / 10;++count;}return count;} static Scanner sc=new Scanner(System.in); //---------------------------------------------------------------------------------------------------------------------------------------// public static void Khud_Bhi_Krle_Kuch() throws IOException { // int n = sc.nextInt(); long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextLong(); for (int i = 0; i < n; i++) { arr[i]=sc.nextLong()-arr[i]; } sort(arr); long s=0; for(int i=0,j=n-1;;i++,j--,s++) { while (i<n&&-arr[j]>arr[i]) { i++; } if(j<=i)break; } System.out.println(s); } //--------------------------------------MAIN--------------------------------------------// public static void main(String[] args) throws Exception { int t=sc.nextInt();while(t--!=0) Khud_Bhi_Krle_Kuch(); // out.close(); }}
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
2def2625b6362d7a16bf158eb856455f
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
/** * D_Friends_and_the_Restaurant */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Collections; public class D_Friends_and_the_Restaurant { static FastReader sc = new FastReader(); static PrintWriter out= new PrintWriter(System.out); public static void main(String[] args) { int TC = sc.nextInt(); while(TC-- >0) { int n = sc.nextInt(); int[]x = new int[n]; int[]y = new int[n]; for(int i=0;i<n;i++) x[i] = sc.nextInt(); for(int i=0;i<n;i++) y[i] = sc.nextInt(); ArrayList<Integer>pos = new ArrayList<Integer>(); ArrayList<Integer>neg = new ArrayList<Integer>(); for(int i=0;i<n;i++) { if(y[i]-x[i]>=0) pos.add(y[i]-x[i]); else neg.add(y[i]-x[i]); } Collections.sort(pos); Collections.sort(neg); Collections.reverse(neg); int ans = 0; while(pos.isEmpty() == false) { int last = pos.get(pos.size()-1); pos.remove(pos.size()-1); boolean flag = false; while(neg.isEmpty() == false) { int qq = neg.get(neg.size()-1); neg.remove(neg.size()-1); if(last+qq >=0) { flag = true; ans++; break; } } if(flag == true) continue; if(pos.isEmpty() == true) break; ans++; pos.remove(pos.size()-1); } out.println(ans); } out.flush(); out.close(); } } 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
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
88e621173b18c8a1cc0eb8d24630adb6
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Main { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int queries = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < queries; ++i) { solveQuery(); } } public static void solveQuery() { int n = Integer.parseInt(scanner.nextLine()); int[] x = new int[n]; int[] y = new int[n]; for (int i = 0; i < n; ++i) { x[i] = scanner.nextInt(); } scanner.nextLine(); for (int i = 0; i < n; ++i) { y[i] = scanner.nextInt(); y[i] -= x[i]; } scanner.nextLine(); shuffleArray(y); Arrays.sort(y); int total = 0; for (int i = n - 1, j = 0; i >= 0; --i) { while (j < i && y[j] + y[i] < 0) ++j; if (j < i) { ++total; ++j; } } System.out.println(total); } private static void shuffleArray(int[] array) { int index, temp; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); temp = array[index]; array[index] = array[i]; array[i] = temp; } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
cc40213629a02b5abb254a6f4e2437a4
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static private final PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static private final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); int kkk = Integer.parseInt(st.nextToken()); while (kkk-- > 0){ solve(); out.flush(); } } private static void solve() throws IOException { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int[] burles = new int[n]; int[] budget = new int[n]; int[] diff = new int[n]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++){ burles[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++){ budget[i] = Integer.parseInt(st.nextToken()); diff[i] = budget[i] - burles[i]; } Arrays.sort(diff); int left = 0, right = n-1, ans = 0; while (right > left){ if(diff[right] < 0){ break; } if(diff[right] + diff[left] >= 0){ right--; left++; ans++; }else { left++; } } out.println(ans); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
3ffbe580da6cc0c52a70b419e7862fc0
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public final class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t = 1; t<=T; t++){ int n = sc.nextInt(); int[] spend = new int[n]; int[] budget = new int[n]; for(int i = 0; i<n; i++){ spend[i] = sc.nextInt(); } for(int i = 0; i<n; i++){ budget[i] = sc.nextInt(); } int[] savings = new int[n]; for(int i = 0; i<n; i++){ savings[i] = budget[i] - spend[i]; } Arrays.sort(savings); int i = 0; int j = n-1; int groups = 0; while(i < j){ if(savings[i]+savings[j] >= 0){ groups++; i++; j--; } else { i++; } } System.out.println(groups); } sc.close(); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
805442afae7cf5670b2d60ed1efe1231
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static Integer[] array(BufferedReader br,int n) throws IOException{ String [] values = br.readLine().split(" "); Integer [] arr = new Integer[n]; for(int i =0; i<n; i++){ arr[i] = Integer.parseInt(values[i]); } return arr; } public static class Pair implements Comparable<Pair>{ int val; int idx; Pair(int val, int idx){ this.val = val; this.idx = idx; } public int compareTo(Pair o){ return this.val-o.val; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-->0){ int n = Integer.parseInt(br.readLine()); Integer[] cost = array(br, n); Integer[] total = array(br, n); Integer[] rem = new Integer[n]; for(int i =0; i<n; i++){ rem[i] = total[i]-cost[i]; } Arrays.sort(rem); int l = 0; int r = n-1; int ans = 0; while(l<r){ if(rem[r]>=Math.abs(rem[l])){ ans++; l++; r--; } else{ l++; } } System.out.println(ans); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
749e4ba56c969812cab0c69308750915
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class CF1729D { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try { br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); } catch (Exception e) { 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()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // end of fast i/o code public static boolean isPalindrome(String str) { int i = 0; int j = str.length() - 1; int flag = 0; while (i <= j) { if (str.charAt(i) != str.charAt(j)) { flag = 1; break; } i++; j--; } return flag == 1 ? false : true; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } class Pair { int x1; int x2; public Pair(int x1, int x2) { this.x1 = x1; this.x2 = x2; } } static void solve() { } public static void main(String[] args) { FastReader fs = new FastReader(); PrintWriter out = new PrintWriter(System.out); // solve(); int t=fs.nextInt(); while(t-->0){ int n =fs.nextInt(); int x[]=fs.readArray(n); int y[]=fs.readArray(n); int dif[]=new int [n]; for(int i =0;i<n;i++){ dif[i]=y[i]-x[i]; } Arrays.sort(dif); int ct=0,sum=0; int i =0,j=n-1; while(i<j){ if(dif[i]+dif[j]>=0){ ct++;i++;j--; } else{ i++; } } out.println(ct); } out.close(); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
eede0f806a31163af4980203965f9b09
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Reader scan = new Reader(System.in); BufferedOutputStream b = new BufferedOutputStream(System.out); StringBuffer sb = new StringBuffer(); int t = scan.nextInt(); // int t = 1; while (t-->0) { int n = scan.nextInt(); int[][] mat = new int[2][n]; mat[0] = scan.nextIntArr(n); mat[1] = scan.nextIntArr(n); sb.append(solve(n, mat)); } b.write((sb.toString()).getBytes()); b.flush(); } private static String solve(int n, int[][] mat) { StringBuffer sb = new StringBuffer(); ArrayList<Integer> neg = new ArrayList<>(); ArrayList<Integer> pos = new ArrayList<>(); for(int i=0;i<n;i++) { if(mat[1][i]-mat[0][i] < 0)neg.add(mat[1][i]-mat[0][i]); else pos.add(mat[1][i]-mat[0][i]); } int i = 0; int j = 0; Collections.sort(neg); Collections.sort(pos); Collections.reverse(pos); while (i<pos.size() && j<neg.size()) { if(pos.get(i)+neg.get(j) >= 0){ i++; } j++; } int ans = (i) + (pos.size()-i)/2; sb.append(ans).append("\n"); return sb.toString(); } private static int findConnectedComp(ArrayList<ArrayList<Integer>> graph, int n) { int count = 0; boolean[] visited = new boolean[n]; Queue<Integer> q = new LinkedList<>(); for(int i=0;i<n;i++) { if(!visited[i]) { count++; q.add(i); } while (!q.isEmpty()) { int d = q.poll(); if(!visited[d]) { visited[d] = true; for(int j : graph.get(i)){ if(!visited[j])q.add(j); } } } } return count; } private static boolean inRange(int x, int y, int n, int m) { return (x>=0 && x<n && y>=0 && y<m); } public static int getLowest(ArrayList<pair> a, long x) { int l = 0; int h = a.size()-1; while(h-l>1) { int mid = (h+l)>>1; if(a.get(mid).x <= x) l = mid; else h = mid; } if(a.get(l).x > x) return l; else if(a.get(h).x > x)return h; return -1; } public static int getHighest(ArrayList<pair> a, long x) { int l = 0; int h = a.size()-1; while(h-l>1) { int mid = (h+l)>>1; if(a.get(mid).x >= x) h = mid; else l = mid; } if(a.get(h).x < x) return h; else if(a.get(l).x < x)return l; return -1; } } class pair { int x; int y; long area = 0; pair(int x, int y) { this.x = x; this.y = y; this.area = this.x*this.y; } } class comp implements Comparator<pair> { public int compare(pair a, pair b) { return (int)(a.x-b.x); } } class Reader{ private final BufferedReader reader; private StringTokenizer tokenizer; Reader(InputStream input) { this.reader = new BufferedReader(new InputStreamReader(input)); this.tokenizer = new StringTokenizer(""); } public String next() throws IOException { while(!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for(int i=0;i<n;i++)arr[i]=nextInt(); return arr; } public long[] nextLongArr(int n)throws IOException { long[] arr = new long[n]; for(int i=0;i<n;i++)arr[i]=nextLong(); return arr; } public char[] nextCharArr() throws IOException { return next().toCharArray(); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
befd9d7c952099a60a310a7a2305f509
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { public static FastReader cin; public static PrintWriter out; public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); cin = new FastReader(); int ttt = cin.nextInt(); label:for(int qqq = 1; qqq <= ttt ;qqq++ ){ int n = cin.nextInt(); long ans = 0; long zero = 0; long x[] = new long [n + 1]; long y[] = new long [n + 1]; for(int i = 0;i < n; i ++){ x[i] = cin.nextLong(); } for(int i = 0;i < n; i ++){ y[i] = cin.nextLong(); } ArrayList<Long>zlist = new ArrayList<>(); ArrayList<Long>flist = new ArrayList<>(); for(int i = 0; i < n ;i++){ if(y[i] - x[i] > 0){ zlist.add(y[i] - x[i]); }else if(y[i] - x[i] < 0){ flist.add(y[i] - x[i]); }else{ zero++; } } // out.println("最初0=>"+zero); Collections.sort(zlist,(a,b)->Long.compare(a,b)); Collections.sort(flist,(a,b)->Long.compare(b,a)); int pz = 0; int pf = 0; long sum = 0; if(flist.size() == 0){ out.println((zero + zlist.size()) / 2); continue label; } while(pz < zlist.size()){ long now = zlist.get(pz); if(pf < flist.size() && now + flist.get(pf) < 0){ pz++; zero++;//这个用不到了 // out.println("now="+now+" "+flist.get(pf)); }else{ pf++; pz++; ans++; if(pf == flist.size()){ break; } } } ans += (zlist.size() - pz + zero) / 2; out.println(ans); //至少两人 //权重最后要>=0 //sum x <= sumy //不一定所有人都要去 // out.println("zlist="+zlist); // out.println("flist="+flist); // out.println("zero="+zero); } out.close(); } public static long lcm(long a,long b ){ long ans = a / gcd(a,b) * b ; return ans; } public static long gcd(long a,long b){ if(b==0)return a; else return gcd(b,a%b); } static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.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 lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
dcaacb720b256366a46e1a1727967ff9
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Scanner; public class CF1729D { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { int n = scanner.nextInt(); int[] x = new int[n]; int[] y = new int[n]; for (int j = 0; j < n; j++) { x[j] = scanner.nextInt(); } for (int j = 0; j < n; j++) { y[j] = scanner.nextInt(); } System.out.println(solve(n, x, y)); } } private static String solve(int n, int[] x, int[] y) { int[] ySubX = new int[n]; for (int i = 0; i < n; i++) { ySubX[i] = y[i] - x[i]; } Arrays.sort(ySubX); int left = 0; int right = n - 1; int cnt = 0; while (left < right) { if (ySubX[left] + ySubX[right] >= 0) { ySubX[right] -= ySubX[left]; left++; right--; cnt++; } else { left++; } } return String.valueOf(cnt); } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
9f41c34a003d8de59543b44691a5c359
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.lang.reflect.Array; import java.util.*; import java.io.*; import static java.lang.Math.*; public class Codeforces { 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 { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); while ( t-->0 ){ int n = in.nextInt(); long[] x = new long[n]; long[] y = new long[n]; long[] z = new long[n]; for (int i = 0 ; i < n ; i++) { x[i] = in.nextLong(); } for (int i = 0 ; i < n ; i++) { y[i] = in.nextLong(); } for (int i = 0 ; i < n ; i++) { z[i] = x[i] - y[i]; } Arrays.sort(z); int i = 0; int j = n-1; int cnt = 0; while ( i<j ){ if (z[i]+z[j]<=0){ cnt++; j--;i++; }else if(z[i]+z[j]>0){ if ( z[j] >= abs(z[i]) ){ j--; }else { i++; } } } System.out.println(cnt); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
21066d6147070057bfc05eccecb2e328
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Test1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] arr1 = new int[n]; int[] arr2 = new int[n]; for(int i=0;i<n;i++) arr1[i] = sc.nextInt(); for(int i=0;i<n;i++) arr2[i] = sc.nextInt(); int[] list = new int[n]; for(int i=0;i<n;i++) { list[i] = arr2[i]-arr1[i]; } Arrays.sort(list); int count = 0; int i = 0, j = n-1; while(i < j) { if(list[i]+list[j] >= 0) { count++; i++; j--; continue; } i++; } System.out.println(count); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
4b9eac8fcb8ec96dd0e45dae6eacba8a
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.*; public class D { final static boolean multipleTests = true; Input in; PrintWriter out; public D() { in = new Input(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { D solution = new D(); int t = 1; if (multipleTests) t = solution.in.nextInt(); for (; t > 0; t--) { solution.solve(); } solution.out.close(); } void solve() { int n = in.nextInt(); int[] x = in.nextIntArray(n); int[] y = in.nextIntArray(n); long[] diff = new long[n]; for (int i=0; i<n; i++) { diff[i] = y[i] - x[i]; } Arrays.sort(diff); int lo = 0; int hi = n/2; while (lo < hi) { int mid = (1 + hi + lo)/2; boolean valid = true; int l = n - 2*mid; int r = n-1; while (l < r && valid) { if (diff[l] + diff[r] < 0) { valid = false; } l++; r--; } if (valid) { lo = mid; } else { hi = mid-1; } } out.println(lo); } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } String nextString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextString()); } long nextLong() { return Long.parseLong(nextString()); } double nextDouble() { return Double.parseDouble(nextString()); } int[] nextIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) { ans[i] = nextInt(); } return ans; } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
74b5b30f35dbc4c5679aba108d340c6d
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T=in.nextInt(); while(T-->0) { int n=in.nextInt(); int k[][]=new int[n][3]; for(int i=0;i<n;i++) k[i][0]=in.nextInt(); for(int i=0;i<n;i++) k[i][1]=in.nextInt(); for(int i=0;i<n;i++) k[i][2]=k[i][1]-k[i][0]; Arrays.sort(k,(a,b)->a[2]-b[2]); int lo=0,hi=n-1; int ans=0; while(lo<hi) { if(k[lo][2]+k[hi][2]>=0) { ans++; lo++; hi--; } else { lo++; } } System.out.println(ans); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
80c35ac3f862d4f97f875f314436325c
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.util.*; import java.io.*; public class D { public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int tc = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (tc-->0){ int n = sc.nextInt(); long[] x = sc.nextLongArray(n); long[] y = sc.nextLongArray(n); long[] diff = new long[n]; for(int i=0;i<n;i++){ diff[i] = y[i] - x[i]; } Arrays.sort(diff); int l = 0, r = n-1; int c = 0; while(diff[l] < 0 && l < r){ if(diff[l] + diff[r] >= 0){ c++; r--; } l++; } c += (r - l + 1) / 2; sb.append(c).append("\n"); } System.out.println(sb); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
92e16819499cde1f7cd1cf1c379ec892
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class TaskD { public static void main(String[] args) { FastReader reader = new FastReader(); int tt = reader.nextInt(); // int tt = 1; for (; tt > 0; tt--) { int n = reader.nextInt(); int[] delta = new int[n]; for (int i = 0; i < n; i++) { delta[i] = -reader.nextInt(); } for (int i = 0; i < n; i++) { delta[i] += reader.nextInt(); } Arrays.sort(delta); int l = 0; int r = delta.length - 1; int counter = 0; while (l < r) { if (delta[l] + delta[r] >= 0) { counter++; r--; } l++; } System.out.println(counter); } } 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 { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
d023dc7d2642866ef9c1fd272d290c93
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (Math.pow(10, 9) + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static int dp[][]; static double cmp = 0.000000001; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter("output.txt")); int test = input.nextInt(); loop: for (int o = 1; o <= test; o++) { int n = input.nextInt(); long x[] = new long[n]; long y[] = new long[n]; int ans = 0; HashMap<Long, Integer> h = new HashMap<>(); TreeSet<Long> s = new TreeSet<>(); for (int i = 0; i < n; i++) { x[i] = input.nextInt(); } for (int i = 0; i < n; i++) { y[i] = input.nextInt(); long d = y[i] - x[i]; if (h.get(d) == null) { h.put(d, 0); s.add(d); } h.put(d, h.get(d) + 1); } for (int i = 0; i < n; i++) { long d = y[i] - x[i]; if (s.contains(d)) { h.put(d, h.get(d) - 1); if (h.get(d) == 0) { s.remove(d); } long dd = d * -1; Long ce = s.ceiling(dd); if (ce != null) { ans++; h.put(ce, h.get(ce) - 1); if (h.get(ce) == 0) { s.remove(ce); } } } else { h.put(d, h.get(d) - 1); if (h.get(d) == 0) { s.remove(d); } } } log.write(ans + "\n"); } log.flush(); } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static int sumOfRange(int x1, int y1, int x2, int y2, int e, int a[][][]) { return (a[e][x2][y2] - a[e][x1 - 1][y2] - a[e][x2][y1 - 1]) + a[e][x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void dfs(int node, ArrayList<Integer> a[], boolean vi[]) { vi[node] = true; for (Integer ch : a[node]) { if (!vi[ch]) { dfs(ch, a, vi); } } } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } public static pair[] dijkstra(int node, ArrayList<pair> a[]) { PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } }); q.add(new tri(node, 0, -1)); pair distance[] = new pair[a.length]; while (!q.isEmpty()) { tri p = q.poll(); int cost = p.y; if (distance[p.x] != null) { continue; } distance[p.x] = new pair(p.z, cost); ArrayList<pair> nodes = a[p.x]; for (pair node1 : nodes) { if (distance[node1.x] == null) { tri pa = new tri(node1.x, cost + node1.y, p.x); q.add(pa); } } } return distance; } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static int logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long n) { if (n == 1) { return a; } long pow = power(a, n / 2); pow *= pow; if (n % 2 != 0) { pow *= a; } return pow; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> a = new ArrayList<>(); while (n % 2 == 0) { a.add(2); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { a.add(i); n /= i; } if (n < i) { break; } } if (n > 2) { a.add(n); } return a; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } // end of solution public static BigInteger f(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (int i = 3; i <= Math.sqrt(num) + 1; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(int[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] >= a[i + 1]) { return false; } } return true; } public static void print(int[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(r.readLine()); } return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
7bd5df7145d27f8bb098650053dd40f2
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class codeforces_820_D { private static void solve(FastIOAdapter in, PrintWriter out) { int n = in.nextInt(); int[] x = in.readArray(n); int[] y = in.readArray(n); int[] diff = new int[n]; for (int i = 0; i < n; i++) { diff[i] = y[i] - x[i]; } Arrays.sort(diff); int l = 0, r = n - 1; int ans = 0; while (l < r) { while (l < r && diff[l] + diff[r] < 0) l++; if (l < r) { l++; r--; ans++; } } out.println(ans); } public static void main(String[] args) throws Exception { try (FastIOAdapter ioAdapter = new FastIOAdapter()) { int count = 1; count = ioAdapter.nextInt(); while (count-- > 0) { solve(ioAdapter, ioAdapter.out); } } } static class FastIOAdapter implements AutoCloseable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out)))); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } 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[] readArrayLong(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } @Override public void close() throws Exception { out.flush(); out.close(); br.close(); } } }
Java
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
050c078ca3f069042ceb70ef20b77f9b
train_110.jsonl
1662993300
A group of $$$n$$$ friends decide to go to a restaurant. Each of the friends plans to order meals for $$$x_i$$$ burles and has a total of $$$y_i$$$ burles ($$$1 \le i \le n$$$). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all $$$x_i$$$ values in the group must not exceed the sum of $$$y_i$$$ values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be $$$n = 6$$$ friends for whom $$$x$$$ = [$$$8, 3, 9, 2, 4, 5$$$] and $$$y$$$ = [$$$5, 3, 1, 4, 5, 10$$$]. Then: first and sixth friends can go to the restaurant on the first day. They will spend $$$8+5=13$$$ burles at the restaurant, and their total budget is $$$5+10=15$$$ burles. Since $$$15 \ge 13$$$, they can actually form a group. friends with indices $$$2, 4, 5$$$ can form a second group. They will spend $$$3+2+4=9$$$ burles at the restaurant, and their total budget will be $$$3+4+5=12$$$ burles ($$$12 \ge 9$$$). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is $$$2$$$. Friends will visit the restaurant for a maximum of two days. Note that the $$$3$$$-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given $$$n$$$, $$$x$$$ and $$$y$$$.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ public class D { public static void process() throws IOException { int n = sc.nextInt(); int a[] = sc.readArray(n); int b[] = sc.readArray(n); TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for(int i = 0; i<n; i++)push(map, b[i] - a[i], 1); int ans = 0; while(!map.isEmpty()) { int last = map.lastKey(); pull(map, last, 1); if(last < 0)break; int maxi = -last; if(!map.isEmpty() && map.lastKey() >= maxi) { int my = map.ceilingKey(maxi); pull(map, my, 1); ans++; continue; } break; } System.out.println(ans); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static 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[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = 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[] readArrayDouble(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
["6\n\n6\n\n8 3 9 2 4 5\n\n5 3 1 4 5 10\n\n4\n\n1 2 3 4\n\n1 1 2 2\n\n3\n\n2 3 7\n\n1 3 10\n\n6\n\n2 3 6 9 5 7\n\n3 2 7 10 6 10\n\n6\n\n5 4 2 1 8 100\n\n1 1 1 1 1 200\n\n6\n\n1 4 1 2 4 2\n\n1 3 3 2 3 4"]
2 seconds
["2\n0\n1\n3\n1\n3"]
NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends ($$$1+3+10 \ge 2+3+7$$$). Note that they do not have the option of splitting into two groups.
Java 17
standard input
[ "greedy", "sortings", "two pointers" ]
7c8884b72dcc3c51e0696eec8d6aa8ef
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of friends. The second line of each test case contains exactly $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$). The value of $$$x_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ plans to spend at the restaurant. The third line of each test case contains exactly $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$). The value $$$y_i$$$ corresponds to the number of burles that the friend numbered $$$i$$$ has. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^5$$$.
1,200
For each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.
standard output
PASSED
02b81297f37bdfffcaa61f2556fb7471
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
//package com.example.practice.codeforces.sc2100; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; //G. Cut Substrings public class Solution13 { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { //StringTokenizer st = new StringTokenizer(input.readLine()); //final int n = Integer.parseInt(st.nextToken()); final String ss = input.readLine(); final int[] res = calc(ss, input.readLine()); printArrayInt(res, out); Q--; } out.close(); // close the output file } private static int[] calc(final String ss, final String tt) { final int MODE = 1000000007; final int n = ss.length(), m = tt.length(); ArrayList<Integer> al = new ArrayList<>(); for (int i=0;i<n;++i){ if (ss.substring(i).startsWith(tt)){ al.add(i); } } if (al.isEmpty()){ return new int[]{0, 1}; } int[] dp = new int[al.size()], dp2 = new int[al.size()], nx = new int[al.size()]; for (int i=dp.length-1;i>=0;--i){ int next = i + 1, cur = al.get(i); while (next<dp.length && al.get(next)<cur+m){ next++; } nx[i] = next; dp[i] = dp2[i] = 1 + (next<dp.length ? dp[next] : 0); for (int j=i+1;j<next;++j){ dp[i] = Math.min(dp[i], dp2[j]); } } int[] res = new int[]{dp[0], 0}; Integer[] dp3 = new Integer[dp.length]; res[1] = count(dp, dp2, nx, dp3, 0, MODE); return res; } private static int count(int[] dp, int[] dp2, int[] nx, Integer[] dp3, int idx, final int MODE){ if (idx >= dp3.length)return 1; if (dp3[idx] != null)return dp3[idx]; dp3[idx] = 0; for (int i=idx;i<nx[idx];++i){ if (dp2[i] == dp[idx]){ dp3[idx] += count(dp, dp2, nx, dp3, nx[i], MODE); dp3[idx] = dp3[idx] % MODE; } } return dp3[idx]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int GCD(int x, int y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } private static long GCD(long x, long y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
95177e81d9f992646522414cf99341f6
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Solution { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { //StringTokenizer st = new StringTokenizer(input.readLine()); //final int n = Integer.parseInt(st.nextToken()); final String ss = input.readLine(); final int[] res = calc(ss, input.readLine()); printArrayInt(res, out); Q--; } out.close(); // close the output file } private static int[] calc(final String ss, final String tt) { final int MODE = 1000000007; final int n = ss.length(), m = tt.length(); ArrayList<Integer> al = new ArrayList<>(); for (int i=0;i<n;++i){ if (ss.substring(i).startsWith(tt)){ al.add(i); } } if (al.isEmpty()){ return new int[]{0, 1}; } int[] dp = new int[al.size()], dp2 = new int[al.size()], nx = new int[al.size()]; for (int i=dp.length-1;i>=0;--i){ int next = i + 1, cur = al.get(i); while (next<dp.length && al.get(next)<cur+m){ next++; } nx[i] = next; dp[i] = dp2[i] = 1 + (next<dp.length ? dp[next] : 0); for (int j=i+1;j<next;++j){ dp[i] = Math.min(dp[i], dp2[j]); } } int[] res = new int[]{dp[0], 0}; Integer[] dp3 = new Integer[dp.length]; res[1] = count(dp, dp2, nx, dp3, 0, MODE); return res; } private static int count(int[] dp, int[] dp2, int[] nx, Integer[] dp3, int idx, final int MODE){ if (idx >= dp3.length)return 1; if (dp3[idx] != null)return dp3[idx]; dp3[idx] = 0; for (int i=idx;i<nx[idx];++i){ if (dp2[i] == dp[idx]){ dp3[idx] += count(dp, dp2, nx, dp3, nx[i], MODE); dp3[idx] = dp3[idx] % MODE; } } return dp3[idx]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int GCD(int x, int y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } private static long GCD(long x, long y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } static class BIT{ long[] ns; public BIT(int n){ ns = new long[n]; } void add(int idx, int v){ for (int i=idx; i<ns.length; i += -i & i){ ns[i] += v; } } long get(int idx){ long res = 0; for (int i=idx; i>0; i -= -i & i){ res += ns[i]; } return res; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
76339b75904560597fb4fa2a3a88436d
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
//package com.example.practice.codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Solution { public static void main (String [] args) throws IOException { // Use BufferedReader rather than RandomAccessFile; it's much faster final BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // input file name goes above int Q = Integer.parseInt(input.readLine()); while (Q > 0) { //StringTokenizer st = new StringTokenizer(input.readLine()); //final int n = Integer.parseInt(st.nextToken()); final String ss = input.readLine(); int[] res = calc(ss, input.readLine()); printArrayInt(res, out); Q--; } out.close(); // close the output file } private static int[] calc(final String ss, final String tt) { final int MODE = 1000000007; final int n = ss.length(), m = tt.length(); ArrayList<Integer> al = new ArrayList<>(); for (int i=0;i<n;++i){ if (ss.substring(i).startsWith(tt)){ al.add(i); } } if (al.isEmpty()){ return new int[]{0, 1}; } int[] dp = new int[al.size()], dp2 = new int[al.size()], nx = new int[al.size()]; for (int i=dp.length-1;i>=0;--i){ int next = i + 1, cur = al.get(i); while (next<dp.length && al.get(next)<cur+m){ next++; } nx[i] = next; dp[i] = dp2[i] = 1 + (next<dp.length ? dp[next] : 0); for (int j=i+1;j<next;++j){ dp[i] = Math.min(dp[i], dp2[j]); } } int[] res = new int[]{dp[0], 0}; Integer[] dp3 = new Integer[dp.length]; res[1] = count(dp, dp2, nx, dp3, 0, MODE); return res; } private static int count(int[] dp, int[] dp2, int[] nx, Integer[] dp3, int idx, final int MODE){ if (idx >= dp3.length)return 1; if (dp3[idx] != null)return dp3[idx]; dp3[idx] = 0; for (int i=idx;i<nx[idx];++i){ if (dp2[i] == dp[idx]){ dp3[idx] += count(dp, dp2, nx, dp3, nx[i], MODE); dp3[idx] = dp3[idx] % MODE; } } return dp3[idx]; } private static void printArray(long[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayInt(int[] ns, final PrintWriter out){ for (int i=0;i<ns.length;++i){ out.print(ns[i]); if (i+1<ns.length)out.print(" "); else out.println(); } } private static void printArrayVertical(long[] ns, final PrintWriter out){ for (long a : ns){ out.println(a); } } private static void printArrayVerticalInt(int[] ns, final PrintWriter out){ for (int a : ns){ out.println(a); } } private static void printArray2D(long[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (long[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static void printArray2DInt(int[][] ns, final int len, final PrintWriter out){ int cnt = 0; for (int[] kk : ns){ cnt++; if (cnt > len)break; for (int i=0;i<kk.length;++i){ out.print(kk[i]); if (i+1<kk.length)out.print(" "); else out.println(); } } } private static long[] readArray(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Long.parseLong(st.nextToken()); } return ns; } private static int[] readArrayInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; StringTokenizer st = new StringTokenizer(input.readLine()); for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(st.nextToken()); } return ns; } private static long[] readArrayVertical(final int n, final BufferedReader input) throws IOException{ long[] ns = new long[n]; for (int i=0;i<n;++i){ ns[i] = Long.parseLong(input.readLine()); } return ns; } private static int[] readArrayVerticalInt(final int n, final BufferedReader input) throws IOException{ int[] ns = new int[n]; for (int i=0;i<n;++i){ ns[i] = Integer.parseInt(input.readLine()); } return ns; } private static long[][] readArray2D(final int n, final int len, final BufferedReader input) throws IOException{ long[][] ns = new long[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Long> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Long.parseLong(st.nextToken())); } long[] kk = new long[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int[][] readArray2DInt(final int n, final int len, final BufferedReader input) throws IOException{ int[][] ns = new int[len][]; for (int i=0;i<n;++i){ StringTokenizer st = new StringTokenizer(input.readLine()); ArrayList<Integer> al = new ArrayList<>(); while (st.hasMoreTokens()){ al.add(Integer.parseInt(st.nextToken())); } int[] kk = new int[al.size()]; for (int j=0;j<kk.length;++j){ kk[j] = al.get(j); } ns[i] = kk; } return ns; } private static int GCD(int x, int y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } private static long GCD(long x, long y){ if (x > y)return GCD(y, x); if (x==0)return y; return GCD(y%x, x); } static class SegTree{ int st; int en; int mid; int val1; int val2; SegTree left; SegTree right; public SegTree(int l, int r, int d){ st = l; en = r; mid = (st + en) >> 1; val1 = val2 = d; if (st<en){ left = new SegTree(st, mid, d); right = new SegTree(mid+1, en, d); }else { left = right = null; } } public SegTree(int l, int r, int[] ns){ st = l; en = r; mid = (st + en) >> 1; if (st==en){ val1 = val2 = ns[st]; }else { left = new SegTree(l, mid, ns); right = new SegTree(mid+1, r, ns); val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } void update(int idx, int v){ if (st==en){ val1 = val2 = v; }else { if (idx <= mid){ left.update(idx, v); }else { right.update(idx, v); } val1 = Math.min(left.val1, right.val1); val2 = Math.max(left.val2, right.val2); } } int getMin(int l, int r){ if (st==en || (l==st && r==en))return val1; if (r<=mid){ return left.getMin(l, r); } if (l>mid){ return right.getMin(l, r); } return Math.min(left.getMin(l, mid), right.getMin(mid+1, r)); } int getMax(int l, int r){ if (st==en || (l==st && r==en))return val2; if (r<=mid){ return left.getMax(l, r); } if (l>mid){ return right.getMax(l, r); } return Math.max(left.getMax(l, mid), right.getMax(mid+1, r)); } } static class SparseTable{ int[][] minTable; int[][] maxTable; int[] log2; int n; public SparseTable(final int[] ns){ n = ns.length; int m = 0, pre = 0; while (1<<m < n){ m++; } m++; minTable = new int[n][m]; maxTable = new int[n][m]; log2 = new int[n+1]; for (int i=0;i<n;++i){ minTable[i][0] = ns[i]; maxTable[i][0] = ns[i]; if ((1<<(pre+1)) == i+1){ pre++; } log2[i+1] = pre; } for (int i=1;i<m;++i){ for (int j=0;j<n;++j){ int r = Math.min(n-1, j+(1<<i)-1); if (r-(1<<(i-1))+1 <= j){ minTable[j][i] = minTable[j][i-1]; maxTable[j][i] = maxTable[j][i-1]; }else { minTable[j][i] = Math.min(minTable[j][i-1], minTable[r-(1<<(i-1))+1][i-1]); maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[r-(1<<(i-1))+1][i-1]); } } } } int getMin(final int l, final int r){ int d = log2[r-l+1]; return Math.min(minTable[l][d], minTable[r-(1<<d)+1][d]); } int getMax(final int l, final int r){ int d = log2[r-l+1]; return Math.max(maxTable[l][d], maxTable[r-(1<<d)+1][d]); } } static class BIT{ long[] ns; public BIT(int n){ ns = new long[n]; } void add(int idx, int v){ for (int i=idx; i<ns.length; i += -i & i){ ns[i] += v; } } long get(int idx){ long res = 0; for (int i=idx; i>0; i -= -i & i){ res += ns[i]; } return res; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
91de2ecd4257652dade0bafd8a0b399b
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
/* 8 abababacababa aba ddddddd dddd xyzxyz xyz abc abcd abacaba abaca abc def aaaaaaaa a aaaaaaaa aa 1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaa */ import java.util.*; import java.io.*; public class Main{ public static long mod = 1000000007; //hash using 31? public static long hash = 31; public static long[] pow = new long[501]; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); pow[0] = 1; for(int a = 1; a <= 500; a++) pow[a] = (pow[a-1] * hash) % mod; int nc = Integer.parseInt(br.readLine()); for(int cc = 0; cc < nc; cc++){ char[] str = br.readLine().toCharArray(); int n = str.length; char[] match = br.readLine().toCharArray(); int m = match.length; long mhash = 0; for(int a = 0; a < m; a++){ mhash = (mhash + ((match[a] - 'a' + 1) * pow[m-a-1]) % mod) % mod; } ArrayList<Range> ranges = new ArrayList<Range>(); //already sorted by starting point --> all same size ranges.add(new Range(-1, -1)); int prev = 0; long nhash = 0; for(int a = 0; a < n; a++){ nhash = (nhash * hash) % mod; nhash = (nhash + (str[a] - 'a' + 1)) % mod; while(a-prev+1 > m){ nhash = (nhash - (((str[prev] - 'a' + 1) * pow[a-prev]) % mod) + mod) % mod; prev++; //System.out.println("sub"); } //System.out.println(nhash + " " + mhash + " " + a + " " + prev); if(nhash == mhash){ ranges.add(new Range(prev, a)); } } //System.out.println(ranges); //Look for all ranges that match this string --> dp[a] = min # of steps + total # of ways to delete all occurrences of match in larger string given last occurrence you deleted was at a //find these ranges first, and sort by ending then starting points int[] minWays = new int[ranges.size()]; long[] numWays = new long[ranges.size()]; Arrays.fill(minWays, 501); //delete entire string minWays[0] = 0; numWays[0] = 1; for(int cur = 1; cur < ranges.size(); cur++){ //look at all ranges such that they do not intersect with current range, and that there is no range in between cur and this range that don't intersect either //base case --> have a starting range --> to take care of this add -1, -1 as a range? Range current = ranges.get(cur); //System.out.println("cur range is " + current); Range firstDisjoint = null; //latest earlier range that was disjoint from this one --> can also check all ranges that are connected with this one for(int p = cur - 1; p >= 0; p--){ //already know that prev.start < cur.start --> prev.end < cur.start? Range pv = ranges.get(p); if(firstDisjoint == null && pv.end < current.start){ firstDisjoint = pv; //System.out.println("first disjointed range is " + firstDisjoint); } if(firstDisjoint != null){ //System.out.println(pv); if(pv.end >= firstDisjoint.start){ //intersect if(minWays[cur] > minWays[p] + 1){ minWays[cur] = minWays[p] + 1; numWays[cur] = numWays[p]; } else if(minWays[cur] == minWays[p] + 1){ numWays[cur] = (numWays[cur] + numWays[p]) % mod; } } else break; } } } //System.out.println("min ways " + Arrays.toString(minWays)); //System.out.println("num ways " + Arrays.toString(numWays)); int min = 501; long sm = 0; //look at all ranges such that there is no range in between this range and the end that does not intersect with current range Range last = ranges.get(ranges.size() - 1); for(int p = ranges.size() - 1; p >= 0; p--){ Range pr = ranges.get(p); if(pr.end >= last.start){ if(minWays[p] < min){ min = minWays[p]; sm = numWays[p]; } else if(minWays[p] == min){ sm = (sm + numWays[p]) % mod; } } else break; } sb.append(min + " " + sm + "\n"); } System.out.println(sb.toString()); br.close(); } } class Range{ int start; int end; public Range(int s, int e){ start = s; end = e; } public String toString(){ return start + " " + end; } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
b111bcf3b9e84ce3313f5b99ceb9bdb5
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; public class testing { public static void main(String[] args) throws IOException { FastScanner input = new FastScanner(false); int t = input.nextInt(); //int t=1; PrintWriter out = new PrintWriter(System.out); for (int iter = 1; iter<=t; iter++) { String S = input.nextString(); String T = input.nextString(); int N = S.length(); int M = T.length(); int[] lps = lps(T); int j = 0; boolean[] end = new boolean[N]; boolean[] start = new boolean[N]; for (int i = 0; i<N;) { if (S.charAt(i)==T.charAt(j)) { j++; i++; if (j==M) { j = lps[j]; end[i-1]=true; } } else if (j>0) { j = lps[j]; } else { i++; } } for (int i = 0; i<=N-M; i++) { start[i]=end[i+M-1]; } //System.out.println(Arrays.toString(start)); //System.out.println(Arrays.toString(end)); // min[i]=min possible replacements needed, last replacement at i // num[i]=num possible ways to get min[i] replacements, last replacement at i int[] min = new int[N]; int[] num = new int[N]; Arrays.fill(min,2000000000); Arrays.fill(num,1); ArrayDeque<Integer> cur = new ArrayDeque<>(); for (int i = 0; i<N; i++) { //System.out.println(i+" "+cur); if (end[i]) { if (cur.size()==0) { min[i]=1; num[i]=1; } else { for (int x : cur) { if (min[x]+1==min[i]) num[i]=(num[i]+num[x])%1000000007; else if (min[x]+1<min[i]) { min[i]=min[x]+1; num[i]=num[x]; } } } } if (i-M+1>=0 && end[i-M+1]) cur.addLast(i-M+1); while (!cur.isEmpty() && cur.getFirst()<=cur.getLast()-M) cur.removeFirst(); } int idx = N-1; while (idx>=0 && !end[idx]) idx--; //System.out.println(Arrays.toString(min)); //System.out.println(Arrays.toString(num)); //System.out.println(idx); int minimum = Integer.MAX_VALUE; int number = 1; for (int i = Math.max(0,idx-M+1); i<=idx; i++) { if (end[i]) { if (min[i]<minimum) { minimum=min[i]; number=num[i]; } else if (min[i]==minimum) { number=(number+num[i])%1000000007; } } } if (minimum==Integer.MAX_VALUE) { out.println("0 1"); } else { out.println(minimum+" "+number); } } out.close(); } public static int[] lps(String S) { int[] res = new int[S.length()+1]; res[0]=-1; res[1]=0; int i = 2; int j = 0; while (i<=S.length()) { if (S.charAt(i-1)==S.charAt(j)) { res[i]=j+1; i++; j++; } else if (j>0) { j = res[j]; } else { res[i]=0; i++; } } return res; } private static class FastScanner { final private 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("C:\\Users\\skwek\\IdeaProjects\\HelloWorld\\src\\testing.in")); 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++]; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
8e015d845cdaf36bc612ff7e8f39eb25
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new MainClass().execute(); } } class MainClass extends PrintWriter { MainClass() { super(System.out, true); } boolean cases = true; // Solution char a[], b[]; void solveIt(int testCaseNo) { this.a = sc.next().toCharArray(); this.b = sc.next().toCharArray(); if (a.length < b.length) { System.out.println(0 + " " + 1); return; } List<Integer> al = new ArrayList<>(); for (int i = 0; i <= a.length - b.length; i++) { boolean f = true; for (int j = 0; j < b.length; j++) { if (a[i + j] != b[j]) { f = false; break; } } if (f) al.add(i); } this.dp = new int[al.size() + 1]; Arrays.fill(dp, -1); int min = solve(0, al); this.dp2 = new int[al.size() + 1][min + 1]; for (int d[] : dp2) Arrays.fill(d, -1); System.out.println(min + " " + solve2(0, al, min)); } int dp2[][]; int solve2(int i, List<Integer> al, int k) { if (i >= al.size()) return k == 0 ? 1 : 0; if (k == 0) return 0; if (dp2[i][k] != -1) return dp2[i][k]; int c = 0; int s = i, e = al.size() - 1; int pos = -1; while (s <= e) { int mid = s + (e - s) / 2; if (al.get(mid) <= al.get(i) + b.length - 1) { pos = max(pos, mid); s = mid + 1; } else { e = mid - 1; } } for (int j = i; j <= pos; j++) { s = j; e = al.size() - 1; int x = i; while (s <= e) { int mid = s + (e - s) / 2; if (al.get(mid) <= al.get(j) + b.length - 1) { x = max(x, mid); s = mid + 1; } else { e = mid - 1; } } c += solve2(x + 1, al, k - 1); c %= mod; } return dp2[i][k] = c; } int dp[]; int solve(int i, List<Integer> al) { if (i >= al.size()) return 0; if (dp[i] != -1) return dp[i]; int min = ima; int s = i, e = al.size() - 1; int pos = -1; while (s <= e) { int mid = s + (e - s) / 2; if (al.get(mid) <= al.get(i) + b.length - 1) { pos = max(pos, mid); s = mid + 1; } else { e = mid - 1; } } for (int j = i; j <= pos; j++) { s = j; e = al.size() - 1; int x = i; while (s <= e) { int mid = s + (e - s) / 2; if (al.get(mid) <= al.get(j) + b.length - 1) { x = max(x, mid); s = mid + 1; } else { e = mid - 1; } } min = min(min, 1 + solve(x + 1, al)); } return dp[i] = min; } void solve() { int caseNo = 1; if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); } solveIt(caseNo); } void execute() { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); this.sc = new FastIO(); solve(); out.flush(); long G = System.currentTimeMillis(); sc.tr(G - S + "ms"); } class FastIO { private boolean endOfFile() { if (bufferLength == -1) return true; int lptr = ptrbuf; while (lptr < bufferLength) { // _|_ if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false; } try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!isThisTheSpaceCharacter(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private byte[] inputBufffferBigBoi = new byte[1024]; int bufferLength = 0, ptrbuf = 0; private int justReadTheByte() { if (bufferLength == -1) throw new InputMismatchException(); if (ptrbuf >= bufferLength) { ptrbuf = 0; try { bufferLength = is.read(inputBufffferBigBoi); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLength <= 0) return -1; } return inputBufffferBigBoi[ptrbuf++]; } private boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); } private int skipItBishhhhhhh() { int b; while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b)); return b; } private double nextDouble() { return Double.parseDouble(next()); } private char nextChar() { return (char) skipItBishhhhhhh(); } private String next() { int b = skipItBishhhhhhh(); StringBuilder sb = new StringBuilder(); while (!(isThisTheSpaceCharacter(b))) { sb.appendCodePoint(b); b = justReadTheByte(); } return sb.toString(); } private char[] readCharArray(int n) { char[] buf = new char[n]; int b = skipItBishhhhhhh(), p = 0; while (p < n && !(isThisTheSpaceCharacter(b))) { buf[p++] = (char) b; b = justReadTheByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] readCharMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = readCharArray(m); return map; } private int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } private long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } private int nextInt() { int num = 0, b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private long nextLong() { long num = 0; int b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } } InputStream is; PrintWriter out; String INPUT = ""; final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; final long mod = (long) 1e9 + 7; FastIO sc; } // And I wish you could sing along, But this song is a joke, and the melody I // wrote, wrong
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
436c4887ad9cfb0337db9dd44b1ed8e5
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
// package c1729; // // Codeforces Round #820 (Div. 3) 2022-09-12 07:35 // G. Cut Substrings // https://codeforces.com/contest/1729/problem/G // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given two non-empty strings s and t, consisting of Latin letters. // // In one move, you can choose an occurrence of the string t in the string s and replace it with // dots. // // Your task is to remove all occurrences of the string t in the string s in the minimum number of // moves, and also calculate how many sequences of moves of the minimum length exist. // // Two sequences of moves are considered different if the sets of indices at which the removed // occurrences of the string t in s begin differ. For example, the sets {1, 2, 3} and {1, 2, 4} are // considered different, the sets {2, 4, 6} and {2, 6} -- too, but sets {3, 5} and {5, 3} -- not. // // For example, let the string s = "abababacababa" and the string t = "aba". We can remove all // occurrences of the string t in 2 moves by cutting out the occurrences of the string t at the 3th // and 9th positions. In this case, the string s is an example of the form "ab...bac...ba". It is // also possible to cut occurrences of the string t at the 3th and 11th positions. There are two // different sequences of minimum length moves. // // Since the answer can be large, output it modulo 10^9 + 7. // // Input // // The first line of the input contains a single integer q (1 <= q <= 50)-- the number of test // cases. The descriptions of the sets follow. // // The first line of each set contains a non-empty string s (1 <= |s| <= 500) consisting of // lowercase Latin letters. // // The second line of each set contains a non-empty string t (1 <= |t| <= 500) consisting of // lowercase Latin letters. // // It is guaranteed that the sum of string lengths s over all test cases does not exceed 500. // Similarly, it is guaranteed that the sum of string lengths t over all test cases does not exceed // 500. // // Output // // For each test case print two integers -- the minimum number of moves and the number of different // optimal sequences, modulo 10^9 + 7. // // Example /* input: 8 abababacababa aba ddddddd dddd xyzxyz xyz abc abcd abacaba abaca abc def aaaaaaaa a aaaaaaaa aa output: 2 2 1 4 2 1 0 1 1 1 0 1 8 1 3 6 */ // Note // // The first test case is explained in the statement. // // In the second case, it is enough to cut any of the four occurrences. // // In the third case, string s is the concatenation of two strings t = "xyz", so there is a unique // optimal sequence of 2 moves. // // In the fourth and sixth cases, the string s initially contains no occurrences of the string t. // // In the fifth case, the string s contains exactly one occurrence of the string t. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class C1729G { static final int MOD = 1000000007; static final Random RAND = new Random(); static int[] solve(String s, String t) { int m = s.length(); int n = t.length(); if (m < n) { return new int[] {0, 1}; } else if (m == n) { return s.equals(t) ? new int[] {1, 1} : new int[] {0, 1}; } myAssert(m > n); List<Integer> idxes = indexOf(s, t); if (idxes.isEmpty()) { return new int[] {0, 1}; } int k = idxes.size(); // preidx[i] is the previous chunk that has no overlap with chunk i int[] preidx = new int[k]; { int b = -1; for (int i = 0; i < k; i++) { while (idxes.get(b + 1) + n <= idxes.get(i)) { b++; } preidx[i] = b; } } // dp1[i] is result for prefix [0,i] with i being replaced int[][] dp1 = new int[k][2]; // dp1[i] is result for prefix [0,i] (i is NOT required to be removed) int[][] dp2 = new int[k][2]; for (int i = 0; i < k; i++) { int b = preidx[i]; dp1[i][0] = 1 + (b < 0 ? 0 : dp2[b][0]); dp1[i][1] = (b < 0 ? 1 : dp2[b][1]); // One of [b+1,i] must be replaced, let j be the last one in [b+1,i] that is replaced int minc = k; for (int j = b + 1; j <= i; j++) { minc = Math.min(minc, dp1[j][0]); } dp2[i][0] = minc; for (int j = b + 1; j <= i; j++) { if (dp1[j][0] == minc) { // j is the last one in [b+1,i] that is replaced dp2[i][1] = (dp2[i][1] + dp1[j][1]) % MOD; } } } if (test) { System.out.format(" idxes: %s\n", idxes.toString()); System.out.format(" preifx: %s\n", Arrays.toString(preidx)); System.out.format(" dp1: %s\n", Arrays.deepToString(dp1)); System.out.format(" dp2: %s\n", Arrays.deepToString(dp2)); } return dp2[k-1]; } static List<Integer> indexOf(String s, String t) { List<Integer> ans = new ArrayList<>(); int b = 0; while (b >= 0) { int i = s.indexOf(t, b); if (i < 0) { break; } ans.add(i); b = i + 1; } return ans; } static void test(int[] exp, String s, String t) { int[] ans = solve(s, t); boolean equal = ans[0] == exp[0] && ans[1] == exp[1]; System.out.format("%s %s => %s %s\n", s, t, Arrays.toString(ans), equal ? "" : "expected " + Arrays.toString(exp)); myAssert(equal); } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); test(new int[] {8,1}, "aaaaaaaa", "a"); test(new int[] {2,2}, "abababacababa", "aba"); test(new int[] {1,4}, "ddddddd", "dddd"); test(new int[] {2,1}, "xyzxyz", "xyz"); test(new int[] {0,1}, "abc", "abcd"); test(new int[] {1,1}, "abacaba", "abaca"); test(new int[] {0,1}, "abc", "def"); test(new int[] {8,1}, "aaaaaaaa", "a"); test(new int[] {3,6}, "aaaaaaaa", "aa"); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { String s1 = in.next(); String s2 = in.next(); int[] ans = solve(s1, s2); System.out.format("%d %d\n", ans[0], ans[1]); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
e1b4df21da67cca82f00ad4178945ed0
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
// package c1729; // // Codeforces Round #820 (Div. 3) 2022-09-12 07:35 // G. Cut Substrings // https://codeforces.com/contest/1729/problem/G // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given two non-empty strings s and t, consisting of Latin letters. // // In one move, you can choose an occurrence of the string t in the string s and replace it with // dots. // // Your task is to remove all occurrences of the string t in the string s in the minimum number of // moves, and also calculate how many sequences of moves of the minimum length exist. // // Two sequences of moves are considered different if the sets of indices at which the removed // occurrences of the string t in s begin differ. For example, the sets {1, 2, 3} and {1, 2, 4} are // considered different, the sets {2, 4, 6} and {2, 6} -- too, but sets {3, 5} and {5, 3} -- not. // // For example, let the string s = "abababacababa" and the string t = "aba". We can remove all // occurrences of the string t in 2 moves by cutting out the occurrences of the string t at the 3th // and 9th positions. In this case, the string s is an example of the form "ab...bac...ba". It is // also possible to cut occurrences of the string t at the 3th and 11th positions. There are two // different sequences of minimum length moves. // // Since the answer can be large, output it modulo 10^9 + 7. // // Input // // The first line of the input contains a single integer q (1 <= q <= 50)-- the number of test // cases. The descriptions of the sets follow. // // The first line of each set contains a non-empty string s (1 <= |s| <= 500) consisting of // lowercase Latin letters. // // The second line of each set contains a non-empty string t (1 <= |t| <= 500) consisting of // lowercase Latin letters. // // It is guaranteed that the sum of string lengths s over all test cases does not exceed 500. // Similarly, it is guaranteed that the sum of string lengths t over all test cases does not exceed // 500. // // Output // // For each test case print two integers -- the minimum number of moves and the number of different // optimal sequences, modulo 10^9 + 7. // // Example /* input: 8 abababacababa aba ddddddd dddd xyzxyz xyz abc abcd abacaba abaca abc def aaaaaaaa a aaaaaaaa aa output: 2 2 1 4 2 1 0 1 1 1 0 1 8 1 3 6 */ // Note // // The first test case is explained in the statement. // // In the second case, it is enough to cut any of the four occurrences. // // In the third case, string s is the concatenation of two strings t = "xyz", so there is a unique // optimal sequence of 2 moves. // // In the fourth and sixth cases, the string s initially contains no occurrences of the string t. // // In the fifth case, the string s contains exactly one occurrence of the string t. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class C1729G { static final int MOD = 1000000007; static final Random RAND = new Random(); static int[] solve(String s, String t) { int m = s.length(); int n = t.length(); if (m < n) { return new int[] {0, 1}; } else if (m == n) { return s.equals(t) ? new int[] {1, 1} : new int[] {0, 1}; } myAssert(m > n); List<Integer> idxes = indexOf(s, t); if (idxes.isEmpty()) { return new int[] {0, 1}; } int k = idxes.size(); // preidx[i] is the previous chunk that has no overlap with chunk i int[] preidx = new int[k]; { int b = -1; for (int i = 0; i < k; i++) { while (idxes.get(b + 1) + n <= idxes.get(i)) { b++; } preidx[i] = b; } } // sufidx[i] is the next chunk that has no overlap with chunk i int[] sufidx = new int[k]; { int e = k; for (int i = k - 1; i >= 0; i--) { while (idxes.get(i) + n <= idxes.get(e - 1)) { e--; } sufidx[i] = e; } } int[][] dp1 = new int[k][2]; int[][] dp2 = new int[k][2]; for (int i = 0; i < k; i++) { int b = preidx[i]; dp1[i][0] = 1 + (b < 0 ? 0 : dp2[b][0]); dp1[i][1] = (b < 0 ? 1 : dp2[b][1]); int minc = k; for (int j = b + 1; j <= i; j++) { minc = Math.min(minc, dp1[j][0]); } dp2[i][0] = minc; for (int j = b + 1; j <= i; j++) { if (dp1[j][0] == minc) { dp2[i][1] = (dp2[i][1] + dp1[j][1]) % MOD; } } } if (test) { System.out.format(" idxes: %s\n", idxes.toString()); System.out.format(" preifx: %s\n", Arrays.toString(preidx)); System.out.format(" sufidx: %s\n", Arrays.toString(sufidx)); System.out.format(" dp1: %s\n", Arrays.deepToString(dp1)); System.out.format(" dp2: %s\n", Arrays.deepToString(dp2)); } return dp2[k-1]; /* int[][] pre = new int[k][2]; for (int i = 0; i < k; i++) { int b = preidx[i]; pre[i][0] = 1 + (b < 0 ? 0 : pre[b][0]); pre[i][1] = (b < 0 ? 1 : pre[b][0]); } int[][] suf = new int[k][2]; for (int i = k - 1; i >= 0; i--) { int e = sufidx[i]; suf[i][0] = 1 + (e < k ? suf[e][0] : 0); suf[i][1] = (e < k ? suf[e][0] : 1); } System.out.format(" pre: %s\n", Utils.trace(pre)); System.out.format(" suf: %s\n", Utils.trace(suf)); int minc = k; for (int i = 0; i < k; i++) { int b = preidx[i]; int e = sufidx[i]; int cnt = 1 + (b < 0 ? 0 : pre[b][0]) + (e < k ? suf[e][0] : 0); minc = Math.min(minc, cnt); } long sum = 0; for (int i = 0; i < k; i++) { int b = preidx[i]; int e = sufidx[i]; int cnt = 1 + (b < 0 ? 0 : pre[b][0]) + (e < k ? suf[e][0] : 0); if (cnt == minc) { long v1 = b < 0 ? 1 : pre[b][1]; long v2 = e < k ? suf[e][1] : 1; sum = (sum + v1 * v2) % MOD; } } return new int[] {minc, (int)sum}; */ /* // get minimal number of indexes that collectively overlap with all others // pre[i][0] is the minimal count to take care of prefix [0, idxes[i] + n - 1] and replace chunk i // pre[i][1] is the number of different optional sequences to take care prefix [0, idxes[i] + n - 1] int[][] dp = new int[k][2]; for (int i = 0; i < k; i++) { int b = preidx[i]; // We like to choose ones in [b+1,i] with min count dp[i][0] = 1 + (b < 0 ? 0 : dp[b][0]); dp[i][1] = (b < 0 ? 1 : dp[b][0]); // We like to choose ones in [b+1,i] with min count int minc = dp[b+1][0]; for (int j = b + 1; j <= i; j++) { minc = Math.min(minc, dp[j][0]); } long sum = 0; for (int j = b + 1; j <= i; j++) { if (dp[j][0] == minc) { sum += dp[j][1]; } } dp[i][0] = minc; dp[i][1] = (int) (sum % MOD); System.out.format(" i:%d %s\n", i, Arrays.toString(dp[i])); } System.out.format(" dp: %s\n", Arrays.deepToString(dp)); int b = preidx[k-1]; int minc = dp[k-1][0]; for (int j = b + 1; j < k; j++) { minc = Math.min(minc, dp[j][0]); } long seq = 0; for (int j = b + 1; j < k; j++) { if (dp[j][0] == minc) { seq = (seq + dp[j][1]) % MOD; } } return new int[] {minc, (int) seq}; */ } static List<Integer> indexOf(String s, String t) { List<Integer> ans = new ArrayList<>(); int b = 0; while (b >= 0) { int i = s.indexOf(t, b); if (i < 0) { break; } ans.add(i); b = i + 1; } return ans; } static void test(int[] exp, String s, String t) { int[] ans = solve(s, t); boolean equal = ans[0] == exp[0] && ans[1] == exp[1]; System.out.format("%s %s => %s %s\n", s, t, Arrays.toString(ans), equal ? "" : "expected " + Arrays.toString(exp)); myAssert(equal); } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); test(new int[] {8,1}, "aaaaaaaa", "a"); test(new int[] {2,2}, "abababacababa", "aba"); test(new int[] {1,4}, "ddddddd", "dddd"); test(new int[] {2,1}, "xyzxyz", "xyz"); test(new int[] {0,1}, "abc", "abcd"); test(new int[] {1,1}, "abacaba", "abaca"); test(new int[] {0,1}, "abc", "def"); test(new int[] {8,1}, "aaaaaaaa", "a"); test(new int[] {3,6}, "aaaaaaaa", "aa"); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { String s1 = in.next(); String s2 = in.next(); int[] ans = solve(s1, s2); System.out.format("%d %d\n", ans[0], ans[1]); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
0e0a0e439a862c485cc1cb3f841a10cb
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.PrintWriter; import java.util.*; public class G { private static final int MAX_LENGTH = 500; public static void main(String[] args) { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int tests = sc.nextInt(); for (int t = 0; t < tests; t++) { solve(sc, pw); } sc.close(); pw.close(); } static void solve(Scanner sc, PrintWriter pw) { String s = sc.next(); String t = sc.next(); List<Occurrence> occurrences = new ArrayList<>(); for (int i = 0; i <= s.length() - t.length(); i++) { boolean validStartPosition = true; for (int j = 0; j < t.length(); j++) { if (s.charAt(i + j) != t.charAt(j)) { validStartPosition = false; break; } } if (validStartPosition) { occurrences.add(new Occurrence(i)); } } Occurrence finalResult = new Occurrence(MAX_LENGTH); occurrences.add(finalResult); // we can start from any occurrence that intersect with first occurrence for (int i = 0; i < occurrences.size(); i++) { Occurrence current = occurrences.get(i); if (current.idx < occurrences.get(0).idx + t.length()) { current.minMoves = 0; current.addWay(1); } else break; } for (int i = 0; i < occurrences.size() - 1; i++) { Occurrence current = occurrences.get(i); // find first occurrence that does not intersect with current int nextNotCrossIdx = i + 1; Occurrence nextNotCross = occurrences.get(nextNotCrossIdx); while (nextNotCross.idx < current.idx + t.length()) { nextNotCrossIdx++; nextNotCross = occurrences.get(nextNotCrossIdx); } // find all occurrences that intersect with nextNotCross (including nextNotCross) and update them int nextCrossIdx = nextNotCrossIdx; while (nextCrossIdx < occurrences.size()) { Occurrence nextCross = occurrences.get(nextCrossIdx); if (nextCross.idx < nextNotCross.idx + t.length()) { nextCross.addPredecessor(current); nextCross.minMoves = Math.min(nextCross.minMoves, current.minMoves + 1); } else { break; } nextCrossIdx++; } } // update ways for each occurrence occurrences.forEach(current -> current.predecessors.forEach(predecessor-> { if (predecessor.minMoves + 1 == current.minMoves) { current.addWay(predecessor.getWaysCount()); } })); pw.println(finalResult.minMoves + " " + finalResult.waysCount); } static class Occurrence { // start position of occurrences t in string S int idx; // minimum number of moves (remove occurrences of string t in string s) we should do to achieve current idx int minMoves = MAX_LENGTH; // list of previous start position from which we can jump to current position List<Occurrence> predecessors = new ArrayList<>(); // number of ways we can achieve current position with minimum moves private int waysCount; Occurrence(int idx) { this.idx = idx; } void addPredecessor(Occurrence predecessor) { predecessors.add(predecessor); } void addWay(int newWays) { waysCount += newWays; if (waysCount > 1e9 + 7) { waysCount -= 1e9 + 7; } } int getWaysCount() { return waysCount; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
dae08f93f73939f5d2f01a18d06f309d
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Main { static final long MOD1=1000000007; static final long MOD=998244353; static final int NTT_MOD1 = 998244353; static final int NTT_MOD2 = 1053818881; static final int NTT_MOD3 = 1004535809; static long MAX = 1000000000000000000l;//10^18 static int index = 2; public static void main(String[] args){ PrintWriter out = new PrintWriter(System.out); InputReader sc=new InputReader(System.in); int t = sc.nextInt(); long MOD = 1000000007; for (int i = 0; i < t; i++) { String S = sc.next(); String T = sc.next(); out.println(solve(S, T, MOD)); } out.flush(); } static String solve(String S, String T, long MOD) { StringBuilder sb = new StringBuilder(T); sb.append("#"); sb.append(S); int n = S.length(); int m = T.length(); int[] Z = StringAlgorithm.zAlgorithm(String.valueOf(sb)); long[][] dp = new long[n + 1][n + 1]; dp[0][0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) { if(dp[i][j] == 0) continue; if (Z[m + 1 + i] == m) { for (int j2 = 0; j2 < m; j2++) { if (i + j2 < n && Z[m + 1 + i + j2] == m) { dp[i + j2 + m][j + 1] = (dp[i + j2 + m][j + 1] + dp[i][j]) % MOD; } } }else { dp[i + 1][j] = (dp[i + 1][j] + dp[i][j]) % MOD; } } } for (int i = 0; i <= n; i++) { if (dp[n][i] > 0) { return i + " " + dp[n][i]; } } return null; } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } } //StringAlgorithm.methodで使う class StringAlgorithm { private static int[] saNaive(int[] s) { int n = s.length; Integer[] _sa = new Integer[n]; for (int i = 0; i < n; i++) { _sa[i] = i; } java.util.Arrays.sort(_sa, (l, r) -> { while (l < n && r < n) { if (s[l] != s[r]) return s[l] - s[r]; l++; r++; } return -(l - r); }); int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = _sa[i]; } return sa; } private static int[] saDoubling(int[] s) { int n = s.length; Integer[] _sa = new Integer[n]; for (int i = 0; i < n; i++) { _sa[i] = i; } int[] rnk = s; int[] tmp = new int[n]; for (int k = 1; k < n; k *= 2) { final int _k = k; final int[] _rnk = rnk; java.util.Comparator<Integer> cmp = (x, y) -> { if (_rnk[x] != _rnk[y]) return _rnk[x] - _rnk[y]; int rx = x + _k < n ? _rnk[x + _k] : -1; int ry = y + _k < n ? _rnk[y + _k] : -1; return rx - ry; }; java.util.Arrays.sort(_sa, cmp); tmp[_sa[0]] = 0; for (int i = 1; i < n; i++) { tmp[_sa[i]] = tmp[_sa[i - 1]] + (cmp.compare(_sa[i - 1], _sa[i]) < 0 ? 1 : 0); } int[] buf = tmp; tmp = rnk; rnk = buf; } int[] sa = new int[n]; for (int i = 0; i < n; i++) { sa[i] = _sa[i]; } return sa; } private static final int THRESHOLD_NAIVE = 10; private static final int THRESHOLD_DOUBLING = 40; private static int[] sais(int[] s, int upper) { int n = s.length; if (n == 0) return new int[0]; if (n == 1) return new int[]{0}; if (n == 2) { if (s[0] < s[1]) { return new int[]{0, 1}; } else { return new int[]{1, 0}; } } if (n < THRESHOLD_NAIVE) { return saNaive(s); } if (n < THRESHOLD_DOUBLING) { return saDoubling(s); } int[] sa = new int[n]; boolean[] ls = new boolean[n]; for (int i = n - 2; i >= 0; i--) { ls[i] = s[i] == s[i + 1] ? ls[i + 1] : s[i] < s[i + 1]; } int[] sumL = new int[upper + 1]; int[] sumS = new int[upper + 1]; for (int i = 0; i < n; i++) { if (ls[i]) { sumL[s[i] + 1]++; } else { sumS[s[i]]++; } } for (int i = 0; i <= upper; i++) { sumS[i] += sumL[i]; if (i < upper) sumL[i + 1] += sumS[i]; } java.util.function.Consumer<int[]> induce = lms -> { java.util.Arrays.fill(sa, -1); int[] buf = new int[upper + 1]; System.arraycopy(sumS, 0, buf, 0, upper + 1); for (int d : lms) { if (d == n) continue; sa[buf[s[d]]++] = d; } System.arraycopy(sumL, 0, buf, 0, upper + 1); sa[buf[s[n - 1]]++] = n - 1; for (int i = 0; i < n; i++) { int v = sa[i]; if (v >= 1 && !ls[v - 1]) { sa[buf[s[v - 1]]++] = v - 1; } } System.arraycopy(sumL, 0, buf, 0, upper + 1); for (int i = n - 1; i >= 0; i--) { int v = sa[i]; if (v >= 1 && ls[v - 1]) { sa[--buf[s[v - 1] + 1]] = v - 1; } } }; int[] lmsMap = new int[n + 1]; java.util.Arrays.fill(lmsMap, -1); int m = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lmsMap[i] = m++; } } int[] lms = new int[m]; { int p = 0; for (int i = 1; i < n; i++) { if (!ls[i - 1] && ls[i]) { lms[p++] = i; } } } induce.accept(lms); if (m > 0) { int[] sortedLms = new int[m]; { int p = 0; for (int v : sa) { if (lmsMap[v] != -1) { sortedLms[p++] = v; } } } int[] recS = new int[m]; int recUpper = 0; recS[lmsMap[sortedLms[0]]] = 0; for (int i = 1; i < m; i++) { int l = sortedLms[i - 1], r = sortedLms[i]; int endL = (lmsMap[l] + 1 < m) ? lms[lmsMap[l] + 1] : n; int endR = (lmsMap[r] + 1 < m) ? lms[lmsMap[r] + 1] : n; boolean same = true; if (endL - l != endR - r) { same = false; } else { while (l < endL && s[l] == s[r]) { l++; r++; } if (l == n || s[l] != s[r]) same = false; } if (!same) { recUpper++; } recS[lmsMap[sortedLms[i]]] = recUpper; } int[] recSA = sais(recS, recUpper); for (int i = 0; i < m; i++) { sortedLms[i] = lms[recSA[i]]; } induce.accept(sortedLms); } return sa; } public static int[] suffixArray(int[] s, int upper) { assert (0 <= upper); for (int d : s) { assert (0 <= d && d <= upper); } return sais(s, upper); } public static int[] suffixArray(int[] s) { int n = s.length; Integer[] idx = new Integer[n]; for (int i = 0; i < n; i++) { idx[i] = i; } java.util.Arrays.sort(idx, (l, r) -> s[l] - s[r]); int[] s2 = new int[n]; int now = 0; for (int i = 0; i < n; i++) { if (i > 0 && s[idx[i - 1]] != s[idx[i]]) { now++; } s2[idx[i]] = now; } return sais(s2, now); } public static int[] suffixArray(char[] s) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return sais(s2, 255); } public static int[] suffixArray(java.lang.String s) { return suffixArray(s.toCharArray()); } public static int[] lcpArray(int[] s, int[] sa) { int n = s.length; assert (n >= 1); int[] rnk = new int[n]; for (int i = 0; i < n; i++) { rnk[sa[i]] = i; } int[] lcp = new int[n - 1]; int h = 0; for (int i = 0; i < n; i++) { if (h > 0) h--; if (rnk[i] == 0) { continue; } int j = sa[rnk[i] - 1]; for (; j + h < n && i + h < n; h++) { if (s[j + h] != s[i + h]) break; } lcp[rnk[i] - 1] = h; } return lcp; } public static int[] lcpArray(char[] s, int[] sa) { int n = s.length; int[] s2 = new int[n]; for (int i = 0; i < n; i++) { s2[i] = s[i]; } return lcpArray(s2, sa); } public static int[] lcpArray(java.lang.String s, int[] sa) { return lcpArray(s.toCharArray(), sa); } public static int[] zAlgorithm(int[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(char[] s) { int n = s.length; if (n == 0) return new int[0]; int[] z = new int[n]; for (int i = 1, j = 0; i < n; i++) { int k = j + z[j] <= i ? 0 : Math.min(j + z[j] - i, z[i - j]); while (i + k < n && s[k] == s[i + k]) k++; z[i] = k; if (j + z[j] < i + z[i]) j = i; } z[0] = n; return z; } public static int[] zAlgorithm(String s) { return zAlgorithm(s.toCharArray()); } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
2449d21f8fac76a1c8521ca1f39701e1
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
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.List; import java.util.StringTokenizer; public class Main { static AReader scan = new AReader(); static int MOD = (int)1e9 + 7; static void solve() throws IOException { String s = scan.next(); String t = scan.next(); List<Integer> list = new ArrayList<>(); list.add(0); int n = s.length(); int m = t.length(); for(int i = 0;i + m - 1<s.length();i++){ boolean flag = true; for(int j = 1;j<=m;j++){ if(s.charAt(i + j -1) != t.charAt(j-1)){ flag = false; break; } } if(flag) list.add(i + m); } int[] dp = new int[list .size()]; long[] f = new long[list.size()]; Arrays.fill(dp,0x3f3f3f3f); dp[0] = 0;f[0] = 1; for(int i = 1;i<list.size();i++){ for(int j = 0;j<i;j++){ if(list.get(i) - list.get(j) < m) continue; boolean flag = true; for(int k = j + 1;k<i;k++){ if(list.get(i) - list.get(k) >= m && list.get(k) - list.get(j) >= m){ flag = false; break; } } if(!flag) continue; if(dp[i] > dp[j] + 1) { dp[i] = dp[j] + 1; f[i] = f[j]; }else if(dp[i] == dp[j] + 1){ f[i] = (f[i] + f[j]) % MOD; } } } int min = 0x3f3f3f3f; long ans = 0; for(int i = 0;i<list.size();i++){ if(list.get(list.size() - 1) - list.get(i) < m) min = Math.min(min,dp[i]); } for(int i = 0;i<list.size();i++){ if(list.get(list.size() - 1) - list.get(i) < m && dp[i] == min){ ans = (ans + f[i]) % MOD; } } System.out.printf("%d %d\n",min,ans); } public static void main(String[] args) throws IOException { int T = scan.nextInt(); while (T-- > 0) { solve(); } } } class Pair{ int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } } class Solution { int MOD = (int)1e9+7; public int numberOfPaths(int[][] grid, int K) { int n = grid.length; int m = grid[0].length; long[][][] dp = new long[n+10][m+10][K]; dp[1][1][grid[0][0] % K] = 1; for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ for(int k = 0;k<K;k++){ int x = grid[i-1][j-1]; int p = ((k - x) % K + K) % K; dp[i][j][k] = dp[i-1][j][p]; dp[i][j][k] = (dp[i][j][k] + dp[i][j-1][p]) % MOD; } } } return (int)dp[n][m][0]; } } 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()); } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
f02a081f7441ce7e10cde690c3c8bbbc
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class G_Cut_Substrings { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } static String str,pat; static boolean arr[]; static int dp1[],len; static long dp2[][],mod; public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int test=input.scanInt(); for(int tt=1;tt<=test;tt++) { str=input.scanString(); pat=input.scanString(); arr=new boolean[str.length()]; for(int i=0;i+pat.length()-1<str.length();i++) { String tmp=str.substring(i, i+pat.length()); if(tmp.equals(pat)) { arr[i]=true; } } mod=1000000007L; dp1=new int[str.length()+5]; Arrays.fill(dp1, -1); len=solve_min(0); dp2=new long[str.length()+5][str.length()+5]; for(int i=0;i<dp2.length;i++) { for(int j=0;j<dp2[0].length;j++) { dp2[i][j]=-1; } } long cnt=solve_ways(0,0); ans.append(len+" "+cnt+"\n"); } System.out.print(ans); } public static int solve_min(int indx) { if(indx==str.length()) { return 0; } if(dp1[indx]!=-1) { return dp1[indx]; } int ans=Integer.MAX_VALUE/10; // System.out.println(str.length()+" "+indx); if(arr[indx]) { for(int i=indx;i<str.length() && i<indx+pat.length();i++) { if(arr[i]) { // System.out.println("\t"+i); ans=Math.min(ans,1+solve_min(i+pat.length())); } } } else { ans=Math.min(ans,solve_min(indx+1)); } dp1[indx]=ans; return ans; } public static long solve_ways(int indx,int cnt) { if(indx==str.length()) { if(cnt==len) { return 1; } return 0; } if(dp2[indx][cnt]!=-1) { return dp2[indx][cnt]; } long ans=0; if(arr[indx]) { for(int i=indx;i<str.length() && i<indx+pat.length();i++) { if(arr[i]) { ans+=solve_ways(i+pat.length(),cnt+1); } } } else { ans+=solve_ways(indx+1,cnt); } ans%=mod; dp2[indx][cnt]=ans; return ans; } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
c20dfe754d41425a912d54eb496cf99f
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; public class g { static int an; static int bn; static boolean[] valid; static long[][][] memo; static final long[] BASE = new long[] {0, 1}; static final long MOD = 1_000_000_007L; public static void main(String[] args) { Scanner in = new Scanner(System.in); int numT = in.nextInt(); for (int ci = 0; ci < numT; ci++) { String a = in.next(); String b = in.next(); an = a.length(); bn = b.length(); valid = new boolean[an]; for (int i = 0; i < an; i++) { valid[i] = a.startsWith(b, i); } memo = new long[an][an][]; long[] ans = go(0, an - 1); System.out.printf("%d %d\n", ans[0], ans[1]); } } static long[] go(int i, int j) { if (i > j) { return BASE; } if (memo[i][j] != null) { return memo[i][j]; } long min = Long.MAX_VALUE; long num = 1; for (int k = i; k <= j - bn + 1; k++) { if (valid[k]) { long[] left = go(i, k - 1); if (left[0] > 0) { break; } long[] right = go(k + bn, j); long minn = left[0] + right[0] + 1; if (minn < min) { min = minn; num = (left[1] * right[1]) % MOD; } else if (minn == min) { num = (num + left[1] * right[1]) % MOD; } } } if (min == Long.MAX_VALUE) { min = 0; } return memo[i][j] = new long[] {min, num}; } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
69b7ad414288bd36e763762d756992b8
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; public class G { static IOHandler sc = new IOHandler(); static int mod = 1_000_000_007; static long [][][] memo; public static void main(String[] args) { // TODO Auto-generated method stub int testCases = sc.nextInt(); for (int i = 1; i <= testCases; ++i) { solve(i); } } private static void solve(int t) { String s = sc.next(); String st = sc.next(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < s.length(); ++i) { if (s.substring(i).startsWith(st)) { list.add(i); } } int [] next = new int [list.size()]; Arrays.fill(next, list.size()); int idx = 0; for (int i = 0; i < list.size(); ++i) { while (list.get(i) - list.get(idx) >= st.length()) { next[idx++] = i; } } memo = new long [list.size()][list.size()][]; long [] res = solve(list, 0 , 0, st.length(), next); System.out.println(res[0] + " " + res[1]); } // total, ways private static long [] solve(List<Integer> list, int l, int r, int len, int [] next) { long [] result = new long [2]; if (r == list.size()) { if (l != r) return null; result[1] = 1; return result; }else if (list.get(r) - list.get(l) >= len) { return null; }else if (memo[l][r] != null) return memo[l][r]; long [] skip = solve(list, l , r + 1, len, next); long [] vals = solve(list, next[r], next[r], len, next); result[0] = vals[0] + 1; result[1] = vals[1]; if (skip != null && result[0] == skip[0]) { result[1] += skip[1]; }else if (skip != null && result[0] > skip[0]) { result[0] = skip[0]; result[1] = skip[1]; } result[1] %= mod; memo[l][r] = result; return result; } private static class IOHandler { BufferedReader br; StringTokenizer st; public IOHandler() { 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()); } int [] readArray(int n) { int [] res = new int [n]; for (int i = 0; i < n; ++i) res[i] = nextInt(); return res; } 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
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 11
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
2e01f0288c667bf2a1b44a08c5693099
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
//package codeforces.round820div3; import java.io.*; import java.util.*; import static java.lang.Math.*; public class G { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int mod = (int)1e9 + 7, n; static List<int[]> idx; static int[] rightMostSmallerNonOverlap, leftMostBiggerNonOverlap; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { String s = in.next(), t = in.next(); if(s.length() < t.length()) { out.println(0 + " " + 1); } else { n = s.length(); idx = new ArrayList<>(); int i = 0; while(i <= s.length() - t.length()) { int j = s.indexOf(t, i); if(j < 0) break; idx.add(new int[]{j, j + t.length() - 1}); i = j + 1; } rightMostSmallerNonOverlap = new int[n]; leftMostBiggerNonOverlap = new int[n]; // Arrays.fill(rightMostNonOverlap, Integer.MIN_VALUE); // Arrays.fill(leftMostNonOverlap, Integer.MAX_VALUE); long minMoves = 0, numMoves = 1; int prev = 0; for(int k = 0; k < idx.size() - 1; k++) { if(idx.get(k)[1] < idx.get(k + 1)[0]) { long[] ans = compute(prev, k); minMoves += ans[0]; numMoves = numMoves * ans[1] % mod; prev = k + 1; } } if(prev <= idx.size() - 1) { long[] ans = compute(prev, idx.size() - 1); minMoves += ans[0]; numMoves = numMoves * ans[1] % mod; } out.println(minMoves + " " + numMoves); } } out.close(); } static long[] compute(int l, int r) { //int[][] minMovesDp; //minMovesDp[i][j]: the min moves needed to remove entries in [i, j] int cnt = r - l + 1; int[][] minMovesDp = new int[cnt][cnt]; for(int i = 0; i < minMovesDp.length; i++) { Arrays.fill(minMovesDp[i], -1); } for(int i = l; i <= r; i++) { rightMostSmallerNonOverlap[i] = bsOnLeft(l, r, i); leftMostBiggerNonOverlap[i] = bsOnRight(l, r, i); } computeMinMoves(l, r, l, minMovesDp); int minMoves = minMovesDp[0][r - l]; long[][] minMoveSeqCnt = new long[cnt][cnt]; for(int i = 0; i < minMoveSeqCnt.length; i++) { Arrays.fill(minMoveSeqCnt[i], -1); } long seqCnt = computeNumOfSeq(l, r, l, minMovesDp, minMoveSeqCnt); return new long[]{minMoves, seqCnt}; } static long computeNumOfSeq(int l, int r, int offset, int[][] minMovesDp, long[][] minMoveSeqCnt) { if(l > r) return 1; if(minMoveSeqCnt[l - offset][r - offset] < 0) { long cnt = 0; // int leftMostNonOverlap = l + 1; // for (; leftMostNonOverlap <= r && idx.get(leftMostNonOverlap)[0] <= idx.get(l)[1]; leftMostNonOverlap++) { // } int leftMostNonOverlap = leftMostBiggerNonOverlap[l]; for (int i = l; i < leftMostNonOverlap; i++) { //int j = i; //for(; j <= r && idx.get(j)[0] <= idx.get(i)[1]; j++) {} //int j = bsOnRight(l, r, i); int j = leftMostBiggerNonOverlap[i]; int remainMoves = j <= r ? minMovesDp[j - offset][r - offset] : 0; if (remainMoves + 1 == minMovesDp[l - offset][r - offset]) { cnt = (cnt + computeNumOfSeq(j, r, offset, minMovesDp, minMoveSeqCnt)) % mod; } } minMoveSeqCnt[l - offset][r - offset] = cnt; } return minMoveSeqCnt[l - offset][r - offset]; } static int bsOnRight(int l, int r, int i) { while(l < r - 1) { int mid = l + (r - l) / 2; if(idx.get(mid)[0] > idx.get(i)[1]) { r = mid; } else { l = mid + 1; } } if(idx.get(l)[0] > idx.get(i)[1]) { return l; } else if(idx.get(r)[0] > idx.get(i)[1]) { return r; } return r + 1; } static int bsOnLeft(int l, int r, int i) { while(l < r - 1) { int mid = l + (r - l) / 2; if(idx.get(mid)[1] < idx.get(i)[0]) { l = mid; } else { r = mid - 1; } } if(idx.get(r)[1] < idx.get(i)[0]) { return r; } else if(idx.get(l)[1] < idx.get(i)[0]) { return l; } return l - 1; } static int computeMinMoves(int l, int r, int offset, int[][] minMovesDp) { int i = l - offset, j = r - offset; if(i > j) return 0; if(minMovesDp[i][j] < 0) { minMovesDp[i][j] = idx.size() + 1; for(int k = l; k <= r; k++) { // int j1 = k - 1; // for(; j1 >= l && idx.get(j1)[1] >= idx.get(k)[0]; j1--) {} // int j1 = bsOnLeft(l, r, k); int j1 = rightMostSmallerNonOverlap[k]; int leftMoves = computeMinMoves(l, j1, offset, minMovesDp); // int j2 = k + 1; // for(; j2 <= r && idx.get(j2)[0] <= idx.get(k)[1]; j2++) {} // int j2 = bsOnRight(l, r, k); int j2 = leftMostBiggerNonOverlap[k]; int rightMoves = computeMinMoves(j2, r, offset, minMovesDp); minMovesDp[i][j] = min(minMovesDp[i][j], 1 + leftMoves + rightMoves); } } return minMovesDp[i][j]; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } 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; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<Integer>[] readGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
d2bea30e52a666113e811ba111ff858c
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; /* */ public class G{ static FastReader sc=null; public static void main(String[] args) { sc=new FastReader(); int t=sc.nextInt(); for(int tt=0;tt<t;tt++) { char a[]=sc.next().toCharArray(),b[]=sc.next().toCharArray(); int n=a.length,m=b.length; ArrayList<Integer> Ls=new ArrayList<>(); for(int i=0;i+m<=n;i++) { boolean same=true; for(int j=0;j<m;j++)same&=(a[i+j]==b[j]); if(same)Ls.add(i); } //System.out.println(Ls.toString()); //dp[i][j] -> no of ways to cover prefix until i in j ways n=Ls.size(); if(n==0) { System.out.println(0+" "+1); continue; } long dp[][]=new long[n][n+1]; dp[0][0]=1; for(int i=0;i<Ls.size();i++)if(Ls.get(i)<=Ls.get(0)+m-1)dp[i][1]=1; for(int i=1;i<n;i++) { for(int j=2;j<=n;j++) { for(int k=0,c=0;k<i;k++) { while(c<n && Ls.get(c)<Ls.get(k)+m)c++; if(c==Ls.size()) { //out of bounds already break; } int right=Ls.get(c)+m-1; if(right>=Ls.get(i) && right<=Ls.get(i)+m-1) { dp[i][j]=add(dp[i][j],dp[k][j-1]); } } } } int ans=0; long cnt=1; int last=Ls.get(n-1); for(int i=1;i<=n;i++) { long cur_cnt=0; for(int j=0;j<n;j++) { if(Ls.get(j)+m>last){ cur_cnt=add(cur_cnt,dp[j][i]); } } if(cur_cnt>0) { cnt=cur_cnt; ans=i; break; } } System.out.println(ans+" "+cnt); } } static long mod=(long)1e9+7; static long add(long a,long b) { a+=b; if(a>=mod)a-=mod; return a; } static int[] ruffleSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al); for(int i=0;i<a.length;i++)a[i]=al.get(i); return a; } static void print(int a[]) { for(int e:a) { System.out.print(e+" "); } System.out.println(); } static class FastReader{ StringTokenizer st=new StringTokenizer(""); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); return a; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
a57d1b6e07b63715b6a60e4792d2f3c6
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; /* */ public class G{ static FastReader sc=null; public static void main(String[] args) { sc=new FastReader(); int t=sc.nextInt(); for(int tt=0;tt<t;tt++) { char a[]=sc.next().toCharArray(),b[]=sc.next().toCharArray(); int n=a.length,m=b.length; ArrayList<Integer> Ls=new ArrayList<>(); for(int i=0;i+m<=n;i++) { boolean same=true; for(int j=0;j<m;j++)same&=(a[i+j]==b[j]); if(same)Ls.add(i); } //System.out.println(Ls.toString()); //dp[i][j] -> no of ways to cover prefix until i in j ways n=Ls.size(); if(n==0) { System.out.println(0+" "+1); continue; } long dp[][]=new long[n][n+1]; dp[0][0]=1; for(int i=0;i<Ls.size();i++)if(Ls.get(i)<=Ls.get(0)+m-1)dp[i][1]=1; for(int i=1;i<n;i++) { for(int j=2;j<=n;j++) { for(int k=0,c=0;k<i;k++) { while(c<n && Ls.get(c)<Ls.get(k)+m)c++; if(c==Ls.size()) { //out of bounds already break; } int right=Ls.get(c)+m-1; if(right>=Ls.get(i) && right<=Ls.get(i)+m-1) { dp[i][j]=add(dp[i][j],dp[k][j-1]); } } } } //for(int i=0;i<n;i++)print(dp[i]); int ans=0; long cnt=1; int last=Ls.get(n-1); for(int i=1;i<=n;i++) { long cur_cnt=0; for(int j=0;j<n;j++) { if(Ls.get(j)+m>last){ cur_cnt=add(cur_cnt,dp[j][i]); } } if(cur_cnt>0) { cnt=cur_cnt; ans=i; break; } } System.out.println(ans+" "+cnt); } } static long mod=(long)1e9+7; static long add(long a,long b) { a+=b; if(a>=mod)a-=mod; return a; } static int bs(ArrayList<Integer> a,int k) { int l=-1,r=a.size(); while(l+1<r) { int mid=(l+r)/2; if(a.get(mid)<k)l=mid; else r=mid; } return r; } static int[] ruffleSort(int a[]) { ArrayList<Integer> al=new ArrayList<>(); for(int i:a)al.add(i); Collections.sort(al); for(int i=0;i<a.length;i++)a[i]=al.get(i); return a; } static void print(int a[]) { for(int e:a) { System.out.print(e+" "); } System.out.println(); } static class FastReader{ StringTokenizer st=new StringTokenizer(""); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); return a; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
c94c253eac237e8bc911674a530be1fc
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Nervose.Wu * @date 2022/10/3 12:27 */ public final class S820G { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); // write here int mod = (int) (1e9 + 7); for (int testNo = sc.nextInt(); testNo > 0; testNo--) { String s = sc.next(); int sLen = s.length(); String t = sc.next(); int tLen = t.length(); int[][] dict = new int[sLen][tLen]; for (int i = sLen - 1; i >= 0; i--) { for (int j = tLen - 1; j >= 0; j--) { if (s.charAt(i) == t.charAt(j)) { dict[i][j] = 1 + (i + 1 < sLen && j + 1 < tLen ? dict[i + 1][j + 1] : 0); } else { dict[i][j] = 0; } } } //dpOperations[i]表示[i,sLen)范围内最前操作位为j时,为满足要求的最少操作次数 int[][] dpOperations = new int[sLen + 1][sLen + 1]; for (int[] cur : dpOperations) Arrays.fill(cur, 501); dpOperations[sLen][sLen] = 0; //dp[i][j]表示[i,sLen)范围内,最先操作位为j时的操作种数 long[][] dpCount = new long[sLen + 1][sLen + 1]; dpCount[sLen][sLen] = 1; for (int i = sLen - 1; i >= 0; i--) { if (dict[i][0] == tLen) { //在该位置添加 for (int j = i + tLen; j <= sLen; j++) { if (dpCount[i + tLen][j] > 0) { if (dpOperations[i][i] == dpOperations[i + tLen][j] + 1) { dpCount[i][i] = (dpCount[i][i] + dpCount[i + tLen][j]) % mod; } else if (dpOperations[i][i] > dpOperations[i + tLen][j] + 1) { dpOperations[i][i] = dpOperations[i + tLen][j] + 1; dpCount[i][i] = dpCount[i + tLen][j]; } } } //不在该位置添加 for (int j = i + 1; j < Math.min(i + tLen, sLen + 1); j++) { if (dpCount[i + 1][j] > 0) { if (dpOperations[i][j] == dpOperations[i + 1][j]) { dpCount[i][j] = (dpCount[i][j] + dpCount[i + 1][j]) % mod; } else if (dpOperations[i][j] > dpOperations[i + 1][j]) { dpOperations[i][j] = dpOperations[i + 1][j]; dpCount[i][j] = dpCount[i + 1][j]; } } } } else { for (int j = i + 1; j <= sLen; j++) { if (dpCount[i + 1][j] > 0) { if (dpOperations[i][j] == dpOperations[i + 1][j]) { dpCount[i][j] = (dpCount[i][j] + dpCount[i + 1][j]) % mod; } else if (dpOperations[i][j] > dpOperations[i + 1][j]) { dpOperations[i][j] = dpOperations[i + 1][j]; dpCount[i][j] = dpCount[i + 1][j]; } } } } } int nOperation=501; long count=0; for(int i=0;i<=sLen;i++){ if(dpOperations[0][i]<nOperation){ nOperation=dpOperations[0][i]; count=dpCount[0][i]; }else if(dpOperations[0][i]==nOperation){ count=(count+dpCount[0][i])%mod; } } out.println(nOperation+" "+count); } out.close(); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
d96e8f758689baff0e10c428c35546f3
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
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; /* DP[index1][prefixMatch] = minCost,nways Find the times it occurs We need to pick at least one of each 1 aaaaa aa */ public class G { static Pair[] dp; static char[] big; static char[] small; static ArrayList<Integer> occs=new ArrayList<>(); public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { big=fs.next().toCharArray(); small=fs.next().toCharArray(); // dp=new Pair[big.length+1][small.length+1][big.length+1]; occs=new ArrayList<>(); outer: for (int i=0; i<big.length; i++) { for (int j=0; j<small.length; j++) { if (i+j>=big.length || big[i+j]!=small[j]) continue outer; } occs.add(i); } dp=new Pair[big.length+1]; Pair ans=go(0); out.println(ans.minMoves+" "+ans.nWays%mod); } out.close(); } //going to have to speed this up by doing it iteratively... :( static Pair go(int atIndex) { if (dp[atIndex]!=null) return dp[atIndex]; if (atIndex==occs.size()) return new Pair(0, 1); //otherwise pick someone to lose Pair best=null; for (int toKill=atIndex; toKill<occs.size(); toKill++) { int curPos=occs.get(atIndex), next=occs.get(toKill); //killing next wouldn't help us if (Math.abs(next-curPos)>=small.length) continue; //otherwise kill this int firstNotAlive=toKill+1; while (firstNotAlive<occs.size() && occs.get(firstNotAlive)-next<small.length) firstNotAlive++; Pair future=go(firstNotAlive); best=combine(best, new Pair(future.minMoves+1, future.nWays)); } // System.out.println("Go at "+atIndex+" returning "+best); return dp[atIndex]=best; } static final Random random=new Random(); static final int mod=1_000_000_007; static class Pair { int minMoves; long nWays; public Pair(int minMoves, long nWays) { this.minMoves=minMoves; this.nWays=nWays; } public String toString() { return "$"+minMoves+", nWays: "+nWays; } } static Pair combine(Pair a, Pair b) { if (a==null) return b; if (b==null) return a; if (a.minMoves!=b.minMoves) { if (a.minMoves<b.minMoves) return a; return b; } return new Pair(a.minMoves, add(a.nWays, b.nWays)); } 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
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
2ad6474978800efe93096ca64cbed2b7
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.BinaryOperator; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); try {if(new File(System.getProperty("user.dir")).getName().equals("Main_CP")) { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} } catch (Exception ignore) { } } //----------------------START---------------------// void start() { int t = ni(); while(t-- > 0) solve(); w.close(); } long add(long a, long b) { return (a + b) % mod; } long sub(long a, long b) { return (a - b + 2 * mod) % mod; } void solve() { String s = ns(), t = ns(); int ns = s.length(), nt = t.length(); boolean[] end = new boolean[ns]; for(int i = 0; i < ns; i++) if(i + nt -1 < ns && s.substring(i, i + nt).equals(t)) end[i + nt -1] = true; else if(i + nt - 1 >= ns) break; long[][][] dp = new long[2][ns][ns + 1]; long[] move_cont = new long[ns + 1]; if(s.substring(0, 1).equals(t)) { dp[1][0][1] = 1; move_cont[1] = 1; } else dp[0][0][0] = 1; for(int i = 1; i < ns; i++) { for(int moves = 0; moves <= ns; moves++) { if(i - nt >= 0) move_cont[moves] = sub(move_cont[moves], dp[1][i - nt][moves]); if(end[i] && moves != 0) { long prev = (i - nt < 0) ? ((moves == 1) ? 1 : 0) : add(dp[1][i - nt][moves - 1], dp[0][i - nt][moves - 1]); dp[1][i][moves] = add(dp[1][i][moves], prev); dp[0][i][moves] = add(dp[0][i][moves], move_cont[moves]); move_cont[moves] = add(move_cont[moves], dp[1][i][moves]); } else { if(!(end[i] && moves == 0)) { dp[0][i][moves] = add(dp[1][i][moves], add(dp[0][i - 1][moves], dp[1][i - 1][moves])); } } } } for(int i = 0; i <= ns; i++) { if(dp[0][ns-1][i] != 0 || dp[1][ns-1][i] != 0) { p(i +" "+ ((dp[0][ns-1][i] + dp[1][ns-1][i])%mod)); return; } } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
887d09c588e13e3903f996a39d3febfd
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.util.function.BinaryOperator; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); try {if(new File(System.getProperty("user.dir")).getName().equals("Main_CP")) { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} } catch (Exception ignore) { } } //----------------------START---------------------// void start() { int t = ni(); while(t-- > 0) solve(); w.close(); } void solve() { String s = ns(), t = ns(); int ns = s.length(), nt = t.length(); int max_moves = (ns / nt) + 1; long[][][] dp = new long[ns][max_moves + 1][2]; // for(int i = 0; i < ns; i++) Arrays.fill(dp[i], -1); boolean[] end = new boolean[ns]; for(int i = nt - 1; i < ns; i++) { int l = i - nt + 1; if(s.substring(l, i+1).equals(t)) end[i] = true; } long[] sum_j = new long[max_moves + 1]; if(nt == 1 && t.equals(s.substring(0, 1))) { dp[0][1][1] = 1; sum_j[1] = 1; } else dp[0][0][0] = 1; for(int i = 1; i < ns; i++) { for(int j = 0; j <= max_moves; j++) { if(i - nt >= 0) { sum_j[j] = (sum_j[j] - dp[i - nt][j][1] + mod) % mod; } if(end[i] && j != 0) { int prev = i - nt; dp[i][j][1] = (prev < 0) ? ((j == 1) ? 1 : 0): (dp[prev][j-1][0] + dp[prev][j-1][1]); // taking this dp[i][j][1] %= mod; dp[i][j][0] = sum_j[j]; // without taking dp[i][j][0] %= mod; sum_j[j] += dp[i][j][1]; sum_j[j] %= mod; } else { if(!end[i]) dp[i][j][0] = dp[i-1][j][0] + dp[i-1][j][1]; } } } for(int i = 0; i <= max_moves; i++) { if(dp[ns-1][i][0] != 0 || dp[ns-1][i][1] != 0) { p(i +" "+((dp[ns-1][i][0] + dp[ns-1][i][1]) % mod)); return; } } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
db5838efd5bba7b0b04d94eeb422bb68
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); sc.nextLine(); while(q-- > 0) { String s = sc.nextLine(); String t = sc.nextLine(); int n = s.length(); int m = t.length(); boolean is[] = new boolean[n]; for(int i = 0 ; i < n ; i++) { if(i+1 >= m) { is[i] = true; int pp = m-1; for(int j = i ; j > i-m ; j--) { if(s.charAt(j) != t.charAt(pp)) { is[i] = false; break; } pp--; } } } int dp[] = new int[n]; for(int i = 0 ; i < n ; i++) { dp[i] = 10000000; } int mn = 10000000; for(int i = 0 ; i < n ; i++) { if(is[i]) { if(i-m < 0) dp[i] = 1; else { int pp = -1; for(int j = i-m ; j >= 0 ; j--) { if(is[j]) { pp = j; break; } } if(pp != -1) { for(int j = pp ; j > pp-m ; j--) { if(is[j]) dp[i] = Math.min(dp[i],dp[j]+1); } } else dp[i] = 1; } } // mn = Math.min(mn,dp[i]); } int pp = -1; for(int i = n-1 ; i >= 0 ; i--) { if(is[i]) { pp = i; break; } } if(pp == -1) System.out.println(0 + " " + 1); else { //int mn = 10000000; for(int i = pp ; i > pp-m ; i--) { mn = Math.min(mn,dp[i]); } long way[] = new long[n]; long mod = 1000000007; for(int i = 0 ; i < n ; i++) { if(is[i]) { pp = -1; for(int j = i-m ; j >= 0 ; j--) { if(is[j]) { pp = j; break; } } if(pp == -1) way[i] = 1; else { for(int j = pp ; j > pp-m ; j--) { if(dp[j] == dp[i]-1) way[i] += way[j]; way[i] %= mod; } } } } long ans = 0; pp = -1; for(int i = n-1 ; i >= 0 ; i--) { if(is[i]) { pp = i; break; } } for(int i = pp ; i > pp-m ; i--) { if(dp[i] == mn) { ans += way[i]; // System.out.println(way[i] + " " + i); } ans %= mod; } /* for(int i = 0 ; i < n ; i++) { System.out.println(dp[i] + " " + way[i] + " " + (i+1)); }*/ System.out.println(mn + " " + ans); } } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
6beecef4162161e595deaa16f375f54e
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
//package kg.my_algorithms.Codeforces; import java.util.*; import java.io.*; // Not a spectator public class Solution { private static final FastReader fr = new FastReader(); private static final long mod = 1_000_000_007L; public static void main(String[] args) throws IOException { BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); int testCases = fr.nextInt(); for(int testCase=1;testCase<=testCases;testCase++){ String s = fr.next(); String t = fr.next(); int[] zTemp = getZArray(t+"#"+s); int[] Z = new int[s.length()]; int[] dp1 = new int[s.length()]; Arrays.fill(dp1,-1); for(int i=0;i<s.length();i++) Z[i] = zTemp[i+t.length()+1]; int min_moves = minimumMoves(Z,s,0,t.length(),dp1); long[][] dp2 = new long[s.length()][min_moves+2]; for(int i=0;i<dp2.length;i++) for(int j=0;j<min_moves+2;j++) dp2[i][j] = -1; sb.append(min_moves).append(" ").append(ways(Z,s,0,t.length(),0,min_moves,dp2)).append("\n"); } output.write(sb.toString()); output.flush(); } public static int[] getZArray(String string){ char[] s = string.toCharArray(); int left=0,right=0,n=s.length; int[] Z = new int[n]; for(int k=1;k<n;k++){ if(k>right){ left=right=k; while(right<n && s[right]==s[right-left]) right++; Z[k] = right-left; right--; } else{ int k1 = k-left; if(Z[k1]<right-k+1) Z[k] = Z[k1]; else { left = k; while(right<n && s[right]==s[right-left]) right++; Z[k] = right-left; right--; } } } return Z; } private static int minimumMoves(int[] Z, String s, int index,int len,int[] dp){ if(index == s.length()) { // System.out.println("hello\n "); return 0; } if(dp[index] != -1) return dp[index]; if(Z[index] != len) return dp[index] = minimumMoves(Z,s,index+1,len,dp); int min = minimumMoves(Z,s,index+len,len,dp)+1; for(int i=1;i<len;i++){ if(Z[i+index] == len){ min = Math.min(min,minimumMoves(Z,s,index+i+len,len,dp)+1); } } return dp[index] = min; } private static long ways(int[] Z, String s, int index, int len, int moves, int min_moves,long[][] dp){ if(moves>min_moves) return 0L; if(index == s.length()) { // System.out.println("move= " + moves); return 1; } if(dp[index][moves]!=-1L) return dp[index][moves]; if(Z[index] != len) return dp[index][moves] = ways(Z,s,index+1,len,moves,min_moves,dp); long res = ways(Z,s,index+len,len,moves+1,min_moves,dp); for(int i=1;i<len;i++){ if(Z[index+i] == len){ res = (res+ways(Z,s,index+i+len,len,moves+1,min_moves,dp))%mod; } } return dp[index][moves] = res; } } //Fast Input 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
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
5f8797424a154b939ac6175c57e67e19
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
//package kg.my_algorithms.Codeforces; import java.util.*; import java.io.*; // Not a spectator public class Solution { private static final FastReader fr = new FastReader(); private static final long mod = 1_000_000_007L; public static void main(String[] args) throws IOException { BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); int testCases = fr.nextInt(); for(int testCase=1;testCase<=testCases;testCase++){ String s = fr.next(); String t = fr.next(); int[] zTemp = getZArray(t+"#"+s); int[] Z = new int[s.length()]; int[] dp1 = new int[s.length()]; Arrays.fill(dp1,-1); for(int i=0;i<s.length();i++) Z[i] = zTemp[i+t.length()+1]; int min_moves = minimumMoves(Z,s,0,t.length(),dp1); long[][] dp2 = new long[s.length()][min_moves+2]; for(int i=0;i<dp2.length;i++) for(int j=0;j<min_moves+2;j++) dp2[i][j] = -1; sb.append(min_moves).append(" ").append(ways(Z,s,0,t.length(),0,min_moves,dp2)).append("\n"); } output.write(sb.toString()); output.flush(); } public static int[] getZArray(String string){ char[] s = string.toCharArray(); int left=0,right=0,n=s.length; int[] Z = new int[n]; for(int k=1;k<n;k++){ if(k>right){ left=right=k; while(right<n && s[right]==s[right-left]) right++; Z[k] = right-left; right--; } else{ int k1 = k-left; if(Z[k1]<right-k+1) Z[k] = Z[k1]; else { left = k; while(right<n && s[right]==s[right-left]) right++; Z[k] = right-left; right--; } } } return Z; } private static int minimumMoves(int[] Z, String s, int index,int len,int[] dp){ if(index == s.length()) { // System.out.println("hello\n "); return 0; } if(dp[index] != -1) return dp[index]; if(Z[index] != len) return dp[index] = minimumMoves(Z,s,index+1,len,dp); int min = minimumMoves(Z,s,index+len,len,dp)+1; for(int i=1;i<len;i++){ if(Z[i+index] == len){ min = Math.min(min,minimumMoves(Z,s,index+i+len,len,dp)+1); } } return dp[index] = min; } private static long ways(int[] Z, String s, int index, int len, int moves, int min_moves,long[][] dp){ if(moves>min_moves) return 0L; if(index == s.length()) { // System.out.println("move= " + moves); return 1; } if(dp[index][moves]!=-1L) return dp[index][moves]; if(Z[index] != len) return dp[index][moves] = ways(Z,s,index+1,len,moves,min_moves,dp); long res = ways(Z,s,index+len,len,moves+1,min_moves,dp); for(int i=1;i<len;i++){ if(Z[index+i] == len){ res = (res+ways(Z,s,index+i+len,len,moves+1,min_moves,dp))%mod; } } return dp[index][moves] = res; } } //Fast Input 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
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
6ea1f152b3034d8630321c78c79fa5bd
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class G_Cut_Substrings{ public static void main(String[] args) { FastScanner s= new FastScanner(); PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ String str1=s.nextToken(); String str2=s.nextToken(); int size1=str1.length(); int size2=str2.length(); char array1[]= new char[size1]; for(int i=0;i<size1;i++){ array1[i]=str1.charAt(i); } char array2[]= new char[size2]; for(int i=0;i<size2;i++){ array2[i]=str2.charAt(i); } long dp[][]= new long[size1][size1]; for(int i=0;i<size1;i++){ for(int j=0;j<size1;j++){ dp[i][j]=-1; } } solve(dp,0,size1-1,array1,array2); long alpha=dp[0][size1-1]; for(int i=0;i<size1;i++){ for(int j=0;j<size1;j++){ if(dp[i][j]==-1){ solve(dp,i,j,array1,array2); } } } long mod=power(10,9)+7; long well[]= new long[size1+1]; for(int i=0;i<size1;i++){ well[i]=dp[i][size1-1]; } long nice[]= new long[size1+1];//remove kar raha hai // nice[size1-1]=1; nice[size1]=1; int array4[]= new int[size1]; find(array1,array2,array4); // { // //printing // for(int i=0;i<size1;i++){ // out.print(well[i]+" "); // } // out.println(); // } long nice2[]= new long[size1+1]; nice2[size1]=1; for(int i=size1-1;i>=0;i--){ if(array4[i]==1){ long curr=well[i]; long there=well[(i+array2.length)]; // if(there<curr){ nice[i]=((nice[i]+nice2[(i+array2.length)]))%mod; // } // else{ // // // } for(int j=i;j<i+array2.length;j++){ if(array4[j]==1){ long curr2=well[i]; long there2=well[(j+array2.length)]; if(there2<curr2){ nice2[i]=(nice2[i]+nice[j])%mod; } } } } else{ nice2[i]=nice2[i+1]; } // out.print(nice[i]+" "); } // out.println(); // { // //print // for(int i=0;i<size1;i++){ // out.print(nice[i]+" "); // } // out.println(); // for(int i=0;i<size1;i++){ // out.print(nice2[i]+" "); // } // out.println(); // } long beta=nice2[0]; res.append(alpha+" "+beta+"\n"); p++;} out.println(res); out.close(); } private static void solve(long[][] dp, int start, int end, char[] array1, char[] array2) { if(start>end){ return; } if(dp[start][end]!=-1){ return; } int size1=array1.length; int size2=array2.length; int length=end-start+1; char array3[]= new char[length]; int array4[]= new int[length]; for(int i=start;i<=end;i++){ array3[i-start]=array1[i]; } find(array3,array2,array4); int count=0; long ans=Integer.MAX_VALUE; for(int i=0;i<length;i++){ if(array4[i]==1){ count++; solve(dp,start,i-1+start,array1,array2); solve(dp,i+array2.length+start,end,array1,array2); long yoyo=1; if(i-1+start>=start){ yoyo+=dp[start][(i-1+start)]; } if(i+array2.length+start<=end){ yoyo+=dp[(i+array2.length+start)][end]; } ans=Math.min(ans,yoyo); } } if(count==0){ dp[start][end]=0; } else{ dp[start][end]=ans; } } private static void find(char[] array3, char[] array2, int[] array4) { //array2 is the one jo pehle lagna chahiye int size=array3.length+array2.length+1; char array[]= new char[size]; int index=0; for(int i=0;i<array2.length;i++){ array[index]=array2[i]; index++; } array[index]='&'; index++; for(int i=0;i<array3.length;i++){ array[index]=array3[i]; index++; } int nice[]= new int[size]; int l=0; int r=0; for(int i=1;i<size;i++){ if(i>r){ l=i; r=i; int ind=0; while(r<size && array[r]==array[ind]){ r++; ind++; } r--; nice[i]=(r-l+1); } else{ int ind=i-l; if(nice[ind]<(r-i+1)){ nice[i]=nice[ind]; } else{ l=i; r++; int indi=r-i; while(r<size && array[r]==array[indi]){ r++; indi++; } r--; nice[i]=(r-l+1); } } } int here=array2.length+1; for(int i=0;i<array4.length;i++){ if(nice[here]==array2.length){ array4[i]=1; } here++; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
0019c62897b54f270f8af48d2ae86b92
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { private static final int mod = 1000000007; private static void solve(String s, String t){ int INF = s.length() + 100; List<Integer> indices = getAllOccurrence(s, t); if(indices.isEmpty()){ out.println("0 1"); } else { int[][] dp = new int[indices.size()][2]; for(int[] r: dp){ Arrays.fill(r, INF); } int len = t.length(); long[][] count = new long[indices.size()][2]; for(int i = dp.length - 1; i >= 0; i--){ int k = i + 1; while(k < dp.length && indices.get(k) - indices.get(i) + 1 <= len){ if(dp[i][0] > dp[k][1]){ dp[i][0] = dp[k][1]; count[i][0] = count[k][1]; } else if(dp[i][0] == dp[k][1]){ count[i][0] += count[k][1]; count[i][0] %= mod; } k++; } if(k >= dp.length){ dp[i][1] = 1; count[i][1] = 1; continue; } if(dp[i][1] > 1 + dp[k][1]){ dp[i][1] = 1 + dp[k][1]; count[i][1] = count[k][1]; } else if(dp[i][1] == 1 + dp[k][1]){ count[i][1] += count[k][1]; count[i][1] %= mod; } if(dp[i][1] > 1 + dp[k][0]){ dp[i][1] = 1 + dp[k][0]; count[i][1] = count[k][0]; } else if(dp[i][1] == 1 + dp[k][0]){ count[i][1] += count[k][0]; count[i][1] %= mod; } } // out.println(Arrays.deepToString(dp)); // out.println(Arrays.deepToString(count)); int res = Math.min(dp[0][0], dp[0][1]); long cnt = 0L; int idx = 0; while(idx < indices.size() && indices.get(idx) - indices.get(0) + 1 <= t.length()){ if(res == dp[idx][1]){ cnt += count[idx][1]; cnt %= mod; } idx++; } out.println(res + " " + cnt); } } private static int getNextIdx(List<Integer> indices, int pos){ int start = 0, end = indices.size() - 1; while(start + 1 < end){ int mid = start + (end - start) / 2; if(indices.get(mid) >= pos){ end = mid; } else { start = mid; } } if(indices.get(start) >= pos){ return start; } if(indices.get(end) >= pos){ return end; } return indices.size(); } private static List<Integer> getAllOccurrence(String s, String t){ List<Integer> res = new ArrayList<>(); for(int i = 0; i <= s.length() - t.length(); i++){ boolean match = true; for(int j = 0; j < t.length(); j++){ if(s.charAt(i + j) != t.charAt(j)){ match = false; break; } } if(match){ res.add(i); } } return res; } public static void main(String[] args){ MyScanner scanner = new MyScanner(); int testCount = scanner.nextInt(); for(int testIdx = 1; testIdx <= testCount; testIdx++){ String s = scanner.nextLine(); String t = scanner.nextLine(); solve(s, t); } out.close(); } public static void printResult(int idx, long res){ out.println("Case #" + idx + ": " + res); } static void print1DArray(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i]); if(i < arr.length - 1){ out.print(' '); } } out.print('\n'); } static void print1DArrayList(List<Integer> arrayList){ for(int i = 0; i < arrayList.size(); i++){ out.print(arrayList.get(i)); if(i < arrayList.size() - 1){ out.print(' '); } } out.print('\n'); } public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
2b21764605d372d3df4487f7ead0a220
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); sc.nextLine(); while(q-- > 0) { String s = sc.nextLine(); String t = sc.nextLine(); int n = s.length(); int m = t.length(); boolean is[] = new boolean[n]; for(int i = 0 ; i < n ; i++) { if(i+1 >= m) { is[i] = true; int pp = m-1; for(int j = i ; j > i-m ; j--) { if(s.charAt(j) != t.charAt(pp)) { is[i] = false; break; } pp--; } } } int dp[] = new int[n]; for(int i = 0 ; i < n ; i++) { dp[i] = 10000000; } int mn = 10000000; for(int i = 0 ; i < n ; i++) { if(is[i]) { if(i-m < 0) dp[i] = 1; else { int pp = -1; for(int j = i-m ; j >= 0 ; j--) { if(is[j]) { pp = j; break; } } if(pp != -1) { for(int j = pp ; j > pp-m ; j--) { if(is[j]) dp[i] = Math.min(dp[i],dp[j]+1); } } else dp[i] = 1; } } // mn = Math.min(mn,dp[i]); } int pp = -1; for(int i = n-1 ; i >= 0 ; i--) { if(is[i]) { pp = i; break; } } if(pp == -1) System.out.println(0 + " " + 1); else { //int mn = 10000000; for(int i = pp ; i > pp-m ; i--) { mn = Math.min(mn,dp[i]); } long way[] = new long[n]; long mod = 1000000007; for(int i = 0 ; i < n ; i++) { if(is[i]) { pp = -1; for(int j = i-m ; j >= 0 ; j--) { if(is[j]) { pp = j; break; } } if(pp == -1) way[i] = 1; else { for(int j = pp ; j > pp-m ; j--) { if(dp[j] == dp[i]-1) way[i] += way[j]; way[i] %= mod; } } } } long ans = 0; pp = -1; for(int i = n-1 ; i >= 0 ; i--) { if(is[i]) { pp = i; break; } } for(int i = pp ; i > pp-m ; i--) { if(dp[i] == mn) { ans += way[i]; // System.out.println(way[i] + " " + i); } ans %= mod; } /* for(int i = 0 ; i < n ; i++) { System.out.println(dp[i] + " " + way[i] + " " + (i+1)); }*/ System.out.println(mn + " " + ans); } } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
22fa13b4b1489a092fb47833de0ae602
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class E_Guess_the_Cycle_Size { static FastReader sc; static PrintWriter out; static long[][] dp; static long mod = 1_000_000_007; static void solve() { StringBuilder res = new StringBuilder(); String s = sc.next(); String t = sc.next(); int p = 31,n = s.length(); int m = (int)1e9 + 9; long hash_value = 0; long p_pow = 1; for (char c :t.toCharArray()) { hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } long[] pow = new long[n]; pow[0] = 1; for (int i = 1; i < n; i++) pow[i] = (pow[i-1] * p) % m; long[] hash = new long[n+1]; for (int i = 0; i < n; i++) hash[i+1] = (hash[i] + (s.charAt(i) - 'a' + 1) * pow[i]) % m; int l = t.length(); boolean[] match = new boolean[n]; for (int i = 0; i <= n - l; i++) { long cur_h = (hash[i + l] + m - hash[i]) % m; long tmp = (hash_value * pow[i]) % m; if(cur_h==tmp) { match[i] = true; } } int ans = 0,i=0; while(i<n){ if(match[i]){ int max = i+l; for(int j=i;j<i+l;j++){ if(match[j]) max = j+l; } i = max; ans++; }else { i++; } } dp = new long[n+1][n+1]; for(long[] d:dp){ Arrays.fill(d,-1); } print(ans +" "+dfs(match,0,0,l,ans)); } static long dfs(boolean[] match,int i,int c,int l,int max){ if(c>max) return 0; if(dp[i][max-c]!=-1) return dp[i][max-c]; if(i>=match.length) return 1; long ans = 0; if(match[i]){ for(int j=i;j<i+l;j++){ if(match[j]){ ans = (ans + dfs(match,j+l,c+1,l,max))%mod; } } }else{ ans = (ans + dfs(match,i+1,c,l,max))%mod; } return dp[i][max-c] = ans; } public static void main(String[] args) throws IOException { sc = new FastReader(); out = new PrintWriter(System.out); int tt = sc.nextInt(); while (tt-- > 0) { solve(); } out.close(); } static <E> void debug(E a) { System.err.println(a); } static void debug(int... a) { System.err.println(Arrays.toString(a)); } static int maxOf(int... array) { return Arrays.stream(array).max().getAsInt(); } static int minOf(int... array) { return Arrays.stream(array).parallel().reduce(Math::min).getAsInt(); } static <E> void print(E res) { out.println(res); } 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
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
5f09d28909974bb985743b3b1015a1c3
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { static Scanner sc; static PrintWriter pw; static int[] occ; static int n, m; static ArrayList<Integer> idx; static int mod = (int) 1e9 + 7; static int[][] memo1; static boolean[] eq; static long[][] memo2; static int dp(int myidx, int done) { if (done == -1) return 0; if (memo1[done][myidx] != -1) return memo1[done][myidx]; int ans = (int) 1e9; for (int j = myidx; j < idx.get(done) + m; j++) { // System.out.println(j + 1 + " " + occ[j + 1]); if (eq[j]) ans = Math.min(ans, 1 + dp(j + m, occ[j + m])); } return memo1[done][myidx] = ans; } static long dp2(int myidx, int done) { if (done == -1) return 1; if (memo2[done][myidx] != -1) return memo2[done][myidx]; int cur = dp(myidx, done); long ans = 0; for (int j = myidx; j < idx.get(done) + m; j++) { if (eq[j]) { if (cur == 1 + dp(j + m, occ[j + m])) { ans += dp2(j + m, occ[j + m]); if (ans >= mod) ans -= mod; } } } return memo2[done][myidx] = ans; } public static void main(String[] args) throws Exception { pw = new PrintWriter(System.out); sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 1; tc <= t; tc++) { String a = sc.next(), b = sc.next(); n = a.length(); m = b.length(); if (m > n) { pw.println("0 1"); continue; } occ = new int[n + m]; int cnt = 0; Arrays.fill(occ, -1); idx = new ArrayList<>(); eq = new boolean[n]; for (int i = 0; i <= n - m; i++) { boolean cur = a.substring(i, i + m).equals(b); if (cur) { occ[i] = cnt++; idx.add(i); } eq[i] = cur; } if (cnt == 0) { pw.println("0 1"); continue; } for (int i = n + m - 2; i >= 0; i--) { if (occ[i] == -1) { occ[i] = occ[i + 1]; } } // pw.println(idx); memo1 = new int[idx.size()][n]; for (int[] i : memo1) Arrays.fill(i, -1); memo2 = new long[idx.size()][n]; for (long[] i : memo2) Arrays.fill(i, -1); // for (int i = idx.size() - 1; i >= 0; i--) { // for (int j = n - 1; j >= 0; i--) { // dp2(j, i); // } // } pw.println(dp(0, 0) + " " + dp2(0, 0)); } pw.flush(); } static class hashing { public static long RandomPick(long[] a) { int n = a.length; int r = rn.nextInt(n); return a[r]; } public static int RandomPick(int[] a) { int n = a.length; int r = rn.nextInt(n); return a[r]; } static class Hash { int[] HashsArraypre; int[] HashsArraysuf; static int[] prepow; static int HashsArrayInd = 0; static int prime = 61; static int mod; static int max = 1000009; int prelen; static final int[] mods = { 1000000007, 1000000009, 1000000021, 1000000033, 1000000087, 1000000093, 1000000097, 1000000103, 1000000123, 1000000181, 1000000207, 1000000223, 1000000241, 1000000271, 1000000289, 1000000297, 1000000321, 1000000349, 1000000363, 1000000403, 1000000409, 1000000411, 1000000427, 1000000433, 1000000439, 1000000447, 1000000453, 1000000459, 1000000483, 1000000513, 1000000531, 1000000579, 1000000607, 1000000613, 1000000637, 1000000663, 1000000711, 1000000753, 1000000787, 1000000801, 1000000829, 1000000861, 1000000871, 1000000891, 1000000901, 1000000919, 1000000931, 1000000933, 1000000993, 1000001011, 1000001021, 1000001053, 1000001087, 1000001099, 1000001137, 1000001161, 1000001203, 1000001213, 1000001237, 1000001263, 1000001269, 1000001273, 1000001279, 1000001311, 1000001329, 1000001333, 1000001351, 1000001371, 1000001393, 1000001413, 1000001447, 1000001449, 1000001491, 1000001501, 1000001531, 1000001537, 1000001539, 1000001581, 1000001617, 1000001621, 1000001633, 1000001647, 1000001663, 1000001677, 1000001699, 1000001759, 1000001773, 1000001789, 1000001791, 1000001801, 1000001803, 1000001819, 1000001857, 1000001887, 1000001917, 1000001927, 1000001957, 1000001963, 1000001969, 1000002043 }; public Hash(String s) { prelen = s.length(); HashsArraypre = new int[prelen + 1]; HashsArraysuf = new int[prelen + 1]; if (HashsArrayInd == 0) { mod = RandomPick(mods); prime = (int) (Math.random() * (1e8) + 1000); prepow = new int[max]; prepow[0] = 1; for (int i = 1; i < max; i++) { // prepow[i] = (int) (((1l * prepow[i - 1] << 7) - prepow[i - 1]) % mod); prepow[i] = (int) ((1l * prepow[i - 1] * prime) % mod); } } for (int i = 0; i < prelen; i++) { HashsArraypre[i + 1] = (int) ((HashsArraypre[i] + 1l * s.charAt(i) * prepow[i] % mod) % mod); } for (int i = 0; i < prelen; i++) { HashsArraysuf[i + 1] = (int) ((HashsArraysuf[i] + 1l * s.charAt(i) * prepow[max - 1 - i] % mod) % mod); } HashsArrayInd++; } public int query(int l, int r) { // l>r when the query is reversed int val; if (l <= r) { val = (int) ((1l * HashsArraypre[r + 1] + mod - HashsArraypre[l]) % mod); val = (int) ((1l * val * prepow[max - 1 - l]) % mod); } else { val = (int) ((1l * HashsArraysuf[l + 1] + mod - HashsArraysuf[r]) % mod); val = (int) ((1l * val * prepow[l]) % mod); } return val; } } static Random rn = new Random(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String r) throws Exception { br = new BufferedReader(new FileReader(new File(r))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 8
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
90e7167100fcd461cc7321e0dd4cfbae
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class G { static long mod = (long) 1e9 + 7; static void update(long[][] dp, int i, int j, long val){ int n = dp.length; i++; while(i <= n){ dp[i-1][j] = (dp[i-1][j] + val) % mod; i += (i & (-i)); } } static long sum(long[][] dp, int i, int j){ long sum = 0; i+=1; if(j < 0) return 0; while(i > 0){ sum = (sum + dp[i - 1][j]) % mod; i -= (i & (-i)); } return sum; } static int getCountOps(boolean[] match, int[] last, int i, int tl){ if(i < 0) return 0; int index = i; for(int j=i;j>=i-tl+1;j--){ if(match[j]) index = j; } int prev = (index - tl < 0)?-1:last[index - tl]; return getCountOps(match, last, prev, tl) + 1; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (tc-->0){ String s = br.readLine(); String t = br.readLine(); int sl = s.length(); int tl = t.length(); int[] lps = new int[tl]; lps[0] = -1; for(int i=1;i<tl;i++){ int nextIndex = lps[i-1] + 1; if(t.charAt(nextIndex) == t.charAt(i)){ lps[i] = nextIndex; } else{ lps[i] = -1; } } int si = 0, ti = -1; boolean[] match = new boolean[sl]; while(si < sl){ if(s.charAt(si) == t.charAt(ti + 1)){ ti++; si++; if(ti == tl-1){ match[si - 1] = true; ti = lps[ti]; } } else{ if(ti == -1){ si++; } else{ ti = lps[ti]; } } } int[] last = new int[sl]; last[0] = match[0]?0:-1; for(int i=1;i<sl;i++){ if(match[i]){ last[i] = i; } else{ last[i] = last[i-1]; } } int len = getCountOps(match, last, last[sl - 1], tl); if(len == 0){ sb.append("0 1\n"); continue; } long[][] dp = new long[sl][len]; for(int i=tl-1;i<sl;i++){ for(int j=0;j<len;j++){ if(match[i]) { if(i - tl < 0 || last[i - tl] == -1) { //dp[i][j] = 1; update(dp, i, j, 1); } else { int prev = last[i - tl]; long sum = (sum(dp, prev, j-1) - sum(dp, prev-tl, j-1) + mod) % mod; /*for(int i1 = prev-tl+1;i1 <= prev && j-1>=0;i1++){ sum += dp[i1][j - 1]; }*/ //dp[i][j] = sum; update(dp, i, j, sum); } } } } long ans = (sum(dp, last[sl-1], len-1) - sum(dp, last[sl-1]-tl, len-1) + mod) % mod; /*for(int i = last[sl - 1];i>=(last[sl - 1] - tl + 1);i--){ ans = (ans + dp[i][len-1]) % mod; }*/ sb.append(len).append(" ").append(ans).append("\n"); } System.out.println(sb); br.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 17
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
01288712b2ab52bf864a9acb430faa7e
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class G { static long mod = (long) 1e9 + 7; static void update(long[][] dp, int i, int j, long val){ int n = dp.length; i++; while(i <= n){ dp[i-1][j] = (dp[i-1][j] + val) % mod; i += (i & (-i)); } } static long sum(long[][] dp, int i, int j){ long sum = 0; i+=1; j+=1; if(j <= 0) return 0; while(i > 0){ sum = (sum + dp[i - 1][j - 1]) % mod; i -= (i & (-i)); } return sum; } static int getCountOps(boolean[] match, int[] last, int i, int tl){ if(i < 0) return 0; int index = i; for(int j=i;j>=i-tl+1;j--){ if(match[j]) index = j; } int prev = (index - tl < 0)?-1:last[index - tl]; return getCountOps(match, last, prev, tl) + 1; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (tc-->0){ String s = br.readLine(); String t = br.readLine(); int sl = s.length(); int tl = t.length(); int[] lps = new int[tl]; lps[0] = -1; for(int i=1;i<tl;i++){ int nextIndex = lps[i-1] + 1; if(t.charAt(nextIndex) == t.charAt(i)){ lps[i] = nextIndex; } else{ lps[i] = -1; } } int si = 0, ti = -1; boolean[] match = new boolean[sl]; while(si < sl){ if(s.charAt(si) == t.charAt(ti + 1)){ ti++; si++; if(ti == tl-1){ match[si - 1] = true; ti = lps[ti]; } } else{ if(ti == -1){ si++; } else{ ti = lps[ti]; } } } int[] last = new int[sl]; last[0] = match[0]?0:-1; for(int i=1;i<sl;i++){ if(match[i]){ last[i] = i; } else{ last[i] = last[i-1]; } } int len = getCountOps(match, last, last[sl - 1], tl); if(len == 0){ sb.append("0 1\n"); continue; } long[][] dp = new long[sl][len]; for(int i=tl-1;i<sl;i++){ for(int j=0;j<len;j++){ if(match[i]) { if(i - tl < 0 || last[i - tl] == -1) { dp[i][j] = 1; } else { int prev = last[i - tl]; long sum = 0; for(int i1 = prev-tl+1;i1 <= prev && j-1>=0;i1++){ sum += dp[i1][j - 1]; } dp[i][j] = sum; } } } } long ans = 0; for(int i = last[sl - 1];i>=(last[sl - 1] - tl + 1);i--){ ans = (ans + dp[i][len-1]) % mod; } sb.append(len).append(" ").append(ans).append("\n"); } System.out.println(sb); br.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 17
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
5ef28c2d5848e2c8ef9dc56012513a2c
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.util.*; import java.io.*; public class G { static long mod = (long) 1e9 + 7; static void update(long[][] dp, int i, int j, long val){ int n = dp.length; i++; while(i <= n){ dp[i-1][j] = (dp[i-1][j] + val) % mod; i += (i & (-i)); } } static long sum(long[][] dp, int i, int j){ long sum = 0; i+=1; j+=1; if(j <= 0) return 0; while(i > 0){ sum = (sum + dp[i - 1][j - 1]) % mod; i -= (i & (-i)); } return sum; } static int getCountOps(boolean[] match, int[] last, int i, int tl){ if(i < 0) return 0; int index = i; for(int j=i;j>=i-tl+1;j--){ if(match[j]) index = j; } int prev = (index - tl < 0)?-1:last[index - tl]; return getCountOps(match, last, prev, tl) + 1; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (tc-->0){ String s = sc.next(); String t = sc.next(); int sl = s.length(); int tl = t.length(); int[] lps = new int[tl]; lps[0] = -1; for(int i=1;i<tl;i++){ int nextIndex = lps[i-1] + 1; if(t.charAt(nextIndex) == t.charAt(i)){ lps[i] = nextIndex; } else{ lps[i] = -1; } } int si = 0, ti = -1; boolean[] match = new boolean[sl]; while(si < sl){ if(s.charAt(si) == t.charAt(ti + 1)){ ti++; si++; if(ti == tl-1){ match[si - 1] = true; ti = lps[ti]; } } else{ if(ti == -1){ si++; } else{ ti = lps[ti]; } } } int[] last = new int[sl]; last[0] = match[0]?0:-1; for(int i=1;i<sl;i++){ if(match[i]){ last[i] = i; } else{ last[i] = last[i-1]; } } int len = getCountOps(match, last, last[sl - 1], tl); if(len == 0){ sb.append("0 1\n"); continue; } long[][] dp = new long[sl][len]; for(int i=tl-1;i<sl;i++){ for(int j=0;j<len;j++){ if(match[i]) { if(i - tl < 0 || last[i - tl] == -1) { dp[i][j] = 1; } else { int prev = last[i - tl]; long sum = 0; for(int i1 = prev-tl+1;i1 <= prev && j-1>=0;i1++){ sum += dp[i1][j - 1]; } dp[i][j] = sum; } } } } long ans = 0; for(int i = last[sl - 1];i>=(last[sl - 1] - tl + 1);i--){ ans = (ans + dp[i][len-1]) % mod; } sb.append(len).append(" ").append(ans).append("\n"); } System.out.println(sb); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } 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;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 17
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
6a45cabe88632fec5f5b17ed0b27e4d9
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
// Input : Pratik import java.io.*; import java.util.*; public class JavaDeveoper { static int an; static int bn; static boolean[] valid; static long[][][] memo; static final long[] BASE = new long[] {0, 1}; static final long MOD = 1_000_000_007L; public static void main(String[] args) { try { System.setIn(new FileInputStream("input.txt")); System.setOut (new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } Scanner in = new Scanner(System.in); int numT = in.nextInt(); for (int ci = 0; ci < numT; ci++) { String a = in.next(); String b = in.next(); an = a.length(); bn = b.length(); valid = new boolean[an]; for (int i = 0; i < an; i++) { valid[i] = a.startsWith(b, i); } memo = new long[an][an][]; long[] ans = go(0, an - 1); System.out.printf("%d %d\n", ans[0], ans[1]); } } static long[] go(int i, int j) { if (i > j) { return BASE; } if (memo[i][j] != null) { return memo[i][j]; } long min = Long.MAX_VALUE; long num = 1; for (int k = i; k <= j - bn + 1; k++) { if (valid[k]) { long[] left = go(i, k - 1); if (left[0] > 0) { break; } long[] right = go(k + bn, j); long minn = left[0] + right[0] + 1; if (minn < min) { min = minn; num = (left[1] * right[1]) % MOD; } else if (minn == min) { num = (num + left[1] * right[1]) % MOD; } } } if (min == Long.MAX_VALUE) { min = 0; } return memo[i][j] = new long[] {min, num}; } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 17
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
d7e1055aa8b6ab516f3538ce959f4333
train_110.jsonl
1662993300
You are given two non-empty strings $$$s$$$ and $$$t$$$, consisting of Latin letters.In one move, you can choose an occurrence of the string $$$t$$$ in the string $$$s$$$ and replace it with dots.Your task is to remove all occurrences of the string $$$t$$$ in the string $$$s$$$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $$$t$$$ in $$$s$$$ begin differ. For example, the sets $$$\{1, 2, 3\}$$$ and $$$\{1, 2, 4\}$$$ are considered different, the sets $$$\{2, 4, 6\}$$$ and $$$\{2, 6\}$$$ — too, but sets $$$\{3, 5\}$$$ and $$$\{5, 3\}$$$ — not.For example, let the string $$$s =$$$ "abababacababa" and the string $$$t =$$$ "aba". We can remove all occurrences of the string $$$t$$$ in $$$2$$$ moves by cutting out the occurrences of the string $$$t$$$ at the $$$3$$$th and $$$9$$$th positions. In this case, the string $$$s$$$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $$$t$$$ at the $$$3$$$th and $$$11$$$th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo $$$10^9 + 7$$$.
256 megabytes
import java.io.*; import java.util.*; public class G { final static boolean multipleTests = true; Input in; PrintWriter out; public G() { in = new Input(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { G solution = new G(); int t = 1; if (multipleTests) t = solution.in.nextInt(); for (; t > 0; t--) { solution.solve(); } solution.out.close(); } final static int mod = (int) (1e9 + 7); List<Integer> pos; char[] s, t; int[][] dp; int[] prev; void solve() { s = in.nextString().toCharArray(); t = in.nextString().toCharArray(); pos = new ArrayList<>(); for (int i=0; i+t.length-1<s.length; i++) { boolean valid = true; for (int j=0; j<t.length; j++) { if (s[i+j] != t[j]) { valid = false; break; } } if (valid) pos.add(i); } int minMoves = 0; for (int i=0; i<pos.size(); ) { minMoves++; int r = pos.get(i) + t.length; while (i<pos.size() && pos.get(i)<r) { i++; } r = pos.get(i-1) + t.length; while (i<pos.size() && pos.get(i)<r) { i++; } } prev = new int[pos.size()]; Arrays.fill(prev, -1); for (int i=0; i<pos.size(); i++) { for (int j=i+1; j<pos.size(); j++) { if (pos.get(i) + t.length <= pos.get(j)) { prev[j] = i; } } } dp = new int[pos.size()][minMoves+1]; for (int i=0; i<pos.size(); i++) Arrays.fill(dp[i], -1); int ans = recurse(pos.size()-1, minMoves); out.printf("%d %d%n", minMoves, ans); } int recurse(int idx, int movesLeft) { if (movesLeft == 0 && idx >= 0) return 0; if (movesLeft == 0) return 1; if (dp[idx][movesLeft] != -1) return dp[idx][movesLeft]; long ans = 0; for (int i=idx; i>=0 && pos.get(i) + t.length > pos.get(idx); i--) { ans += recurse(prev[i], movesLeft-1); } ans %= mod; dp[idx][movesLeft] = (int)ans; return dp[idx][movesLeft]; } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } String nextString() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextString()); } long nextLong() { return Long.parseLong(nextString()); } double nextDouble() { return Double.parseDouble(nextString()); } int[] nextIntArray(int size) { int[] ans = new int[size]; for (int i = 0; i < size; i++) { ans[i] = nextInt(); } return ans; } } }
Java
["8\n\nabababacababa\n\naba\n\nddddddd\n\ndddd\n\nxyzxyz\n\nxyz\n\nabc\n\nabcd\n\nabacaba\n\nabaca\n\nabc\n\ndef\n\naaaaaaaa\n\na\n\naaaaaaaa\n\naa"]
2 seconds
["2 2\n1 4\n2 1\n0 1\n1 1\n0 1\n8 1\n3 6"]
NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string $$$s$$$ is the concatenation of two strings $$$t =$$$ "xyz", so there is a unique optimal sequence of $$$2$$$ moves.In the fourth and sixth cases, the string $$$s$$$ initially contains no occurrences of the string $$$t$$$.In the fifth case, the string $$$s$$$ contains exactly one occurrence of the string $$$t$$$.
Java 17
standard input
[ "combinatorics", "dp", "hashing", "strings", "two pointers" ]
904af5d6a9d84b7b7b7ff8d63e6f0254
The first line of the input contains a single integer $$$q$$$ ($$$1 \le q \le 50$$$) — the number of test cases. The descriptions of the sets follow. The first line of each set contains a non-empty string $$$s$$$ ($$$1 \le |s| \le 500$$$) consisting of lowercase Latin letters. The second line of each set contains a non-empty string $$$t$$$ ($$$1 \le |t| \le 500$$$) consisting of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$500$$$. Similarly, it is guaranteed that the sum of string lengths $$$t$$$ over all test cases does not exceed $$$500$$$.
2,100
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $$$10^9 + 7$$$.
standard output
PASSED
d12eacffc4a6c44ab2664f0dfac9ae91
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static void main(String[] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int k = Integer.parseInt(br.readLine()); while(k-->0){ char s[] = br.readLine().toCharArray(); PriorityQueue<Pare> pq; int len = s.length; int si = s[0] - 96; int ei = s[len-1] - 96; if(si <= ei){ pq = new PriorityQueue<Pare>(new PareComparator()); }else{ pq = new PriorityQueue<Pare>(new PareComparatorInv()); } for(int i = 1; i < len-1; ++i){ pq.add(new Pare((s[i] - 96),i+1)); } if(si > ei){ int temp = si; si = ei; ei = temp; } int nl = pq.size()+2,ic = 1; int ar[] = new int[nl]; ar[0] = 1; while(!pq.isEmpty()){ Pare p = pq.poll(); if(p.a >= si && p.a <= ei){ ar[ic++] = p.b; } } ar[ic] = len; System.out.println((ei - si)+" "+(ic+1)); for(int i = 0; i <= ic; ++i) System.out.print(ar[i] + " "); System.out.println(); } } } class PareComparatorInv implements Comparator<Pare>{ public int compare(Pare x, Pare y) { return -x.a + y.a ; } } class PareComparator implements Comparator<Pare>{ public int compare(Pare x, Pare y) { return x.a - y.a ; } } class Pare { public int a; //value public int b; //index public Pare(int a, int b) { this.a = a; this.b = b; } public String toString(){ return a + ":"+ b; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
7ff9d48dd4e3d04e7e1bdc7af7d9f64a
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static void main(String[] args)throws Exception{ //Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //int k = sc.nextInt(); //sc.nextLine(); int k = Integer.parseInt(br.readLine()); //br.readLine(); while(k-->0){ //String s = sc.nextLine(); char s[] = br.readLine().toCharArray(); PriorityQueue<Pare> pq; int len = s.length; int si = s[0] - 96; int ei = s[len-1] - 96; if(si <= ei){ pq = new PriorityQueue<Pare>(new PareComparator()); }else{ pq = new PriorityQueue<Pare>(new PareComparatorInv()); } for(int i = 1; i < len-1; ++i){ pq.add(new Pare((s[i] - 96),i+1)); } if(si > ei){ int temp = si; si = ei; ei = temp; } int nl = pq.size()+2,ic = 1; int ar[] = new int[nl]; ar[0] = 1; while(!pq.isEmpty()){ Pare p = pq.poll(); //System.out.print(p.toString()+" "); if(p.a >= si && p.a <= ei){ ar[ic++] = p.b; } } ar[ic] = len; /* String rs = ""; String rsa = ""; int tt = 0; while(!pq.isEmpty()){ Pare p = pq.poll(); //System.out.print(p.toString()+" "); if(p.a >= si && p.a <= ei){ rs += p.b+" "; tt++; } }*/ //System.out.println(); System.out.println((ei - si)+" "+(ic+1)); for(int i = 0; i <= ic; ++i) System.out.print(ar[i] + " "); System.out.println(); //System.out.println(""+1+" "+rs.trim()+(rs.trim().length() == 0?"":" ")+s.length()); //System.out.println(""+1+" "+rs+len); //System.out.println(""+1+" "+rsa.trim()+(rsa.trim().length() == 0?"":" ")+s.length()); } } } class PareComparatorInv implements Comparator<Pare>{ public int compare(Pare x, Pare y) { return -x.a + y.a ; } } class PareComparator implements Comparator<Pare>{ public int compare(Pare x, Pare y) { return x.a - y.a ; } } class Pare { public int a; //value public int b; //index public Pare(int a, int b) { this.a = a; this.b = b; } public String toString(){ return a + ":"+ b; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
fbcbf231796ef23512a385a3c16bd188
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Hackerearth{ public static void main(String []args){ Scanner scx = new Scanner(System.in); int t = scx.nextInt(); while(t-->0) { //int n = scx.nextInt(); String s = scx.next(); char[] ch = s.toCharArray(); int len = ch.length; int minCost = Math.abs(ch[len-1] - ch[0]); List<Integer> list = new ArrayList<>(); for (int i = 1; i < len-1; i++) { if ((ch[i] >= ch[0] && ch[i] <= ch[len-1]) || (ch[i] <= ch[0] && ch[i] >= ch[len-1])) { list.add(i); } } if (ch[0] < ch[len-1]) Collections.sort(list, (x, y) -> ch[x] - ch[y] ); else Collections.sort(list, (x, y) -> ch[y] - ch[x] ); System.out.println(minCost+" "+(list.size()+2)); System.out.print(1+" "); for (int i=0; i<list.size(); i++) { System.out.print((list.get(i)+1)+" "); } System.out.println(len); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
76563f8fe25904c67ceb0acb35e61846
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ static StreamTokenizer st ; static BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); st = new StreamTokenizer(re); int t = I(); re.readLine(); while(t-->0) { char[]s = re.readLine().toCharArray(); node[]a = new node[s.length]; int cnt = 0; int start = (int)s[0] , end = (int)s[s.length-1]; for (int i = 0 ; i < s.length ; i++) { if(s[i] >=start && s[i] <=end || s[i] <= start && s[i] >=end) a[cnt++] = new node(s[i],i+1); } int val = Math.abs(start-end); int m = cnt; Vector<Integer> ans = new Vector<>(); if(start <= end) { Arrays.sort(a,0,cnt,new Comparator<node>(){ @Override public int compare(node o1, node o2) { // TODO 自动生成的方法存根 if(o1.x != o2.x)return o1.x-o2.x; else return o1.k-o2.k; } }); for (int i = 0 ; i < cnt ; i++) { ans.add(a[i].k); } } else { Arrays.sort(a,0,cnt,new Comparator<node>(){ @Override public int compare(node o1, node o2) { // TODO 自动生成的方法存根 if(o1.x != o2.x)return o1.x-o2.x; else return o2.k-o1.k; } }); for (int i = cnt-1 ; i >= 0 ; i--) { ans.add(a[i].k); } } pw.println(val +" "+m); for (int i = 0 ; i < ans.size() ; i++) pw.print(ans.get(i)+" "); pw.println(); pw.flush(); } } static int I() throws IOException { st.nextToken(); return (int)st.nval; } static long L() throws IOException { st.nextToken(); return (long)st.nval; } } class node { char x; int k; public node(char x,int k) { this.x = x; this.k = k; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
86fea762667fed1eac20161d7227f700
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ static StreamTokenizer st ; static BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); st = new StreamTokenizer(re); int t = I(); re.readLine(); while(t-->0) { char[]s = re.readLine().toCharArray(); int cnt = 0; Vector<Vector<Integer>>v = new Vector<>(); for (int i = 0 ; i <= 26 ; i++) v.add(new Vector<Integer>()); int start = (int)s[0] , end = (int)s[s.length-1]; for (int i = 0 ; i < s.length ; i++) { if(s[i] >=start && s[i] <=end || s[i] <= start && s[i] >=end) v.get((int)(s[i])-96).add(i+1); } int val = Math.abs(start-end); int m = 0; Vector<Integer> ans = new Vector<>(); if(start <= end) { for (int i = start-96 ; i <=end-96 ; i++) for(int j = 0 ; j < v.get(i).size() ; j++) { ans.add(v.get(i).get(j)); m++; } } else { for (int i = start-96 ; i >=end-96 ; i--) for(int j = 0 ; j < v.get(i).size() ; j++){ ans.add(v.get(i).get(j)); m++; } } pw.println(val +" "+m); for (int i = 0 ; i < ans.size() ; i++) pw.print(ans.get(i)+" "); pw.println(); pw.flush(); } } static int I() throws IOException { st.nextToken(); return (int)st.nval; } static long L() throws IOException { st.nextToken(); return (long)st.nval; } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
7c4cf25af0e29f23b5a757537c14a354
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class E { public static void main(String[] args) { FastScanner go = new FastScanner(); OutputStream out = System.out; PrintWriter o = new PrintWriter(out); int t = go.nextInt(); while (t-->0){ String s = go.next(); String alp = "abcdefghijklmnopqrstuvwxyz"; int cost = 0; StringBuilder[] map = new StringBuilder[26]; int m = 0; for (int i = 0; i < 26; i++) { map[i] = new StringBuilder(); } for (int i = 0; i < s.length(); i++) { int i1 = alp.indexOf(s.charAt(i)); map[ i1].append((i+1)); map[i1 ].append(" "); if (s.charAt(0) < s.charAt(s.length()-1) ){ if (s.charAt(i) >= s.charAt(0) && s.charAt(i) <= s.charAt(s.length()-1)){ m++; } }else { if (s.charAt(i) <= s.charAt(0) && s.charAt(i) >= s.charAt(s.length()-1)){ m++; } } } cost = Math.abs(s.charAt(0) - s.charAt(s.length()-1)); // System.out.println(map); int l = alp.indexOf(s.charAt(0)); int r = alp.indexOf(s.charAt(s.length()-1)); if (l == r ){ // System.out.print("1"); o.println(cost + " " + m); o.println( map[l]); } else if ( l < r ){ o.println(cost + " " + m); for (int i = l ; i <= r; i++) { if (map[i] != null){ o.print( map[i]); } } o.println(); } else{ o.println(cost + " " + m); for (int i = l ; i >= r; i--) { if (map[i] != null){ o.print( map[i]); } } o.println(); } } o.close(); } public 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()); } } } /* 5 3 8 6 3 2 2 3 3 5 6 8 5 11 11 1 2 2 8 6 1 7 5 2 9 3 10 4 3 2 3 4 1 2 4 3 4 4 */
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
ee002883842677613c59b03b68f2bb32
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); while(t-->0){ String s = br.readLine(); int[][] arr = new int[s.length()][2]; for(int i=0; i<s.length(); i++){ arr[i][0]=s.charAt(i); arr[i][1]=i; } int first = arr[0][0]; int last = arr[s.length()-1][0]; int cost = arr[0][0]-arr[s.length()-1][0]; Arrays.sort(arr, Comparator.comparingInt(o -> o[0])); boolean start=false; StringBuilder ans = new StringBuilder(); int count = 0; if(cost<=0){ for(int i=0; i<s.length(); i++){ if(arr[i][0]==first&&!start){ start=true; ans.append(1+" "); count++; } if(last<arr[i][0]&&start){ break; } if(start&&arr[i][1]!=0&&arr[i][1]!=s.length()-1){ ans.append((arr[i][1]+1)+" "); count++; } } ans.append(s.length()); count++; } else{ for(int i=s.length()-1; i>=0; i--){ if(arr[i][0]==first&&!start){ start=true; ans.append(1+" "); count++; } if(last>arr[i][0]&&start){ break; } if(start&&arr[i][1]!=0&&arr[i][1]!=s.length()-1){ ans.append((arr[i][1]+1)+" "); count++; } } ans.append(s.length()); count++; } pw.println(Math.abs((int)(s.charAt(0)-s.charAt(s.length()-1)))+" "+count); pw.println(ans); } pw.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
5ebbfccd885733b34b28d5ba14767f23
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner scr = new Scanner(System.in); int t = Integer.parseInt(scr.nextLine()); while(t > 0) { char[] c = scr.nextLine().toCharArray(); int l = c.length; List<int[]> base = new ArrayList<>(); base.add(new int[] {c[0]-'a' + 1,1}); base.add(new int[] {c[l-1]-'a' + 1,l}); int dir = (c[0]-'a' + 1) <= (c[l-1]-'a' + 1)?1:-1; Collections.sort(base,(a,b)->a[0] - b[0]); for(int i = 1;i < l-1;i++) { int temp = c[i] - 'a' + 1; if(temp >= base.get(0)[0] && temp <= base.get(1)[0]) { base.add(new int[] {temp,i+1}); } } if(dir < 0)Collections.sort(base,(a,b)->b[0] - a[0]); else Collections.sort(base,(a,b)->a[0] - b[0]); int cost = Math.abs((c[0]-'a' + 1) - (c[l-1]-'a' + 1)); System.out.println(cost + " " + base.size()); System.out.print(1 + " "); for(int[] el:base) if(el[1] != 1 && el[1] != l)System.out.print(el[1]+ " "); System.out.print(l); System.out.println(); t--; } if(scr != null)scr.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
95e5f22b38bfa62531cc6c3623114682
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner scr = new Scanner(System.in); int t = Integer.parseInt(scr.nextLine()); while(t > 0) { char[] c = scr.nextLine().toCharArray(); int l = c.length; List<int[]> base = new ArrayList<>(); // List<int[]> mid = new ArrayList<>(); base.add(new int[] {c[0]-'a' + 1,1}); base.add(new int[] {c[l-1]-'a' + 1,l}); int dir = (c[0]-'a' + 1) <= (c[l-1]-'a' + 1)?1:-1; Collections.sort(base,(a,b)->a[0] - b[0]); for(int i = 1;i < l-1;i++) { int temp = c[i] - 'a' + 1; if(temp >= base.get(0)[0] && temp <= base.get(1)[0]) { base.add(new int[] {temp,i+1}); // mid.add(new int[] {temp,i+1}); } } // Collections.sort(base,(a,b)->a[0] - b[0]); if(dir < 0)Collections.sort(base,(a,b)->b[0] - a[0]); else Collections.sort(base,(a,b)->a[0] - b[0]); // Collections.sort(mid,(a,b)->a[0] - b[0]); int cost = 0; for(int i = 1;i < base.size();i++) cost += Math.abs(base.get(i-1)[0]-base.get(i)[0]); System.out.println(cost + " " + base.size()); System.out.print(1 + " "); for(int[] el:base) if(el[1] != 1 && el[1] != l)System.out.print(el[1]+ " "); System.out.print(l); System.out.println(); t--; } if(scr != null)scr.close(); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
0afa12430940794debd2c89d8fe2144b
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class CP { static Scanner s = new Scanner(System.in); static class pair{ long key; int count; pair(long key , int count){ this.count = count; this.key = key; } } static class sort implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { if(Math.abs(o1) > Math.abs(o2)){ return 1; }else if(Math.abs(o1) < Math.abs(o2))return -1; return 0; } } public static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(new FileInputStream(s))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } static private long gcd(long a , long b){ if(b == 0)return a; return gcd(b , a % b); } static private void printArrayList(ArrayList<Object> al){ String st = ""; for(Object i : al){ st += i + " "; } System.out.println(st); } static private long digitSum(long n){ long sum = 0; while(n != 0){ sum += n%10; n = n/10; } return sum; } static boolean checkPrime(int x){ for(int i = 2; i <= Math.sqrt(x);i++){ if(x % i == 0){ return false; } } return true; } static boolean checkPallindrome(String st){ int i = 0, j = st.length() - 1; while (i <= j){ if(st.charAt(i) != st.charAt(j))return false; i++; j--; } return true; } static boolean checkPowerOfTwo(int n){ final double v = Math.log(n) / Math.log(2); return (int)(Math.ceil(v)) == (int)(Math.floor(v)); } static ArrayList<Long> insert(long n) throws IOException { ArrayList<Long> al = new ArrayList<>(); for(long i =0 ; i < n; i++){ al.add(s.nextLong()); } return al; } static int debugger = 1; static void debug(){ System.out.println("Reached " + debugger++); } static String reverse(String st){ String ans = ""; for(int i = st.length() - 1; i >= 0; i--)ans += st.charAt(i); return ans; } static ArrayList<Long> sortDescendingOrder(ArrayList<Long> al){ Collections.sort(al); ArrayList<Long> ans = new ArrayList<>(); for(int i = al.size() - 1; i >= 0; i--){ ans.add(al.get(i)); } return ans; } static void dfs(int root , Map<Integer , ArrayList<Integer>> children){ if(children.size() == 0)return; for(int i = 0; i < children.size(); i++){ // do operations } } /* ArrayList<Integer> al = new ArrayList<>(); Map<Integer , ArrayList<Integer>> children = new HashMap<>(); for(int i = 0; i < n; i++){ al.add(s.nextInt()); children.put(i + 1 , new ArrayList<>()); } for(int i = 0; i < m; i++){ int x = s.nextInt(); int y = s.nextInt(); ArrayList<Integer> temp = children.get(x); temp.add(y); children.put(x , temp); } */ //funtions that you have ramakant // a sort (comparator) // gcd // digitSum // checkPrime (sqrt method) // checkPallindrome (two pointer) // checkPowerOfTwo (log method) // reverse a string // dfs of graph / tree // insert in arrayList // print ArrayList // sort ArrayList in descending order public static void main(String[] args) { try { StringBuffer sb = new StringBuffer(); ArrayList<Long> al; int t = s.nextInt(); while (t-- > 0) { String st = s.next(); List<Integer>[] arr = new ArrayList[26]; for(int i = 0; i < 26; i++){ arr[i] = new ArrayList<>(); } for(int i = 0; i < st.length(); i++){ arr[st.charAt(i) - 'a'].add(i); } ArrayList<Integer> res = new ArrayList<>(); // res.add(0); if(st.charAt(0) <= st.charAt(st.length() - 1)){ for(int i = st.charAt(0) - 'a'; i <= st.charAt(st.length() - 1) - 'a'; i++){ for(int j : arr[i]){ res.add(j); } } }else{ for(int i = st.charAt(0) - 'a'; i >= st.charAt(st.length() - 1) - 'a'; i--){ for(int j : arr[i]){ res.add(j); } } } // res.add(st.length() - 1); sb.append(Math.abs(st.charAt(0) - st.charAt(st.length() - 1)) +" " + res.size() +"\n"); for(int i = 0; i < res.size(); i++){ sb.append((res.get(i) + 1) + (i == res.size() - 1 ? "\n" : " ")); } } System.out.println(sb); }catch (Exception e){ e.printStackTrace(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
7e67c97a9ba3d767b9bfbed0bbcb38c4
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.Collectors; import java.net.*; public class P03 { 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());} float nextFloat(){return Float.parseFloat(next());} String nextLine(){ String str = ""; try { str = br.readLine(); }catch(IOException e) { e.printStackTrace(); } return str ; } } static class CPair { char ch ; Integer index; public CPair(char ch,Integer ind) { this.ch =ch; index=ind; } int getIndex() { return index; } char getChar() { return ch; } } static class BPair { Integer index;boolean value; public BPair(Integer index, boolean value) {this.value =value;this.index =index;} int getIndex() {return index;} boolean getValue() {return value;} } static class Pair implements Comparable<Pair> { Integer index,value; public Pair(Integer index, Integer value) {this.value = value;this.index = index;} @Override public int compareTo(Pair o){return value - o.value;} int getValue(){ return value;} int getindex(){return index;} } private static long gcd(long l, long m){ if(m==0) {return l;} return gcd(m,l%m); } static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int partition(int[] arr, int low, int high){ long pivot = arr[high]; int i = (low - 1); for(int j = low; j <= high - 1; j++){ if (arr[j] < pivot){ i++; swap(arr, i, j); } } swap(arr, i + 1, high); return (i + 1); } static void quickSort(int[] arr, int low, int high){ if (low < high){ int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } static long M = 1000000007; static long powe(long a,long b) { long res =1; while(b>0){ if((b&1)!=0) { res=(res*a)&M; } a=(a*a)%M; b>>=1; } return res; } 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; } static boolean [] seive(int n) { boolean a[] = new boolean[n+1]; Arrays.fill(a, true); a[0]=false; a[1]=false; for(int i =2;i<=Math.sqrt(n);i++) { for(int j =2*i;j<=n;j+=i) { a[j]=false; } } return a; } private static String swap(String s, int i, int j){ if(i>=j)return s; String ans = s.substring(0,i); ans+=s.charAt(j); ans+=s.substring(i+1,j); ans+=s.charAt(i); ans+=s.substring(j+1); return ans; } private static void pa(char[] cs){for(int i =0;i<cs.length;i++){System.out.print(cs[i]+" ");}System.out.println();} private static void pa(long[] b){for(int i =0;i<b.length;i++) {System.out.print(b[i]+" ");}System.out.println();} private static void pm(Character[][] a){for(int i =0;i<a.length;i++){for(int j=0;j<a[i].length;j++){System.out.print(a[i][j]);}System.out.println();}} private static void pm(int [][] a) {for(int i =0;i<a.length;i++) {for(int j=0;j<a[0].length;j++) {System.out.print(a[i][j]+" ");}System.out.println();}} private static void pa(int[] a){for(int i =0;i<a.length;i++){System.out.print(a[i]+" ");}System.out.println();} private static boolean isprime(int n){if (n <= 1) return false;else if (n == 2) return true;else if (n % 2 == 0) return false;for (int i = 3; i <= Math.sqrt(n); i += 2){if (n % i == 0) return false;}return true;} static int lb(int[] b, long a){ int l=-1,r=b.length; while(l+1<r) { int m=(l+r)>>>1; if(b[m]>=a) r=m; else l=m; } return r; } static int ub(long a[], long x){ int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static //MAIN FUNCTION -------> ArrayList<String> alpos = new ArrayList<>(); public static void main(String[] args) throws IOException { long start2 = System.currentTimeMillis(); FastReader fs = new FastReader(); PrintWriter write = new PrintWriter(System.out); Scanner sc = new Scanner (System.in); int t =1; t = fs.nextInt(); while(t-->0) { String s = fs.next(); List<Integer> [] cList = new List[26]; for(int i =0;i<26;i++) { cList[i]=new ArrayList<Integer>(); } for(int i =0;i<s.length();i++) { cList[s.charAt(i)-'a'].add(i+1); } char first = s.charAt(0); char last = s.charAt(s.length()-1); int diff = last>first ?1:-1; int c=0; StringBuilder sb = new StringBuilder(); for(char ch = first;;ch+=diff) { for(int num:cList[ch-'a']) { sb.append(num); sb.append(" "); c++; } if(ch==last)break; } sb.setLength(sb.length()-1); diff = Math.abs(first-last); System.out.println(diff+" "+c); System.out.println(sb); } } } /* */
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
29ba002bba4eb85913285380a9bb37ca
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*;import java.lang.*;import java.util.*; //* --> number of prime numbers less then or equal to x are --> x/ln(x) //* --> String concatenation using the + operator within a loop should be avoided. Since the String object is immutable, each call for concatenation will // result in a new String object being created. // THE SIEVE USED HERE WILL RETURN A LIST CONTAINING ALL THE PRIME NUMBERS TILL N public class codechef {static FastScanner sc;static PrintWriter pw;static class FastScanner {InputStreamReader is;BufferedReader br;StringTokenizer st; public FastScanner() {is = new InputStreamReader(System.in);br = new BufferedReader(is);} String next() throws Exception {while (st == null || !st.hasMoreElements())st = new StringTokenizer(br.readLine()); return st.nextToken();}int nextInt() throws Exception {return Integer.parseInt(next());}long nextLong() throws Exception { return Long.parseLong(next());}int[] readArray(int num) throws Exception {int arr[]=new int[num]; for(int i=0;i<num;i++)arr[i]=nextInt();return arr;}String nextLine() throws Exception {return br.readLine(); }} public static boolean power_of_two(int a){if((a&(a-1))==0){ return true;}return false;} static boolean PS(double x){if (x >= 0) {double i= Math.sqrt(x);if(i%1!=0){ return false;}return ((i * i) == x);}return false;}public static int[] ia(int n){int ar[]=new int[n]; return ar;}public static long[] la(int n){long ar[]=new long[n];return ar;} public static void print(int ans,int t){System.out.println("Case"+" "+"#"+t+":"+" "+ans);} static long mod=1000000007;static int max=Integer.MIN_VALUE;static int min=Integer.MAX_VALUE; public static void sort(long[] arr){//because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Long> ls = new ArrayList<Long>();for(long x: arr)ls.add(x);Collections.sort(ls); for(int i=0; i < arr.length; i++)arr[i] = ls.get(i);}public static long fciel(long a, long b) {if (a == 0) return 0;return (a - 1) / b + 1;} static boolean[] is_prime = new boolean[1000001];static ArrayList<Integer> list = new ArrayList<>(); static long n = 1000000;public static void sieve() {Arrays.fill(is_prime, true); is_prime[0] = is_prime[1] = false;for (int i = 2; i * i <= n; i++) { if (is_prime[i]) {for (int j = i * i; j <= n; j += i)is_prime[j] = false;}}for (int i = 2; i <= n; i++) { if (is_prime[i]) {list.add(i);}}} // ---------- NCR ---------- \ static int NC=100005; static long inv[]=new long[NC]; static long fac_inv[]=new long[NC]; static long fac[]=new long[NC];public static void initialize() { long MOD=mod; int i; inv[1]=1; for(i=2;i<=NC-2;i++) inv[i]=(MOD-MOD/i)*inv[(int)MOD%i]%MOD; fac[0]=fac[1]=1; for(i=2;i<=NC-2;i++) fac[i]=i*fac[i-1]%MOD; fac_inv[0]=fac_inv[1]=1; for(i=2;i<=NC-2;i++) fac_inv[i]=inv[i]*fac_inv[i-1]%MOD; } public static long ncr(int n,int r) { long MOD=mod; if(n<r) return 0; return (fac[n]*fac_inv[r]%MOD)*fac_inv[n-r]%MOD; } // ---------- NCR ---------- \ // ---------- FACTORS -------- \ static int div[][] = new int[1000001][]; public static void factors() { int divCnt[] = new int[1000001]; for(int i = 1000000; i >= 1; --i) { for(int j = i; j <= 1000000; j += i) divCnt[j]++; } for(int i = 1; i <= 1000000; ++i) div[i] = new int[divCnt[i]]; int ptr[] = new int[1000001]; for(int i = 1000000; i >= 1; --i) { for(int j = i; j <= 1000000; j += i) div[j][ptr[j]++] = i; } } // ---------- FACTORS -------- \ // ------------- DSU ---------------\ static int par[]=new int[1000001];static int size[]=new int[1000001]; public static void make(int v){par[v]=v;size[v]++;} public static void union(int a,int b){a=find(a);b=find(b); if(a!=b){if(size[a]<size[b]){int temp=a;a=b;b=temp;}par[b]=a; size[a]++;}}public static int find(int v) {if(v==par[v]){return v;}return par[v]=find(par[v]);} // ------------- DSU ---------------\ static class pair{ int idx; int ch; pair(int idx,int ch) { this.idx=idx; this.ch=ch; } } public static void main(String args[]) throws java.lang.Exception { sc = new FastScanner();pw = new PrintWriter(System.out);StringBuilder s = new StringBuilder(); int t=sc.nextInt(); while(t-->0) { String str=sc.next(); ArrayList<pair> list=new ArrayList<>(); int min=Math.min(str.charAt(0)-'a',str.charAt(str.length()-1)-'a'); int max=Math.max(str.charAt(0)-'a',str.charAt(str.length()-1)-'a'); for(int i=0;i<str.length();i++) { int id=str.charAt(i)-'a'; if(id>=min&&id<=max) { list.add(new pair(i+1,id)); } } if(str.charAt(0)<=str.charAt(str.length()-1)) { Collections.sort(list,(a,b)->a.ch-b.ch); } else{ Collections.sort(list,(a,b)->b.ch-a.ch); } s.append((max-min)+" "+list.size()+"\n"); for(pair i:list) { s.append(i.idx+" "); } if(t>0) { s.append("\n"); }} pw.print(s);pw.close();}}
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
c239d9ae5baf96a8b7b333d4d5eea77f
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" onlx if the class is public. */ public class codeforces { static class pair{ int index; int value; pair(int index,int value){ this.index=index; this.value=value; } } static Scanner sc=new Scanner(System.in); public static void solve() { String str=sc.next(); int arr[]=new int[str.length()]; for(int i=0;i<str.length();i++){ arr[i]=(int)(str.charAt(i)-96); } int count=arr[str.length()-1]-arr[0]; int order=0; if(count>0){ order=1; }else if(count<0){ order=-1; }else{ order=2; } ArrayList<pair> list=new ArrayList<>(); int cutoff=arr[0]; int max=arr[str.length()-1]; int last=cutoff; for(int i=1;i<str.length()-1;i++){ if(order==1){ if(cutoff<=arr[i]&&max>=arr[i]){ list.add(new pair(i+1, arr[i])); } }else if(order==-1){ if(cutoff>=arr[i]&&max<=arr[i]){ list.add(new pair(i+1, arr[i])); } }else{ if(cutoff==arr[i]){ list.add(new pair(i+1, arr[i])); } } } int total=0; System.out.println(Math.abs(count)+" "+(list.size()+2)); if(order==-1){ Collections.sort(list,new Comparator<pair>() { @Override public int compare(codeforces.pair o1, codeforces.pair o2) { return o2.value-o1.value; } }); }else{ Collections.sort(list,new Comparator<pair>() { @Override public int compare(codeforces.pair o1, codeforces.pair o2) { return o1.value-o2.value; } }); } System.out.print("1 "); for(int i=0;i<list.size();i++){ System.out.print(list.get(i).index+" "); total+=Math.abs(list.get(i).value-last); last=list.get(i).value; }System.out.println(str.length()); total+=Math.abs(last-arr[str.length()-1]); // System.out.println(total); } public static void main(String[] args) { int t=sc.nextInt(); while(t-->0){ solve(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
b9beab81ff5a485051e7af726dcf8b81
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.StringTokenizer; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class div3820C { public static void main(String[] args) throws IOException { //nerealno class Par { char c; int indeks; public Par(char c, int indeks) { this.c = c; this.indeks = indeks; } } class poredi implements Comparator<Par> { public int compare(Par o1, Par o2) { return o1.c - o2.c; } } Scanner in = new Scanner(System.in); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int tt = Integer.parseInt(st.nextToken()); for(int w = 0; w<tt; w++) { st = new StringTokenizer(br.readLine()); String s = st.nextToken(); int n = s.length(); int mincost = Math.abs(s.charAt(n-1)-s.charAt(0)); int[] niz = new int[n]; Par[] niz1 = new Par[n]; int cnt = 0; int suma = 0; int cnt2 = 1; niz[0] = 1; niz[n-1] = n; if(n==2) { suma = Math.abs(s.charAt(0)-s.charAt(1)); log.write(suma+" "+2+"\n"); log.write(1+" "+2); } else { if((int) s.charAt(0)>(int) s.charAt(n-1)) { for(int i = 1; i<n-1; i++) { if(s.charAt(i)<=s.charAt(0) && s.charAt(i)>=s.charAt(n-1)) { niz1[cnt] = new Par(s.charAt(i),i); cnt++; } } if(cnt==0) { log.write(mincost+" "+2+"\n"); log.write(1+" "+n); log.write("\n"); log.flush(); continue; } Arrays.sort(niz1,0,cnt,new poredi()); for(int i = cnt-1; i>=0; i--) { niz[cnt2] = niz1[i].indeks+1; cnt2++; } } else if((int) s.charAt(0)== (int) s.charAt(n-1)) { for(int i = 1; i<n-1; i++) { if(s.charAt(i) == s.charAt(0)) { niz1[cnt] = new Par(s.charAt(i),i); cnt++; } } for(int i = 0; i<cnt; i++) { niz[cnt2] = niz1[i].indeks+1; cnt2++; } } else { for(int i = 1; i<n-1; i++) { if(s.charAt(i)>=s.charAt(0) && s.charAt(i)<=s.charAt(n-1)) { niz1[cnt] = new Par(s.charAt(i),i); cnt++; } } if(cnt==0) { log.write(mincost+" "+2+"\n"); log.write(1+" "+n); log.write("\n"); log.flush(); continue; } Arrays.sort(niz1,0,cnt,new poredi()); for(int i = 0; i<cnt; i++) { niz[cnt2] = niz1[i].indeks+1; cnt2++; } } int counter = 0; for(int i = 0; i<n; i++) { if(niz[i]!=0) { counter++; } } log.write(mincost+" "+counter+"\n"); for(int i = 0; i<n; i++) { if(niz[i]!=0) { log.write(niz[i]+" "); } } } log.write("\n"); log.flush(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
e9ac24eb2e44122ee76d6439f81cc0ca
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); sc.nextLine(); while (q -- > 0) { String s = sc.nextLine(); int n = s.length(); int min = Math.min(s.charAt(0), s.charAt(n - 1)) - 'a'; int max = Math.max(s.charAt(0), s.charAt(n - 1)) - 'a'; int step = 1; if (s.charAt(0) > s.charAt(n - 1)) step = -1; Map<Character, List<Integer>> map = new HashMap<>(); for (int i = 0; i < 26; i ++) { map.put((char)('a' + i), new ArrayList<>()); } for (int i = 0; i < n; i++) { List<Integer> list = map.get(s.charAt(i)); list.add(i + 1); map.put(s.charAt(i), list); } int count = 0; List<Integer> ans = new ArrayList<>(); if (step == 1) for (int i = s.charAt(0); i <= s.charAt(n - 1); i += 1) { List<Integer> l = map.get((char) i); count += l.size(); ans.addAll(l); } else for (int i = s.charAt(0); i >= s.charAt(n - 1); i += -1) { List<Integer> l = map.get((char) i); count += l.size(); ans.addAll(l); } System.out.println(max - min + " " + count); for(int num : ans) { System.out.print(num + " "); } System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
2b83a6ab0c97d26903f1d51a05ac004f
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class b implements Runnable{ static ContestScanner in = new ContestScanner(); static ContestPrinter out = new ContestPrinter(); public static void main(String[] args) { new Thread(null, new b(), "main", 1<<28).start(); } static class pair implements Comparable<pair>{ public char val; public int index; public pair(char value , int idx){ this.val = value; this.index = idx; } public pair getVal() { return this; } @Override public int compareTo(b.pair o) { // TODO Auto-generated method stub if (o.val == this.val) { return (o.index < this.index ? 1 : -1); } return (this.val > o.val ? 1 : -1); } } public void run() { int tests = in.nextInt(); for (int t = 0; t < tests; t++) { String s = in.next(); ArrayList<pair> all = new ArrayList<>(); char []ss = s.toCharArray(); // if (ss[0] < ss[ss.length-1]) // Collections.reverse(all); for (int i = 1 ; i < ss.length-1 ; i++) { if (ss[i] >= Math.min(ss[0] , ss[ss.length - 1]) && ss[i] <= Math.max(ss[0],ss[ss.length - 1])) { all.add(new pair(ss[i] , i)); } } Collections.sort(all); if (ss[0] > ss[ss.length-1])Collections.reverse(all); int ans1 = Math.abs(ss[0] - ss[ss.length - 1]); out.print(ans1 + " " + (all.size()+2)); out.println(); out.print(1 + " "); for (int i = 0 ; i < all.size() ; i++) { out.print(all.get(i).index+1 + " "); } out.println(ss.length); } out.close(); } static class ContestScanner { private final java.io.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 ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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("%d%s... is not number", n, Character.toString(b)) ); } } } 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("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } 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[] 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 ContestPrinter extends java.io.PrintWriter{ public ContestPrinter(java.io.PrintStream stream){ super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException{ super(new java.io.PrintStream(file)); } public ContestPrinter(){ 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; if(n==0){ super.println(); return; } 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; if(n==0){ super.println(); return; } 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; if(n==0){ super.println(); return; } 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; if(n==0){ super.println(); return; } 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 <T> void printArray(T[] array, String separator){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(array[i]); super.print(separator); } super.println(array[n-1]); } public <T> void printArray(T[] array){ this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map){ int n = array.length; if(n==0){ super.println(); return; } for(int i=0; i<n-1; i++){ super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n-1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map){ this.printArray(array, " ", map); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
1c2727284f5725947e8662d7ee79d948
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.System.*; public class M { public static void main(String[] args) { FastScanner x = new FastScanner(); int t = x.nextInt(); while (t-- > 0){ Long max = (long) Integer.MIN_VALUE; Long min = (long)Integer.MAX_VALUE; Long res = 0L; boolean boo = true; String s = x.nextLine(); char[] arr = s.toCharArray(); ArrayList<Integer> rez = new ArrayList<>(); int mi = Math.min(arr[0],arr[arr.length - 1]); int ma = Math.max(arr[0],arr[arr.length - 1]); for (int i = 0; i < arr.length; i++) { if (mi <= arr[i] && arr[i] <= ma){ rez.add(i); } } Collections.sort(rez,(a,b) ->{ if (arr[a] != arr[b]){ return Integer.compare(Math.abs(arr[a] - arr[0]),Math.abs(arr[b] - arr[0])); }else{ return Integer.compare(a,b); } }); out.println((ma - mi) + " " + rez.size()); for (int i : rez){ out.print((i + 1) + " "); }out.println(); } }static boolean ch(List<Integer> l){ int n = l.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { Integer target = l.get(i) + l.get(j) + l.get(k); if (!l.contains(target)){ return false; } } } }return true; } static boolean bin(int[] arr,int target){ int l = 0; int r = arr.length - 1; while (l <= r){ int mid = l + (r - l) / 2; if (arr[mid] == target){ return true; } else if (arr[mid] > target) { r = mid - 1; }else{ l = mid + 1; } }return false; } static Long getmax(Long[] arr){ Long max = (long) Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { max = Math.max(max,arr[i]); }return max; } static String getter(String s, int ind,int len){ char a1 = s.charAt(ind); char a2 = s.charAt(len); StringBuilder res = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (i == ind){ res.append(a2); } else if (i == len) { res.append(a1); }else{ res.append(s.charAt(i)); } } return res.toString(); } static int shift(Integer[] arr,int l,int r,int k){ Integer[] sarr = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) { sarr[i] = arr[i]; } for (int i = 0; i < k; i++) { for (int j = l - 1; j < r - 1; j++) { arr[j + 1] = arr[j]; } out.println(Arrays.toString(arr)); } return arr[arr.length - 1] - arr[0]; } static int lowerbound(Long[] arr,Long target){ // we can find smallest element in the list that equal or bigger than the target if(arr == null || arr.length == 0){ return -1; } int l = 0; int r = arr.length - 1; while (l < r){ int mid = (l + r) / 2; if (arr[mid] < target){ l = mid + 1; }else{ r = mid; } } if (arr[l] >= target){ return l; } return -1; } static int upperbound(Long[] arr,Long target){ // we can find smallest element in the list that bigger than the target if (arr == null || arr.length == 0){ return -1; } int l = 0; int r = arr.length - 1; while (l < r){ int mid = (l + r) / 2; if (arr[mid] <= target){ l = mid + 1; }else { r = mid; } } return arr[l] > target ? l : -1; } public static void rec(int N,String cur) { if (cur.length() == N) { out.println(cur); return; } rec(N, cur + "0"); rec(N, cur + "1"); rec(N,cur + "2"); } public static int intfromstring(String s){ String[] nums = {"zero","one","two","three","four","five","six","seven","eight","nine","ten"}; for (int i = 0; i < nums.length; i++) { if (s.equals(nums[i])){ return i; } }return -1; } public static long NOK(long a,long b){ return lcm(a,b); }static long gcd(long a,long b){ return b == 0 ? a : gcd(b,a % b); }static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static long sum(long a){ return a * (a - 1) / 2; } static boolean odd(int e){ return e % 2 == 1; }static boolean even(int e){ return e % 2 == 0; } 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; (long) i * i <= n; i = i + 6){ if (n % i == 0 || n % (i + 2) == 0){ return false;}} return true; }static String arrtostring(long res[]){ return Arrays.toString(res).replace(",","").replace("[","").replace("]",""); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextLine() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextLine()); } long nextLong() { return Long.parseLong(nextLine()); } double nextDouble() { return Double.parseDouble(nextLine()); } Integer[] readArray(int n) { Integer[] a=new Integer[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } Long[] readArrayLong(int n) { Long[] a=new Long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
5143e72baa2a321a9e44fd8e647fe98a
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { 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(); } } static class SortingString { int oldIndex; char ch; public SortingString(int oldIndex, char ch) { this.oldIndex = oldIndex; this.ch = ch; } } static class SortingComparator implements Comparator<SortingString> { public int compare(SortingString a, SortingString b) { return a.ch - b.ch; } } public static void main(String[] args) throws IOException { Reader s = new Reader(); Scanner sc = new Scanner(System.in); try { // int t= s.nextInt(); BufferedReader bu = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String[] str = bu.readLine().split(" "); int t = Integer.parseInt(str[0]); while (t-- > 0) { // int n = s.nextInt(); // int[] ar = new int[100001]; // for(int i=0;i<n;i++) ar[s.nextInt()]=i; // int m = s.nextInt(); // int[] mQuery = new int[m]; // for(int i=0;i<m;i++) mQuery[i]=s.nextInt(); // solve(n,ar,m,mQuery); str = bu.readLine().split(" "); solve(str[0]); } } catch (Exception e) { return; } } // public static void solve(int n, int[] ar, int m, int[] mQuery){ // int countFirst =0, countLast=0; // for(int i=0;i<m;i++){ // int index = ar[mQuery[i]]; // countFirst+=index+1; // countLast+=n-index; // } // System.out.println(countFirst+" "+countLast); // } public static void solve(String s) { s = s.trim(); char[] ar = s.toCharArray(); // char ss = ch[0]; // int jumps = 0, cost = 0; // StringBuilder ans = new StringBuilder(); // StringBuilder ans2 = new StringBuilder(); // cost = Math.abs((int) ch[0] - (int) ch[s.length() - 1]); // ans2.append(cost).append(" "); // int j = 0; // StringBuilder[] position = new StringBuilder[26]; // for (int i = 0; i < 26; i++) { // position[i] = new StringBuilder(); // } // int n = s.length(); // int[] a = new int[n]; // for (int i = 0; i < n; i++) { // a[i] = ch[i] - 'a'; // position[a[i]].append(i + 1).append(" "); // } //// System.out.println("positon: "+Arrays.toString(position)); // StringBuilder output = new StringBuilder(); // if (a[0] < a[n - 1]) { // for (int i = a[0]; i <=a[n - 1]; ++i) { // if (position[i].length() > 0) { // output.append(position[i]); // jumps+=(position[i].length())/2; // } // } // } else { // for (int i = a[0]; i >= a[n - 1]; --i) { // if (position[i].length() > 0) { // output.append(position[i]); // jumps+=(position[i].length()+1)/2; // } // } // } //// jumps = (output.length()+1)/2; // // // ans2.append(jumps); // System.out.println(ans2); // System.out.println(output); StringBuilder sb = new StringBuilder(); int n = ar.length; int[] a = new int[n]; ArrayList<Integer>[] pos = new ArrayList[26]; for(int i=0; i<26; ++i) pos[i] = new ArrayList<>(); for(int i=0; i<n; ++i) { a[i] = ar[i] - 'a'; pos[a[i]].add(i); } int cost = Math.abs(a[0]-a[n-1]); ArrayList<Integer> jumps = new ArrayList<>(); if(a[0]<a[n-1]){ for(int i=a[0]; i<=a[n-1]; ++i) if(pos[i].size()>0) for(int x: pos[i]) jumps.add(x+1); } else{ for(int i=a[0]; i>=a[n-1]; --i) if(pos[i].size()>0) for(int x: pos[i]) jumps.add(x+1); } sb.append(cost+" "+jumps.size()+"\n"); for(int x: jumps) sb.append(x+" "); sb.append("\n"); System.out.print(sb); } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
081c6d7e13592cc498c3beac65d32c69
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Scanner; public class Jumping_On_Tiles { static class Pair implements Comparable<Pair>{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return o.x - this.x; } } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while(t > 0){ String s = scan.next(); t--; solve(s); } } public static void solve(String s){ int n = s.length(); if (s.charAt(0) < s.charAt(n - 1)) { int amount = s.charAt(n - 1) - s.charAt(0); int min = 2; ArrayList<Pair> ls = new ArrayList<>(); for (int i = 1; i < n - 1; i++) { if (s.charAt(i) >= s.charAt(0) && s.charAt(i) <= s.charAt(n - 1)) { min++; ls.add(new Pair(s.charAt(i) - 'a' + 1, i + 1)); } } Collections.sort(ls, Collections.reverseOrder()); System.out.println(amount + " " + min); System.out.print(1 + " "); for (Pair p : ls) { System.out.print(p.y + " "); } System.out.print(n + " "); System.out.println(); } else if (s.charAt(0) > s.charAt(n - 1)) { int amount = s.charAt(0) - s.charAt(n - 1); int min = 2; ArrayList<Pair> ls = new ArrayList<>(); for (int i = 1; i < n - 1; i++) { if (s.charAt(i) <= s.charAt(0) && s.charAt(i) >= s.charAt(n - 1)) { min++; ls.add(new Pair(s.charAt(i) - 'a' + 1, i + 1)); } } Collections.sort(ls); System.out.println(amount + " " + min); System.out.print(1 + " "); for (Pair p : ls) { System.out.print(p.y + " "); } System.out.print(n + " "); System.out.println(); } else { int amount = 0; int min = 1; ArrayList<Integer> ls = new ArrayList<>(); ls.add(1); for (int i = 1; i < n; i++) { if (s.charAt(i) == s.charAt(0)) { min++; ls.add(i + 1); } } System.out.println(amount + " " + min); for (int x : ls) { System.out.print(x + " "); } System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
06be9d5b531235bdba944b1604ae294f
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class C_Jumping_on_Tiles { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try {br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out);} catch(Exception e) { 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; } } // end of fast i/o code public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); while(t-->0){ String str = in.nextLine(); // HashMap<Integer,Integer> m = new HashMap<>(); ArrayList<Pair> list1 = new ArrayList<>(); int firsValue = (int)str.charAt(0)-96; int lastValue = (int)str.charAt(str.length()-1)-96; int score = Math.abs(lastValue-firsValue); int sV = Math.min(firsValue,lastValue); int gV = Math.max(firsValue,lastValue); ArrayList<Integer> list = new ArrayList<>(); list.add(1); System.out.println(); for(int i=1;i<=str.length()-2;i++){ list1.add(new Pair(i, Math.abs((int)str.charAt(0)-(int)str.charAt(i)))); } Collections.sort(list1,new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.b==o2.b){ return o1.a-o2.a; } else{ return o1.b-o2.b; } } }); for(int i=0;i<list1.size();i++){ // if( // list.add(); if((int)str.charAt(list1.get(i).a)-96>=sV && (int)str.charAt(list1.get(i).a)-96<=gV){ list.add(list1.get(i).a+1); } else continue; } list.add(str.length()); System.out.println(score+" "+list.size()); for(int i=0;i<list.size();i++){ System.out.print(list.get(i)+" "); } } }} class Pair{ int a; int b; Pair(int c,int d){ this.a = c; this.b = d; } } // c is 3 and s is 19 so score is 19-3 //
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
3abb1a0be61d94c68354ac991b722afc
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; import java.io.*; public class C_Jumping_on_Tiles { // For fast input output static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { try {br = new BufferedReader( new FileReader("input.txt")); PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out);} catch(Exception e) { 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; } } // end of fast i/o code public static void main(String[] args) { FastReader in = new FastReader(); int t = in.nextInt(); while(t-->0){ String str = in.nextLine(); // HashMap<Integer,Integer> m = new HashMap<>(); ArrayList<Pair> list1 = new ArrayList<>(); int firsValue = (int)str.charAt(0)-96; int lastValue = (int)str.charAt(str.length()-1)-96; int score = Math.abs(lastValue-firsValue); int sV = Math.min(firsValue,lastValue); int gV = Math.max(firsValue,lastValue); ArrayList<Integer> list = new ArrayList<>(); list.add(1); // for(int i=1;i<str.length()-1;i++){ // if((int)str.charAt(i)-96>=sV && (int)str.charAt(i)-96<=gV){ // list.add(i+1); // } // } // list.add(str.length()); // for(int i=0;i<list.size();i++){ // System.out.print(list.get(i)+" "); // } System.out.println(); // ArrayList<Integer> list = new ArrayList<>(); // int max = 0; // int idx = 0; // // if(str.length()==2){ // // System.out.println(score+" "+2); // // System.out.println(1+" "+2); // // continue; // // } // for(int i=0;i<str.length();i++){ // if((int)str.charAt(i)-96>max){ // // max = Math.abs((int)str.charAt(0)-(int)str.charAt(i)); // max = (int)str.charAt(i)-96; // idx = i; // } // // m.put(i,str.charAt(i)-96); // } // int match = 1; // // for(int i=0;i<str.length()-1;i++){ // // if(str.charAt(i)==str.charAt(i+1)){ // // match++; // // } // // } // // if(match==str.length()){ // // System.out.println(0+" "+str.length()); // // for(int i=1;i<=str.length();i++){ // // System.out.print(i+" "); // // } // // System.out.println(); // // continue; // // } for(int i=1;i<=str.length()-2;i++){ list1.add(new Pair(i, Math.abs((int)str.charAt(0)-(int)str.charAt(i)))); } // // Collections.sort(m); // // Map.sort Collections.sort(list1,new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if(o1.b==o2.b){ return o1.a-o2.a; } else{ return o1.b-o2.b; } } }); // if((int)str.charAt(str.length()-1)-96==max){ // max = 0; // } // // System.out.println(list1); // list.add(1); // // System.out.println(max); for(int i=0;i<list1.size();i++){ // if( // list.add(); if((int)str.charAt(list1.get(i).a)-96>=sV && (int)str.charAt(list1.get(i).a)-96<=gV){ list.add(list1.get(i).a+1); } else continue; } list.add(str.length()); // System.out.println(list); // // System.out.println(list); System.out.println(score+" "+list.size()); for(int i=0;i<list.size();i++){ System.out.print(list.get(i)+" "); } // // list.add(1); // System.out.println(); // } } }} class Pair{ int a; int b; Pair(int c,int d){ this.a = c; this.b = d; } } // c is 3 and s is 19 so score is 19-3 //
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
70c521cfe16bf11caa09a13a604bdcfc
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while(t-->0) { String s = sc.nextLine(); char first = s.charAt(0); char last = s.charAt(s.length()-1); int minCost = Math.abs(last - first); ArrayList<Integer> ans = new ArrayList<>(); if(first<last) { for(int i=first; i<=last; i++) { for(int j=0; j<s.length(); j++) { if((char)i == s.charAt(j)) { ans.add(j+1); } } } } else if(first>last) { for(int i=first; i>=last; i--) { for(int j=0; j<s.length(); j++) { if(((char)i) == s.charAt(j)) { ans.add(j+1); } } } } else { for(int i=0; i<s.length(); i++) { if(first==s.charAt(i)) { ans.add(i+1); } } } System.out.println(minCost + " " + ans.size()); for(int i=0; i<ans.size(); i++) { System.out.print(ans.get(i) + " "); } System.out.println(); } } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
919932ef810345895de3574ed222b972
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = true; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { String s = fReader.nextString(); int n = s.length(); List<Integer>[] li = new ArrayList[26]; for(int i=0;i<26;i++) li[i] = new ArrayList<>(); for(int i=0;i<s.length();i++) { li[s.charAt(i)-'a'].add(i); } int x = s.charAt(0)-'a', y = s.charAt(n-1)-'a'; if(x > y) { int temp = x; x = y; y = temp; for(int i=0;i<26;i++) Collections.reverse(li[i]); } int cost = y-x; List<Integer> res = new ArrayList<>(); for(int i=x;i<=y;i++) { res.addAll(li[i]); } if(res.get(0) > 0) Collections.reverse(res); o.println(cost + " " + res.size()); for(int i=0;i<res.size();i++) o.print((res.get(i)+1) + " "); o.println(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static boolean isPrime(long x){ boolean ok = true; for(long i=2;i<=Math.sqrt(x);i++){ if(x % i == 0){ ok = false; break; } } return ok; } public static void reverse(int[] array){ reverse(array, 0 , array.length-1); } public static void reverse(int[] array, int left, int right) { if (array != null) { int i = left; for(int j = right; j > i; ++i) { int tmp = array[j]; array[j] = array[i]; array[i] = tmp; --j; } } } public static long qpow(long a, long n){ long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % mod; } n >>= 1; a = a * a % mod; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] tree; public FenWick(int n){ this.n = n; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
f4b30064463b0ea4cf51f2ed984b8cc5
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = true; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { String s = fReader.nextString(); int n = s.length(); List<Integer>[] li = new ArrayList[26]; for(int i=0;i<26;i++) li[i] = new ArrayList<>(); for(int i=0;i<n;i++) { char c = s.charAt(i); li[c-'a'].add(i); } int fst = s.charAt(0)-'a', lst = s.charAt(n-1)-'a'; if(fst > lst) { int temp = fst; fst = lst; lst = temp; for(int i=0;i<26;i++) { Collections.reverse(li[i]); } } int cost = lst-fst; List<Integer> res = new ArrayList<>(); for(int i=fst;i<=lst;i++) { res.addAll(li[i]); } o.println(cost + " " + res.size()); if(res.get(0) > 0) Collections.reverse(res); for(int i=0;i<res.size();i++) o.print((res.get(i)+1) + " "); o.println(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static boolean isPrime(long x){ boolean ok = true; for(long i=2;i<=Math.sqrt(x);i++){ if(x % i == 0){ ok = false; break; } } return ok; } public static void reverse(int[] array){ reverse(array, 0 , array.length-1); } public static void reverse(int[] array, int left, int right) { if (array != null) { int i = left; for(int j = right; j > i; ++i) { int tmp = array[j]; array[j] = array[i]; array[i] = tmp; --j; } } } public static long qpow(long a, long n){ long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % mod; } n >>= 1; a = a * a % mod; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] tree; public FenWick(int n){ this.n = n; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output
PASSED
6bcd23509230cb8a8050ac82387890aa
train_110.jsonl
1662993300
Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = true; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static void solve(PrintWriter o) { try { String s = fReader.nextString(); int n = s.length(); char fst = s.charAt(0), lst = s.charAt(n-1); int d = 1; if(fst > lst) d = -1; List<Integer>[] li = new ArrayList[26]; for(int i=0;i<26;i++) li[i] = new ArrayList<>(); for(int i=0;i<n;i++) { char c = s.charAt(i); li[c-'a'].add(i); } int ans = Math.abs(lst-fst); List<Integer> res = new ArrayList<>(); for(int i=fst-'a';i-d != lst-'a';i+=d) { for(int idx: li[i]) { res.add(idx); } } o.println(ans + " " + res.size()); for(int idx: res) o.print((idx+1) + " "); o.println(); } catch (Exception e) { e.printStackTrace(); } } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static boolean isPrime(long x){ boolean ok = true; for(long i=2;i<=Math.sqrt(x);i++){ if(x % i == 0){ ok = false; break; } } return ok; } public static void reverse(int[] array){ reverse(array, 0 , array.length-1); } public static void reverse(int[] array, int left, int right) { if (array != null) { int i = left; for(int j = right; j > i; ++i) { int tmp = array[j]; array[j] = array[i]; array[i] = tmp; --j; } } } public static long qpow(long a, long n){ long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % mod; } n >>= 1; a = a * a % mod; } return ret; } public static class DSU { int[] parent; int[] size; int n; public DSU(int n){ this.n = n; parent = new int[n]; size = new int[n]; for(int i=0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(parent[p] != p){ parent[p] = parent[parent[p]]; p = parent[p]; } return p; } public void union(int p, int q){ int root_p = find(p); int root_q = find(q); if(root_p == root_q) return; if(size[root_p] >= size[root_q]){ parent[root_q] = root_p; size[root_p] += size[root_q]; size[root_q] = 0; } else{ parent[root_p] = root_q; size[root_q] += size[root_p]; size[root_p] = 0; } n--; } public int getTotalComNum(){ return n; } public int getSize(int i){ return size[find(i)]; } } public static class FenWick { int n; long[] tree; public FenWick(int n){ this.n = n; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
Java
["6\n\nlogic\n\ncodeforces\n\nbca\n\naaaaaaaaaaa\n\nadbaadabad\n\nto"]
1 second
["9 4\n1 4 3 5\n16 10\n1 8 3 4 9 5 2 6 7 10\n1 2\n1 3\n0 11\n1 8 10 4 3 5 7 2 9 6 11\n3 10\n1 9 5 4 7 3 8 6 2 10\n5 2\n1 2"]
NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.
Java 11
standard input
[ "constructive algorithms", "strings" ]
d17c9f91504e1d4c4eae7294bf09dcfc
The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,100
The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.
standard output