exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
27636d778803d5f3d9f718f86164bd59
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; public class JavaTest { private static final PrintWriter out = new PrintWriter(System.out); private static Scanner sc; public static void main(String[] args) throws Exception { InputStream is = JavaTest.class.getResourceAsStream("in.txt"); boolean testMode = is != null; sc = new Scanner(testMode ? is : System.in); long start = System.currentTimeMillis(); main(); if (testMode) { out.println(); out.print(System.currentTimeMillis() - start + " ms"); } out.close(); } private static void main() throws Exception { int n = sc.nextInt(); int[] arr = new int[n]; int a1 = Integer.MAX_VALUE, a2 = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int a = arr[i] = sc.nextInt(); if (a1 > a) { a2 = a1; a1 = a; } else if (a2 > a) { a2 = a; } } int ans = (a1 + 1) / 2 + (a2 + 1) / 2; for (int i = 1; i < n; i++) { int a = Math.max(arr[i - 1], arr[i]); int b = Math.min(arr[i - 1], arr[i]); int k = a > b * 2 ? (a + 1) / 2 : (a + b + 2) / 3; ans = Math.min(ans, k); } for(int i = 1; i < n-1; i++) { int a = arr[i-1]; int b = arr[i+1]; int k0 = (a+1)/2 + (b+1)/2; int k1 = 1 + a/2 + b/2; int k = Math.min(k0, k1); ans = Math.min(ans, k); } System.out.println(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
1c90ab9d238e1e69bad363130269af8c
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class Main { static int mod = (int)1e9+7; static boolean[] prime = new boolean[10]; static int[][] dir1 = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; static int[][] dir2 = new int[][] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; static { for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i < prime.length; i++) { if (prime[i]) { for (int k = 2; i * k < prime.length; k++) { prime[i * k] = false; } } } } static class JoinSet { int[] fa; JoinSet(int n) { fa = new int[n]; for (int i = 0; i < n; i++) fa[i] = i; } int find(int t) { if (t != fa[t]) fa[t] = find(fa[t]); return fa[t]; } void join(int x, int y) { x = find(x); y = find(y); fa[x] = y; } } static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return a * b / gcd(a, b); } static int get() throws Exception { String ss = bf.readLine(); if (ss.contains(" ")) ss = ss.substring(0, ss.indexOf(" ")); return Integer.parseInt(ss); } static long getx() throws Exception { String ss = bf.readLine(); if (ss.contains(" ")) ss = ss.substring(0, ss.indexOf(" ")); return Long.parseLong(ss); } static int[] getint() throws Exception { String[] s = bf.readLine().split(" "); int[] a = new int[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(s[i]); } return a; } static long[] getlong() throws Exception { String[] s = bf.readLine().split(" "); long[] a = new long[s.length]; for (int i = 0; i < a.length; i++) { a[i] = Long.parseLong(s[i]); } return a; } static String getstr() throws Exception { return bf.readLine(); } static void println() throws Exception { bw.write("\n"); } static void print(int a) throws Exception { bw.write(a + "\n"); } static void print(long a) throws Exception { bw.write(a + "\n"); } static void print(String a) throws Exception { bw.write(a + "\n"); } static void print(int[] a) throws Exception { for (int i : a) { bw.write(i + " "); } println(); } static void print(long[] a) throws Exception { for (long i : a) { bw.write(i + " "); } println(); } static void print(int[][] a) throws Exception { for (int i[] : a) print(i); } static void print(long[][] a) throws Exception { for (long[] i : a) print(i); } static void print(char[] a) throws Exception { for (char i : a) { bw.write(i + ""); } println(); } static long pow(long a, long b) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans *= a; } a *= a; b >>= 1; } return ans; } static int powmod(long a, long b, int mod) { long ans = 1; while (b > 0) { if ((b & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; b >>= 1; } return (int)ans; } static void sort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void sort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[i]; } static void resort(int[] a) { int n = a.length; Integer[] b = new Integer[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[n - 1 - i]; } static void resort(long[] a) { int n = a.length; Long[] b = new Long[n]; for (int i = 0; i < n; i++) b[i] = a[i]; Arrays.sort(b); for (int i = 0; i < n; i++) a[i] = b[n - 1 - i]; } static int max(int a, int b) { return Math.max(a, b); } static int min(int a, int b) { return Math.min(a, b); } static long max(long a, long b) { return Math.max(a, b); } static long min(long a, long b) { return Math.min(a, b); } static int max(int[] a) { int max = a[0]; for (int i : a) max = max(max, i); return max; } static int min(int[] a) { int min = a[0]; for (int i : a) min = min(min, i); return min; } static long max(long[] a) { long max = a[0]; for (long i : a) max = max(max, i); return max; } static long min(long[] a) { long min = a[0]; for (long i : a) min = min(min, i); return min; } static int abs(int a) { return Math.abs(a); } static long abs(long a) { return Math.abs(a); } static void yes() throws Exception { print("Yes"); } static void no() throws Exception { print("No"); } static int[] getarr(List<Integer> list) { int n = list.size(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = list.get(i); return a; } public static void main(String[] args) throws Exception { int n = get(); int[] a = getint(); int t[] = a.clone(); sort(t); int ans = (t[0]+1)/2+(t[1]+1)/2; for(int i = 0;i < n-1;i++){ if(i+2 < n){ int x = min(a[i],a[i+2]), y = max(a[i],a[i+2]), z = a[i+1]; if(x <= z){ y -= x; ans = min(ans,x+(y+1)/2); }else{ x -= z; y -= z; ans = min(ans,z+(x+1)/2+(y+1)/2); } } int x = min(a[i],a[i+1]), y = max(a[i],a[i+1]); if(x > y/2) ans = min(ans,(x+y)/3+((x+y)%3 == 0 ? 0 : 1)); else ans = min(ans,(y+1)/2); } print(ans); bw.flush(); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
e1853600daa9089b89e9cd4397fe6595
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class E { static int x; static void ex(){ x++; } public static void main(String[] args) { FastScanner sc=new FastScanner(); int t=1; PrintWriter pw=new PrintWriter(System.out); while(t-->0) { int n=sc.nextInt(); int[] a=sc.readArray(n); int ans=Integer.MAX_VALUE; for(int i=0;i<n-1;i++){ int x=a[i]; int y=a[i+1]; int cur=0; if(x<y){ int temp=x; x=y; y=temp; } int cnt=Math.min(x-y,(x+1)/2); cur+=cnt; x-=2*cnt; y-=cnt; if(x>0 && y>0){ cur+=(x+y+2)/3; } ans=Math.min(ans,cur); } for(int i=0;i<n-2;i++){ int x=a[i]; int y=a[i+2]; int cur=0; if(x<y){ int temp=x; x=y; y=temp; } cur=(x-y+1)/2; cur+=y; ans=Math.min(ans,cur); } Arrays.sort(a); ans=Math.min(ans,((a[0]+1)/2+(a[1]+1)/2)); pw.println(ans); } pw.flush(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
1da4c3f4de0faddd12230ddab2afe75d
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.Map.Entry; public class codeforces { static int mod = 1000000007; public static void main(String[] args) { FastReader sc = new FastReader(); StringBuilder ss = new StringBuilder(); try { int n = sc.nextInt(); int a[] = new int[n]; for(int i = 0 ; i<n;i++) { a[i] = sc.nextInt(); } long move1 = Long.MAX_VALUE; for(int i = 0 ;i <n-1 ; i++) { long max = Math.max(a[i], a[i+1]); long min = Math.min(a[i],a[i+1]); long temp = 0; if(max>=2*min) { temp = (max +1)/2; } else { temp = (max + min + 2)/3; } move1 = Math.min(move1, temp); } long move2 = Long.MAX_VALUE; for(int i = 0 ; i<n-2 ; i++) { long val = a[i]; long val1 = a[i+2]; long temp = (val)/2 + (val1)/2; if(val%2 != 0 || val1%2 != 0) { temp++; } move2 = Math.min(move2, temp); } Arrays.sort(a); long move3 = (a[0]+1)/2 + (a[1]+1)/2; long ans = Math.min(move2, Math.min(move1, move3)); System.out.println(ans); } catch(Exception e) { System.out.println(e.getMessage()); } } static class Pair1 implements Comparable<Pair1>{ long val; int i; Pair1(long val , int i){ this.val = val; this.i = i; } @Override public int compareTo(Pair1 o) { // TODO Auto-generated method stub return (int) (this.val - o.val); } } static long pow(long a, long b) { long ans = 1; long temp = a; while(b>0) { if((b&1) == 1) { ans*=temp; } temp = temp*temp; b = b>>1; } return ans; } static long ncr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static long fact(long n) { long res = 1; for (int i = 2; i <= n; i++) { res = (res * i); } return res; } static long gcd(long a, long b) { if(b == 0) { return a; } return gcd(b , a%b); } static long lcm(long a, long b) { long pr = a*b; return pr/gcd(a,b); } static ArrayList<Integer> factor(long n) { ArrayList<Integer> al = new ArrayList<>(); for(int i = 1 ; i*i<=n;i++) { if(n%i == 0) { if(n/i == i) { al.add(i); } else { al.add(i); al.add((int) (n/i)); } } } return al; } static class Pair implements Comparable<Pair>{ long a; long b ; int c; Pair(long a, long b, int c){ this.a = a; this.b = b; this.c = c; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub int temp = (int) (this.b - o.b); if(temp == 0) { return (int) (this.a - o.a); } return temp; } } static int[] sieve(int n) { int a[] = new int[n+1]; Arrays.fill(a,-1); a[1] = 1; for(int i = 2 ; i*i <=n ; i++) { if(a[i] == -1) { for(int j = 2*i ; j<=n ; j+=i) { a[j] = 1; } } } int prime = -1; for(int i = n ; i>=1 ; i--) { if(a[i] == 1) { a[i] =prime; } else { prime = i; a[i] = prime; } } return a; } static ArrayList<Long> pf(long n) { ArrayList<Long> al = new ArrayList<>(); while(n%2 == 0) { al.add(2l); n = n/2; } for(long i = 3 ; i*i<=n ; i+=2) { while(n%i == 0) { al.add(i); n = n/i; } } if(n>2) { al.add( n); } return al; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
c05b50bbce14c707a574345d9a4666f4
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.io.*; public class E { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } 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]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int n=input.scanInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=input.scanInt(); } int min1=Integer.MAX_VALUE,min2=Integer.MAX_VALUE; int indx=-1; int tmp=0; for(int i=0;i<n;i++) { if(arr[i]<min1) { min1=arr[i]; indx=i; } } for(int i=0;i<n;i++) { if(i==indx) { continue; } min2=Math.min(min2,arr[i]); } int min=Integer.MAX_VALUE; for(int i=0;i<n-1;i++) { if(Math.max(arr[i], arr[i+1])>2*Math.min(arr[i], arr[i+1])) { int val=Math.max(arr[i], arr[i+1])/2+(Math.max(arr[i], arr[i+1])%2); min=Math.min(min,val); } else { int val=(arr[i]+arr[i+1])/3; if(((arr[i]+arr[i+1])%3)!=0) { val++; } min=Math.min(min,val); } } for(int i=1;i<n-1;i++) { int ll=arr[i-1]; int rr=arr[i+1]; int del=Math.min(ll,rr); ll-=del; rr-=del; int val=del; if(ll>0) { val+=(ll/2)+(ll%2); } if(rr>0) { val+=(rr/2)+(rr%2); } min=Math.min(min,val); } min1=(min1/2)+(min1%2); min2=(min2/2)+(min2%2); min=Math.min(min,min1+min2); ans.append(min+"\n"); System.out.print(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
73b0cad4ed72279bcac4855bb25ce375
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; public class Main { InputStream is; PrintWriter out = new PrintWriter(System.out); ; String INPUT = ""; void run() throws Exception { is = System.in; solve(); out.flush(); out.close(); } public static void main(String[] args) throws Exception { new Main().run(); } public byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; public int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() { // continue; String; charAt; println(); ArrayList; Integer; Long; // long; Queue; Deque; LinkedList; Pair; double; binarySearch; // s.toCharArray; length(); length; getOrDefault; break; // Map.Entry<Integer, Integer> e; HashMap; TreeMap; int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } public double nd() { return Double.parseDouble(ns()); } public char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private int ni() { return (int)nl(); } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-') { minus = true; b = readByte(); } while(true) { if(b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } class Pair { int first; int second; Pair(int a, int b) { first = a; second = b; } } // KMP ALGORITHM void KMPSearch(String pat, String txt) { int M = pat.length(); int N = txt.length(); int lps[] = new int[M]; int j = 0; computeLPSArray(pat, M, lps); int i = 0; while (i < N) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == M) { j = lps[j - 1]; } else if (i < N && pat.charAt(j) != txt.charAt(i)) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } } void computeLPSArray(String pat, int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } int FirstAndLastOccurrenceOfAnElement(int[] arr, int target, boolean findStartIndex) { int ans = -1; int n = arr.length; int low = 0; int high = n-1; while(low <= high) { int mid = low + (high - low)/2; if(arr[mid] > target) high = mid-1; else if(arr[mid] < target) low = mid+1; else { ans = mid; if(findStartIndex) high = mid-1; else low = mid+1; } } return ans; } // Print All Subsequence. static ArrayList<Integer> qwerty = new ArrayList<>(); void printAllSubsequence(int[] arr, int index, int n) { if(index >= n) { for(int i=0; i<qwerty.size(); i++) out.print(qwerty.get(i) + " "); if(qwerty.size() == 0) out.print(" "); out.println(); return; } qwerty.add(arr[index]); printAllSubsequence(arr, index+1, n); qwerty.remove(qwerty.size()-1); printAllSubsequence(arr, index+1, n); } // Print All Subsequence. // Print All Subsequence. with sum k. static ArrayList<Integer> qwerty2 = new ArrayList<>(); void printSubsequenceWithSumK(int[] arr, int index, int K, int sum, int n) { if(index >= n) { if(sum == K) { for(int i=0; i<qwerty2.size(); i++) out.print(qwerty2.get(i) + " "); out.println(); } return; } qwerty2.add(arr[index]); sum += arr[index]; printSubsequenceWithSumK(arr, index+1, K, sum, n); sum -= arr[index]; qwerty2.remove(qwerty2.size()-1); printSubsequenceWithSumK(arr, index+1, K, sum, n); } // Print All Subsequence. with sum k. int[] na(int n) { int[] arr = new int[n]; for(int i=0; i<n; i++) arr[i]=ni(); return arr; } long[] nal(int n) { long[] arr = new long[n]; for(int i=0; i<n; i++) arr[i]=nl(); return arr; } void solve() { int n = ni(); int[] arr = na(n); // First find out 2 minimum values in an array int a1 = Integer.MAX_VALUE, a2 = Integer.MAX_VALUE; for (int i=0; i<n; i++) { int a = arr[i]; if (a1 > a) { a2 = a1; a1 = a; } else if (a2 > a) a2 = a; } // out.println(a1 + " " + a2); int ans = (a1 + 1) / 2 + (a2 + 1) / 2; for (int i=1; i<n; i++) { int a = Math.max(arr[i - 1], arr[i]); int b = Math.min(arr[i - 1], arr[i]); int k = a > b * 2 ? (a + 1) / 2 : (a + b + 2) / 3; ans = Math.min(ans, k); } for (int i=1; i<n-1; i++) { int a = arr[i - 1]; int b = arr[i + 1]; int k0 = (a + 1) / 2 + (b + 1) / 2; int k1 = 1 + (a - 1 + 1) / 2 + (b - 1 + 1) / 2; int k = Math.min(k0, k1); ans = Math.min(ans, k); } out.println(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
34896e6a769817adc210c7172daec89c
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.math.BigInteger; import java.util.*; import static java.lang.System.out; // Name: Tastan Yernar && Email: 210103376@stu.sdu.edu.kz// public class Round_780_Div_3 { static Scanner str = new Scanner(System.in); static ArrayList<Integer> list; final int mod = 1000000007; public static void main(String[] args) { long T = 1; while (T-- > 0) { solve(); } } static void solve() { int n = str.nextInt(); int a[] = new int[n]; list = new ArrayList<>(); for (int i = 0; i < n; i++) { a[i] = str.nextInt(); list.add(a[i]); } Collections.sort(list); int ans = (list.get(0) + 1) / 2 + (list.get(1) + 1) / 2; for (int i = 0; i < n - 2; i++) { if (a[i] < a[i + 2]) { ans = Math.min(ans, a[i] + (a[i + 2] - a[i] + 1) / 2); } else { ans = Math.min(ans, a[i + 2] + (a[i] - a[i + 2] + 1) / 2); } } for (int i = 0; i < n - 1; i++) { ans = Math.min(ans, Math.max(Math.max((a[i] + 1) / 2, (a[i + 1] + 1) / 2), (a[i] + a[i + 1] + 2) / 3)); } out.println(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
bfa9ce268d35ffa39d4ee4994494457f
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class codeforces_786_E { private static void solve(FastIOAdapter in, PrintWriter out) { int n = in.nextInt(); int[] a = in.readArray(n); int[] b = a.clone(); ruffleSort(b); int ans = (b[0] + 1) / 2 + (b[1] + 1) / 2; for (int i = 0; i < n; i++) { if (i - 1 >= 0 && a[i] >= a[i - 1]) { int min = Math.min(a[i], 2 * a[i - 1]); int cur = (a[i - 1] + min + 2) / 3; cur += (a[i] - min + 1) / 2; ans = Math.min(ans, cur); } if (i + 1 < n && a[i] >= a[i + 1]) { int min = Math.min(a[i], 2 * a[i + 1]); int cur = (a[i + 1] + min + 2) / 3; cur += (a[i] - min + 1) / 2; ans = Math.min(ans, cur); } if (i - 1 >= 0 && a[i] >= a[i - 1] && i + 1 < n && a[i] >= a[i + 1] && a[i - 1] % 2 == 1 && a[i + 1] % 2 == 1) { ans = Math.min(ans, a[i - 1] / 2 + a[i + 1] / 2 + 1); } } 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 void ruffleSort(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
a22d46f188feea8d5fc5f98ffca19cbd
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class q5 { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // public static long mod = 1000000007; public static void solve() throws Exception { String[] parts = br.readLine().split(" "); int n = Integer.parseInt(parts[0]); int[] arr = new int[n]; int min = Integer.MAX_VALUE,smin = Integer.MAX_VALUE; parts = br.readLine().split(" "); for(int i = 0;i < n;i++){ arr[i] = Integer.parseInt(parts[i]); if(arr[i] < min){ smin = min; min = arr[i]; }else if(arr[i] < smin) smin = arr[i]; } long ans = min + smin; ans = Math.min(ans,(min + 1) / 2 + (smin + 1) / 2); for(int i = 0;i < n - 1;i++){ int cmin = Math.min(arr[i],arr[i + 1]); int cmax = Math.max(arr[i],arr[i + 1]); if(cmin * 3 >= cmin + cmax){ ans = Math.min(ans,(cmin + cmax + 2) / 3); }else{ cmax -= (cmin * 2); ans = Math.min(ans,cmin + (cmax + 1) / 2); } } for(int i = 0;i < n - 2;i++){ int cmin = Math.min(arr[i],arr[i + 2]); int cmax = Math.max(arr[i],arr[i + 2]); cmax -= cmin; ans = Math.min(ans,cmin + (cmax + 1) / 2); } System.out.println(ans); } public static void main(String[] args) throws Exception { // int tests = Integer.parseInt(br.readLine()); // for (int test = 1; test <= tests; test++) { solve(); // } } // public static ArrayList<Integer> primes; // public static void seive(int n){ // primes = new ArrayList<>(); // boolean[] arr = new boolean[n + 1]; // Arrays.fill(arr,true); // // for(int i = 2;i * i <= n;i++){ // if(arr[i]) { // for (int j = i * i; j <= n; j += i) { // arr[j] = false; // } // } // } // for(int i = 2;i <= n;i++) if(arr[i]) primes.add(i); // } // public static void sort(int[] arr){ // ArrayList<Integer> temp = new ArrayList<>(); // for(int val : arr) temp.add(val); // // Collections.sort(temp); // // for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i); // } // public static void sort(long[] arr){ // ArrayList<Long> temp = new ArrayList<>(); // for(long val : arr) temp.add(val); // // Collections.sort(temp); // // for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i); // } // // public static long power(long a,long b,long mod){ // if(b == 0) return 1; // // long p = power(a,b / 2,mod); // p = (p * p) % mod; // // if(b % 2 == 1) return (p * a) % mod; // return p; // } // public static long modDivide(long a,long b,long mod){ // return ((a % mod) * (power(b,mod - 2,mod) % mod)) % mod; // } // // public static int GCD(int a,int b){ // return b == 0 ? a : GCD(b,a % b); // } // public static long GCD(long a,long b){ // return b == 0 ? a : GCD(b,a % b); // } // // public static int LCM(int a,int b){ // return a * b / GCD(a,b); // } // public static long LCM(long a,long b){ // return a * b / GCD(a,b); // } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
851127e80c9fe7ae5f39f78b3eb45d1f
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class CF1674E extends PrintWriter { CF1674E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1674E o = new CF1674E(); o.main(); o.flush(); } static final int INF = 0x3f3f3f3f; void main() { int n = sc.nextInt(); int[] aa = new int[n]; int a1 = INF, a2 = INF; for (int i = 0; i < n; i++) { int a = aa[i] = sc.nextInt(); if (a1 > a) { a2 = a1; a1 = a; } else if (a2 > a) a2 = a; } int ans = (a1 + 1) / 2 + (a2 + 1) / 2; for (int i = 1; i < n; i++) { int a = Math.max(aa[i - 1], aa[i]); int b = Math.min(aa[i - 1], aa[i]); int k = a > b * 2 ? (a + 1) / 2 : (a + b + 2) / 3; ans = Math.min(ans, k); } for (int i = 1; i < n - 1; i++) { int a = aa[i - 1]; int b = aa[i + 1]; int k0 = (a + 1) / 2 + (b + 1) / 2; int k1 = 1 + (a - 1 + 1) / 2 + (b - 1 + 1) / 2; int k = Math.min(k0, k1); ans = Math.min(ans, k); } println(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 11
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
ec60e012d2f5c476678b36e36bdd02e6
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.io.*; public class BreakingTheWall { 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; } } private static void runWithStd() { FastReader scanner = new FastReader(); PrintWriter output = new PrintWriter(System.out); int t = 1; while (t-- > 0) { int n = scanner.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = scanner.nextInt(); } int ret = solve(nums); System.out.println(ret); } output.close(); } private static int solve(int[] nums) { int min1 = Integer.MAX_VALUE,min2 = Integer.MAX_VALUE; for(int n : nums){ if(n < min1){ min2 = min1; min1 = n; }else if (n < min2){ min2 = n; } } int ret = min1 / 2 + min1 % 2 + min2 / 2 + min2 % 2; for (int i = 1;i<nums.length;i++){ int max = Math.max(nums[i],nums[i - 1]),min = Math.min(nums[i],nums[i - 1]); int cur = 0; if(min * 2 <= max){ cur = max / 2 + max % 2; }else{ cur = (max + min) / 3 + ((max + min) % 3 != 0 ? 1 : 0); } ret = Math.min(ret,cur); } for (int i = 0; i < nums.length - 2; i++) { int max = Math.max(nums[i],nums[i + 2]),min = Math.min(nums[i],nums[i + 2]); int cur = (max - min) / 2 + (max - min) % 2 + min; ret = Math.min(ret,cur); } return ret; } private static void runWithDebug() { Random random = new Random(); int t = 100; while (t-- > 0) { long ts = System.currentTimeMillis(); long delta = System.currentTimeMillis() - ts; System.out.println("case t = " + t + " time = " + delta); } System.out.println("all passed"); } public static void main(String[] args) { runWithStd(); //runWithDebug(); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 17
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
301ecd2ae3cd585f43c476d2900f00fd
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /* * Author: Atuer */ public class Main { // ==== Solve Code ====// static int INF = 1000000010; public static void csh() { } public static void main(String[] args) throws IOException { // csh(); // int t = in.nextInt(); // while (t-- > 0) { solve(); out.flush(); } out.close(); } public static void solve() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); // 1) solo int min1 = INF, min2 = INF; for (int i = 0; i < n; i++) { int b = (a[i] + 1) / 2; if (b <= min1) { min2 = min1; min1 = b; } else if (b < min2) min2 = b; } int ans = min1 + min2; // 2) x|att|att|x 取att 开销=最大值/2(单边过大,一个是另一个两倍及以上) 或 总和/3(两边平均) for (int i = 0; i < n - 1; i++) ans = Math.min(ans, Math.max(Math.max((a[i] + 1) / 2, (a[i + 1] + 1) / 2), (a[i] + a[i + 1] + 2) / 3)); // 3) x|att|x 取x 将奇数变成偶数后(次数+1) 然后左右平均减少1,然后再单个减少(有效伤害均为2),可以直接除以2(不考虑奇数) for (int i = 0; i < n - 2; i++) ans = Math.min(ans, 1 + a[i] / 2 + a[i + 2] / 2); out.println(ans); } public static class Node { int x, y, k; public Node(int x, int y, int k) { this.x = x; this.y = y; this.k = k; } } // ==== Solve Code ====// // ==== Template ==== // public static long cnm(int a, int b) { long sum = 1; int i = a, j = 1; while (j <= b) { sum = sum * i / j; i--; j++; } return sum; } public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } public static void gbSort(int[] a, int l, int r) { if (l < r) { int m = (l + r) >> 1; gbSort(a, l, m); gbSort(a, m + 1, r); int[] t = new int[r - l + 1]; int idx = 0, i = l, j = m + 1; while (i <= m && j <= r) if (a[i] <= a[j]) t[idx++] = a[i++]; else t[idx++] = a[j++]; while (i <= m) t[idx++] = a[i++]; while (j <= r) t[idx++] = a[j++]; for (int z = 0; z < t.length; z++) a[l + z] = t[z]; } } // ==== Template ==== // // ==== IO ==== // static InputStream inputStream = System.in; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(System.out); static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { return false; // TODO: handle exception } } return true; } public String nextLine() { String str = null; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public Double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } } // ==== IO ==== // }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
0c31f560c0d1d1db8e92fba7bf888421
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f; public static int mod = 1000000007; public static int mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // 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 { int n = fReader.nextInt(); int[] a = new int[n]; List<Integer> li = new ArrayList<>(); for(int i=0;i<n;i++) { a[i] = fReader.nextInt(); li.add(a[i]); } Collections.sort(li); int mn = (li.get(0)+1)/2 + (li.get(1)+1)/2; for(int i=1;i<n-1;i++) { int x = a[i-1], y = a[i+1]; if(x < y) { int temp = x; x = y; y = temp; } mn = Math.min(mn, (x-y+1)/2+y); } for(int i=0;i<n-1;i++) { int x = a[i], y = a[i+1]; if(x < y) { int temp = x; x = y; y = temp; } if((x+1)/2 >= y) mn = Math.min(mn, (x+1)/2); else { int cnt = x-y; x -= 2*cnt; y -= cnt; mn = Math.min(mn, cnt + (x+y+2)/3); } } o.println(mn); } catch (Exception e){e.printStackTrace();} } public static int upper_bound(List<int[]> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid)[0] <= 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; } n >>= 1; a = a * a; } return ret; } public static class unionFind { int[] parent; int[] size; int n; public unionFind(int n){ this.n = n; parent = new int[n+1]; size = new int[n+1]; for(int i=1;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(p != parent[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 getCount(){ return n; } public int[] getSize(){ return size; } } public static class FenWick { int[] tree; int n; public FenWick(int n){ this.n = n; tree = new int[n+1]; } public void add(int x, int val){ while(x <= n){ tree[x] += val; x += lowBit(x); } } public int query(int x){ int ret = 0; while(x > 0){ ret += tree[x]; x -= lowBit(x); } return ret; } public int lowBit(int x) { return x&-x; } } 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
1893394c4bba3138e16ca16ddea6d27c
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f; public static int mod = 1000000007; public static int mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // 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 { int n = fReader.nextInt(); int[] a = new int[n]; List<Integer> li = new ArrayList<>(); for(int i=0;i<n;i++) { a[i] = fReader.nextInt(); li.add(a[i]); } Collections.sort(li); int mn = (li.get(0)+1)/2 + (li.get(1)+1)/2; for(int i=1;i<n-1;i++) { int x = a[i-1], y = a[i+1]; if(x < y) { int temp = x; x = y; y = temp; } mn = Math.min(mn, (x-y+1)/2+y); } for(int i=0;i<n-1;i++) { int x = a[i], y = a[i+1]; if(x < y) { int temp = x; x = y; y = temp; } int cnt = Math.min(x-y, (x+1)/2); x -= 2*cnt; y -= cnt; mn = Math.min(mn, cnt + ((x > 0 && y > 0) ? (x+y+2)/3 : 0)); } o.println(mn); } catch (Exception e){e.printStackTrace();} } public static int upper_bound(List<int[]> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid)[0] <= 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; } n >>= 1; a = a * a; } return ret; } public static class unionFind { int[] parent; int[] size; int n; public unionFind(int n){ this.n = n; parent = new int[n+1]; size = new int[n+1]; for(int i=1;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int p){ while(p != parent[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 getCount(){ return n; } public int[] getSize(){ return size; } } public static class FenWick { int[] tree; int n; public FenWick(int n){ this.n = n; tree = new int[n+1]; } public void add(int x, int val){ while(x <= n){ tree[x] += val; x += lowBit(x); } } public int query(int x){ int ret = 0; while(x > 0){ ret += tree[x]; x -= lowBit(x); } return ret; } public int lowBit(int x) { return x&-x; } } 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
93bb19b939e7974b8c95ee7feca3f5a5
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class BreakingTheWall { private static final int INF = 123456789; public static void solve(FastIO io) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); io.println(Math.min(bestAny(A), Math.min(bestEveryOther(A), bestAdjacent(A)))); } private static int bestAny(int[] A) { int first = INF; int second = INF; for (int x : A) { if (x <= first) { second = first; first = x; } else if (x < second) { second = x; } } return ((first + 1) >> 1) + ((second + 1) >> 1); } private static int bestEveryOther(int[] A) { int best = INF; for (int i = 1; i + 1 < A.length; ++i) { int x = Math.max(A[i - 1], A[i + 1]); int y = Math.min(A[i - 1], A[i + 1]); best = Math.min(best, y + ((x - y + 1) >> 1)); } return best; } private static int bestAdjacent(int[] A) { int best = INF; for (int i = 1; i < A.length; ++i) { int x = Math.max(A[i - 1], A[i]); int y = Math.min(A[i - 1], A[i]); if (x >= (y << 1)) { best = Math.min(best, y + ((x - (y << 1) + 1) >> 1)); } else { best = Math.min(best, (x + y + 2) / 3); } } return best; } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
c365f8acf1b517e41a7ddee67f93d532
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class BreakingTheWall { private static final int INF = 123456789; public static void solve(FastIO io) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); io.println(Math.min(bestAny(A), Math.min(bestEveryOther(A), bestAdjacent(A)))); } private static int bestAny(int[] A) { int first = INF; int second = INF; for (int x : A) { if (x <= first) { second = first; first = x; } else if (x < second) { second = x; } } return ((first + 1) >> 1) + ((second + 1) >> 1); } private static int bestEveryOther(int[] A) { int best = INF; for (int i = 1; i + 1 < A.length; ++i) { int x = Math.max(A[i - 1], A[i + 1]); int y = Math.min(A[i - 1], A[i + 1]); best = Math.min(best, y + ((x - y + 1) >> 1)); } return best; } private static int bestAdjacent(int[] A) { int best = INF; for (int i = 1; i < A.length; ++i) { int x = Math.max(A[i - 1], A[i]); int y = Math.min(A[i - 1], A[i]); if (x >= (y << 1)) { best = Math.min(best, y + ((x - (y << 1) + 1) >> 1)); } else { best = Math.min(best, (x + y + 2) / 3); } } return best; } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
4055c9e957ef894f3850cd761abbc05e
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class BreakingTheWall { private static final int INF = 123456789; public static void solve(FastIO io) { final int N = io.nextInt(); final int[] A = io.nextIntArray(N); io.println(Math.min(bestAny(A), Math.min(bestEveryOther(A), bestAdjacent(A)))); } private static int bestAny(int[] A) { int[] top = new int[3]; Arrays.fill(top, INF); for (int x : A) { top[2] = x; Arrays.sort(top); } return ((top[0] + 1) >> 1) + ((top[1] + 1) >> 1); } private static int bestEveryOther(int[] A) { int best = INF; for (int i = 1; i + 1 < A.length; ++i) { int x = Math.max(A[i - 1], A[i + 1]); int y = Math.min(A[i - 1], A[i + 1]); best = Math.min(best, y + ((x - y + 1) >> 1)); } return best; } private static int bestAdjacent(int[] A) { int best = INF; for (int i = 1; i < A.length; ++i) { int x = Math.max(A[i - 1], A[i]); int y = Math.min(A[i - 1], A[i]); if (x >= (y << 1)) { best = Math.min(best, y + ((x - (y << 1) + 1) >> 1)); } else { best = Math.min(best, (x + y + 2) / 3); } } return best; } public static class FastIO { private InputStream reader; private PrintWriter writer; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastIO(InputStream r, OutputStream w) { reader = r; writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w))); } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = reader.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } // TODO: read this byte-by-byte like the other read functions. public double nextDouble() { return Double.parseDouble(nextString()); } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printArray(long[] arr) { for (int i = 0; i < arr.length; i++) { if (i != 0) { writer.print(' '); } writer.print(arr[i]); } } public void printlnArray(int[] arr) { printArray(arr); writer.println(); } public void printlnArray(long[] arr) { printArray(arr); writer.println(); } public void printf(String format, Object... args) { print(String.format(format, args)); } public void flush() { writer.flush(); } } public static void main(String[] args) { FastIO io = new FastIO(System.in, System.out); solve(io); io.flush(); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
d472a3d3f246816387ad747ed4d66ba3
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class c731{ public static void main(String[] args) throws IOException{ BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pt = new PrintWriter(System.out); FastReader sc = new FastReader(); //int t = sc.nextInt(); //for(int o = 0; o<t;o++) { int n = sc.nextInt(); int[] arr = new int[n+2]; arr[0] = Integer.MAX_VALUE; for(int i = 1 ; i<=n;i++) { arr[i] = sc.nextInt(); } arr[n+1] = Integer.MAX_VALUE; ArrayList<Integer> al = new ArrayList<Integer>(); for(int i = 1 ; i<=n;i++) { if(arr[i] % 2 == 1) { al.add(arr[i]/2 +1); }else { al.add(arr[i]/2); } } Collections.sort(al); int ans = al.get(0) + al.get(1); for(int i = 2 ; i<=n;i++) { int v1 = Math.max(arr[i], arr[i-1]); int v2 = Math.min(arr[i], arr[i-1]); if(v1 == v2) { int val = 2 * v1 /3; if((2 * v1 )%3!= 0) { val++; } ans = Math.min(ans,val ); // System.out.println(val + "aaa"); continue; } if(v1>=v2*2){ int x = v1/2; if(v1%2 == 1) { x++; } ans = Math.min(ans, x); }else { int val1 = v1 - v2 + 1; int t1 = v1 - val1 *2; int t2 = v2 - val1; int x = (t1 + t2)/3; if((t1 + t2)%3 !=0) { x++; } val1+=x; ans = Math.min(ans, val1); int val2 = v1 - v2 ; int t3 = v1 - val2 *2; int t4 = v2 - val2; int y = (t3 + t4)/3; if((t3 + t4)%3 !=0) { y++; } // System.out.println(i + " " + val2 + " x" + v1 + " " + v2 + " " + y); val2+=y; ans = Math.min(ans, val2); } } for(int i = 1 ; i<=n;i++) { // ans = Math.min(ans, Math.max(arr[i-1], arr[i+1])); int val = Math.min(arr[i-1], arr[i+1]); val += (Math.max(arr[i-1], arr[i+1])- val +1 )/2; ans = Math.min(ans, val); } System.out.println(ans); } //} //------------------------------------------------------------------------------------------------------------------------------------------------ public static ArrayList<Long> printDivisors(long n) { ArrayList<Long> al = new ArrayList<>(); for (long i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i)al.add(i); else { al.add(i); al.add(n/i); } } } return al; } public static boolean palin(String s) { int n = s.length(); int i = 0; int j = n-1; while(i<=j) { if(s.charAt(i)!=s.charAt(j)) { return false; } i++; j--; } return true; } public static boolean check(int[] arr , int n , int v , int l ) { int x = v/2; int y = v/2; // System.out.println(x + " " + y); if(v%2 == 1 ) { x++; } for(int i = 0 ; i<n;i++) { int d = l - arr[i]; int c = Math.min(d/2, y); y -= c; arr[i] -= c*2; if(arr[i] > x) { return false; } x -= arr[i]; } return true; } public static int cnt_set(long x) { long v = 1l; int c =0; int f = 0; while(v<=x) { if((v&x)!=0) { c++; } v = v<<1; } return c; } public static int lis(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(arr[0]); dp[0]= 1; for(int i = 1 ; i<n;i++) { int x = al.get(al.size()-1); if(arr[i]>x) { al.add(arr[i]); }else { int v = lower_bound(al, 0, al.size(), arr[i]); // System.out.println(v); al.set(v, arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } public static int lis2(int[] arr,int[] dp) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(-arr[n-1]); dp[n-1] = 1; // System.out.println(al); for(int i = n-2 ; i>=0;i--) { int x = al.get(al.size()-1); // System.out.println(-arr[i] + " " + i + " " + x); if((-arr[i])>x) { al.add(-arr[i]); }else { int v = lower_bound(al, 0, al.size(), -arr[i]); // System.out.println(v); al.set(v, -arr[i]); } dp[i] = al.size(); } //return al.size(); return al.size(); } static int cntDivisors(int n){ int cnt = 0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) cnt++; else cnt+=2; } } return cnt; } public static long power(long x, long y, long p){ long res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ncr(long[] fac, int n , int r , long m) { if(r>n) { return 0; } return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m; } public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k) { int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (arr.get(mid) <=k) { s=mid+1; } else { e=mid; } } if(s==arr.size()) { return -1; } return s; } // ----------------------------------------------------------------------------------------------------------------------------------------------- public static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public static long modInverse(long a, long m){ long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } //_________________________________________________________________________________________________________________________________________________________________ // private static int[] parent; // private static int[] size; public static int find(int[] parent, int u) { while(u != parent[u]) { parent[u] = parent[parent[u]]; u = parent[u]; } return u; } private static void union(int[] parent,int[] size,int u, int v) { int rootU = find(parent,u); int rootV = find(parent,v); if(rootU == rootV) { return; } if(size[rootU] < size[rootV]) { parent[rootU] = rootV; size[rootV] += size[rootU]; } else { parent[rootV] = rootU; size[rootU] += size[rootV]; } } //----------------------------------------------------------------------------------------------------------------------------------- //segment tree //for finding minimum in range public static void build(int [] seg,int []arr,int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build(seg,arr,2*idx+1, lo, mid); build(seg,arr,idx*2+2, mid +1, hi); // seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]); // seg[idx] = seg[idx*2+1]+ seg[idx*2+2]; // seg[idx] = Math.min(seg[idx*2+1], seg[idx*2+2]); seg[idx] = seg[idx*2+1] * seg[idx*2+2]; } //for finding minimum in range public static int query(int[]seg,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { return seg[idx]; } if(hi<l || lo>r) { return 1; } int mid = (lo + hi)/2; int left = query(seg,idx*2 +1, lo, mid, l, r); int right = query(seg,idx*2 + 2, mid + 1, hi, l, r); // return Math.min(left, right); //return gcd(left, right); // return Math.min(left, right); return left * right; } // // for sum // //public static void update(int[]seg,int idx, int lo , int hi , int node , int val) { // if(lo == hi) { // seg[idx] += val; // }else { //int mid = (lo + hi )/2; //if(node<=mid && node>=lo) { // update(seg, idx * 2 +1, lo, mid, node, val); //}else { // update(seg, idx*2 + 2, mid + 1, hi, node, val); //} //seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2]; // //} //} //--------------------------------------------------------------------------------------------------------------------------------------- // static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } // static void shuffleArray(coup[] ar) // { // // If running on Java 6 or older, use `new Random()` on RHS here // Random rnd = ThreadLocalRandom.current(); // for (int i = ar.length - 1; i > 0; i--) // { // int index = rnd.nextInt(i + 1); // // Simple swap // coup a = ar[index]; // ar[index] = ar[i]; // ar[i] = a; // } // } //----------------------------------------------------------------------------------------------------------------------------------------------------------- } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //------------------------------------------------------------------------------------------------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------------------- class coup{ int a; int b; public coup(int a , int b) { this.a = a; this.b = b; } } class tripp{ int a; int b; double c; public tripp(int a , int b, double c) { this.a = a; this.b = b; this.c = c; } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
52d6b18ac5f6a1a7dcbb94bb7bfeed86
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; public class BreakingTheWall { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Integer[] a = new Integer[n]; for (int i=0; i<n; i++){ a[i] = s.nextInt(); } // case 1: two sections are at any place // Integer[] lowest2 = lowestTwo(a); // Integer ans = (lowest2[0]+1)/2 + (lowest2[1]+1)/2; int ans = 100000000; // case 2: two sections have one wall between them for(int i=0; i<n-2; i+=1){ int sum = a[i] + a[i+2]; Integer shotsReq = sum/2 + sum%2; ans = Math.min(ans, shotsReq); } // case 3: two sections are adjacent for(int i=0; i<n-1; i++){ int x = Math.max(a[i], a[i+1]); int y = Math.min(a[i], a[i+1]); if (x>2*y) { ans = Math.min(ans, (x+1)/2); } else { int shots = (x+y+2)/3; ans = Math.min(ans, shots); } } List<Integer> aa = Arrays.asList(a); aa.sort(Comparator.naturalOrder()); ans = Math.min(ans, (aa.get(0)+1)/2 + (aa.get(1)+1)/2); System.out.println(ans); s.close(); } public static Integer[] lowestTwo(Integer[] a){ Integer[] ans = new Integer[2]; ans[0] = a[0]; ans[1] = a[1]; for (int i=2; i<a.length; i++){ if (a[i] < ans[0]){ ans[1] = ans[0]; ans[0] = a[i]; } else if (a[i] < ans[1]){ ans[1] = a[i]; } } return ans; } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
6d8d35f242196615a8760ac9d2cecb37
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; public class BreakingTheWall { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Integer[] a = new Integer[n]; for (int i=0; i<n; i++){ a[i] = s.nextInt(); } // case 1: two sections are at any place // Integer[] lowest2 = lowestTwo(a); // Integer ans = (lowest2[0]+1)/2 + (lowest2[1]+1)/2; int ans = 100000000; // case 2: two sections have one wall between them for(int i=0; i<n-2; i+=1){ int x = Math.max(a[i], a[i+2]); int y = Math.min(a[i], a[i+2]); int z = x - ((x-y)/2)*2; Integer shotsReq = (x-y)/2 + Math.max(y, z); ans = Math.min(ans, shotsReq); } // case 3: two sections are adjacent for(int i=0; i<n-1; i++){ int x = Math.max(a[i], a[i+1]); int y = Math.min(a[i], a[i+1]); if (x>2*y) { ans = Math.min(ans, (x+1)/2); } else { int shots = (x+y+2)/3; ans = Math.min(ans, shots); } } List<Integer> aa = Arrays.asList(a); aa.sort(Comparator.naturalOrder()); ans = Math.min(ans, (aa.get(0)+1)/2 + (aa.get(1)+1)/2); System.out.println(ans); s.close(); } public static Integer[] lowestTwo(Integer[] a){ Integer[] ans = new Integer[2]; ans[0] = a[0]; ans[1] = a[1]; for (int i=2; i<a.length; i++){ if (a[i] < ans[0]){ ans[1] = ans[0]; ans[0] = a[i]; } else if (a[i] < ans[1]){ ans[1] = a[i]; } } return ans; } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
ed7cc8eb533771b83acc4f8aa92a3224
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class E { private static FastReader fr; private static OutputStream out; private static int mod = (int)(1e9+7); private void solve() { int n = fr.nextInt(); int arr[] = fr.nextIntArray(n); int temp[] = new int[n]; for(int i=0;i<n;i++) temp[i] = arr[i]; Arrays.sort(temp); int max = (temp[0]/2 + temp[0] % 2) + (temp[1]/2 + temp[1] % 2); int ans = max; for(int i=0;i<n-1;i++){ int val = -1; if(Math.max(arr[i], arr[i+1]) / 2 >= Math.min(arr[i], arr[i+1])){ val = Math.max(arr[i], arr[i+1]); max = val / 2 + val % 2; } else { val = arr[i] + arr[i+1]; max = val / 3; if(val % 3 != 0) { max ++; } } ans = Math.min(ans, max); } for(int i=1;i<n-1;i++){ int val = Math.max(arr[i-1], arr[i+1]); max = Math.min(arr[i-1], arr[i+1]); max = max + ((val - max)/2 + (val - max) % 2); ans = Math.min(ans, max); } println(ans); } public static void main(String args[]) throws IOException{ new E().run(); } private static int modInverse(int a) { int m0 = mod; int y = 0, x = 1; if (mod == 1) return 0; while (a > 1) { int q = (int)(a / mod); int t = mod; mod = a % mod; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } private ArrayList<Integer> factors(int n, boolean include){ ArrayList<Integer> factors = new ArrayList<>(); if(n < 0) return factors; if(include) { factors.add(1); if(n > 1) factors.add(n); } int i = 2; for(;i*i<n;i++) { if(n % i == 0) { factors.add(i); factors.add(n / i); } } if(i * i == n) { factors.add(i); } return factors; } private ArrayList<Integer> PrimeFactors(int n) { ArrayList<Integer> primes = new ArrayList<>(); int i = 2; while (i * i <= n) { if (n % i == 0) { primes.add(i); n /= i; while (n % i == 0) { primes.add(i); n /= i; } } i++; } if(n > 1) primes.add(i); return primes; } private boolean isPrime(int n) { if(n == 0 || n == 1) { return false; } if(n % 2 == 0) { return false; } for(int i=3;i*i<=n;i+=2) { if(n % i == 0) { return false; } } return true; } private ArrayList<Integer> Sieve(int n){ boolean bool[] = new boolean[n+1]; Arrays.fill(bool, true); bool[0] = bool[1] = false; for(int i=2;i*i<=n;i++) { if(bool[i]) { int j = 2; while(i*j <= n) { bool[i*j] = false; j++; } } } ArrayList<Integer> primes = new ArrayList<>(); for(int i=2;i<=n;i++) { if(bool[i]) primes.add(i); } return primes; } private HashMap<Integer, Integer> addToHashMap(HashMap<Integer, Integer> map, int arr[]){ for(int val: arr) { if(!map.containsKey(val)) { map.put(val, 1); }else { map.put(val, map.get(val) + 1); } } return map; } private int factorial(int n) { long fac = 1; for(int i=2;i<=n;i++) { fac *= i; fac %= mod; } return (int)(fac % mod); } // private static int pow(int base,int exp){ // if(exp == 0){ // return 1; // }else if(exp == 1){ // return base; // } // int a = pow(base,exp/2); // a = ((a % mod) * (a % mod)) % mod; // if(exp % 2 == 1) { // a = ((a % mod) * (base % mod)); // } // return a; // } private static int gcd(int a,int b){ if(a == 0){ return b; } return gcd(b%a,a); } private static int lcm(int a,int b){ return (a * b)/gcd(a,b); } private void run() throws IOException{ fr = new FastReader(); out = new BufferedOutputStream(System.out); solve(); out.flush(); out.close(); } private static class FastReader{ private static BufferedReader br; private static StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedOutputStream(System.out); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public int[] nextIntArray(int n) { int arr[] = new int[n]; for(int i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long arr[] = new long[n]; for(int i=0;i<n;i++) { arr[i] = nextLong(); } return arr; } public String[] nextStringArray(int n) { String arr[] = new String[n]; for(int i=0;i<n;i++) { arr[i] = next(); } return arr; } } public static void print(Object str) { try { out.write(str.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void println(Object str) { try { out.write((str.toString() + "\n").getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void println() { println(""); } public static void printArray(Object str[]){ for(Object s : str) { try { out.write(str.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
c637b461d6b5d632379d835ef6b41ca9
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.StringTokenizer; public class E { public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int t=1; while(t-->0) { int n=sc.nextInt(); int[]a=new int[n]; int mnIdx=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); a[i]=rand(a[i]); if(a[mnIdx]>a[i])mnIdx=i; } // fillRand(a); int smnIdx=n-mnIdx-1; if(smnIdx==mnIdx) { if(mnIdx<n-1)smnIdx++; else smnIdx--; } for(int i=0;i<n;i++) { if(a[i]<a[smnIdx]&&i!=mnIdx)smnIdx=i; } int x=a[mnIdx],y=a[smnIdx]; int ans=(int) (Math.ceil(x/2.0)+Math.ceil(y/2.0)); for(int i=1;i<n;i++) { int mx=Math.max(a[i], a[i-1]); int mn=Math.min(a[i], a[i-1]); if(mx>=mn*2) { ans=(int) Math.min(ans, Math.ceil(mx/2.0)); }else { int moved=mx-mn-1; ans=(int) Math.min(ans, moved+Math.ceil((mx+mn-3*moved)/3.0)); } if(i<n-1) { mn=Math.min(a[i-1], a[i+1]); mx=Math.max(a[i-1], a[i+1]); ans=(int) Math.min(ans, mn+Math.ceil((mx-mn)/2.0)); if(a[i-1]%2==1&&a[i+1]%2==1) { ans=Math.min(ans, a[i-1]/2 + a[i+1]/2 +1); } } } out.println(ans); } out.close(); } private static int rand(int x) { // TODO Auto-generated method stub return x; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public boolean hasNext() {return st.hasMoreTokens();} 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 String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
a8ab54752b604496cda8db131381547f
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class yibianguo{ public static void main(String[]args) { FastScanner c = new FastScanner(); int n = c.nextInt(); int [] a = new int [n]; for(int nn = 0; nn < n; nn++){ a[nn] = c.nextInt(); } int ans = 100000000 , s = 100000000 , t = 10000000; for(int q = 0; q < n; q++){ ans = Math.min(ans , s + (a[q]+1)/2); s = Math.min(s,(a[q]+1)/2); if(q < n - 1){ int max = Math.max(a[q] , a[q+1]); int min = Math.min(a[q] , a[q+1]); t = (max + 1)/2; if(max % 2 != 0){ min -= 1; } if(min - t > 0){ int y = min - t; t -= (y+1)/3; int te = (y + 1 + (y+1)/3)/2; t += te; } ans = Math.min(ans , t); } if(q > 0 && q < n - 1){ ans = Math.min(ans , (a[q+1] + a[q-1]+ 1)/2); } } System.out.println(ans); } static class p implements Comparable<p>{ int j,k; p(int j, int k){ this.j = j; this.k =k; } public int compareTo(p o) { return Integer.compare(j, o.j); } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
0aef30480383defdef8cc03e08942135
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class E1674 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Solver solver = new Solver(); solver.solve(in, out); out.close(); } static class Solver { void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int ans = Integer.MAX_VALUE; // 敲两个相邻的 for (int i = 0; i < n - 1; i++) { ans = Math.min(ans, this.attackBeside(a[i], a[i + 1])); } // 靠溅射伤害 for (int i = 1; i < n - 1; i++) { ans = Math.min(ans, this.attackTwoSide(a[i - 1], a[i + 1])); } // 单独敲两块不相邻的 Arrays.sort(a); ans = Math.min(ans, upper(a[0], 2) + upper(a[1], 2)); out.println(ans); } private int attackBeside(int a, int b) { if (a > b) { int temp = a; a = b; b = temp; } if (a * 2 < b) { return upper(b, 2); } else { return upper(a + b, 3); } // 先把高生命压低 // int large = (b - a) / 2; // b -= large * 2; // a -= large; // return upper(a + b, 3) + large; } private int attackTwoSide(int a, int b) { if (a > b) { int temp = a; a = b; b = temp; } return a + upper(b - a, 2); } private int upper(int a, int b) { if (a % b == 0) { return a / b; } return a / b + 1; } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
c95a536fa3e8b87d1e35b2e41e660247
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class BreakingTheWall { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t =1; // int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] a = sc.nextIntArray(n); int res = Integer.MAX_VALUE; int[] tmp = new int[n]; for (int i = 0; i < n; i++) { tmp[i] = a[i]; } if (n == 1) { pw.println(1); pw.close(); return; } Arrays.sort(tmp); res = (int) Math.min(res, Math.ceil((double) tmp[0] / 2) + Math.ceil((double) tmp[1] / 2)); for (int i = 0; i < n - 1; i++) { int max = Math.max(a[i], a[i + 1]); int min = Math.min(a[i], a[i + 1]); if (min <= Math.ceil((double) max / 2)) { res = (int) Math.min(res, Math.ceil((double) max / 2)); } else res = (int) Math.min(res, Math.ceil((double) (a[i] + a[i + 1]) / 3)); } for (int i = 0; i < n - 2; i++) { res = Math.min(res, Math.max(a[i], a[i + 2])); res = (int) Math.min(res, Math.min(a[i], a[i + 2]) + (Math.ceil((double) (Math.max(a[i], a[i + 2]) - Math.min(a[i], a[i + 2])) / 2))); } pw.println(res); } pw.close(); } // -------------------------------------------------------Scanner--------------------------------------------------- static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(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 { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
e174e838282b935b3ac9c52c5ad10afa
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.io.*; import java.lang.reflect.Array; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = (long) 1e9 + 7; static long inf = (long) 1e16; static ArrayList<Integer>[] ad, ad1; static int[][] remove, add; static long[] inv, f, ncr[]; static HashMap<Integer, Integer> hm; static int[] pre, suf, Smax[], Smin[]; static int idmax, idmin; static ArrayList<Integer> av; static HashMap<Integer, Integer> mm; static boolean[] msks; static int[] lazy[], lazyCount; static int[] c, w; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = sc.nextArrInt(n); PriorityQueue<Integer> ts = new PriorityQueue<>(); int ans = 0; for (int y : a) ts.add(y); if (ts.size() > 1) { ans = ts.peek() / 2 + ts.poll() % 2; ans += ts.peek() / 2 + ts.poll() % 2; } // System.out.println(ans); for (int i = 0; i < n - 1; i++) { int temp = (a[i] + a[i + 1]) / 3; if ((a[i] + a[i + 1]) % 3 != 0) temp++; int max = Math.max(a[i], a[i + 1]); int min = Math.min(a[i], a[i + 1]); if (max >= min * 2) { temp = max / 2; temp += max % 2; // System.out.println(max/2); } // System.out.println(temp+" "+i+" "+max+" "+min); ans = Math.min(ans, temp); if (i > 0) { max = Math.max(a[i - 1], a[i + 1]); min = Math.min(a[i - 1], a[i + 1]); temp = (max - min) / 2 + (max - min) % 2 + min; ans = Math.min(ans, temp); } } out.print(ans); out.flush(); } // 9 8 7 7 5 6 4 4 2 3 1 1 0 0 static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
d68dcfa38e604cda635f22292e6d921f
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.*; public class Codeforces { static long mod= Long.MAX_VALUE; public static void main(String[] args) throws Exception { PrintWriter out=new PrintWriter(System.out); FastScanner fs=new FastScanner(); // DecimalFormat formatter= new DecimalFormat("#0.000000"); // int t=fs.nextInt(); // int t=fs.nextInt(); int t=1; outer:for(int time=1;time<=t;time++) { int n=fs.nextInt(); int arr[]=fs.readArray(n); long ans= Long.MAX_VALUE; for(int i=0;i<n-1;i++) { ans=Math.min(ans,find(arr[i],arr[i+1])); } for(int i=1;i<n-1;i++) { ans=Math.min(ans, finda(arr[i-1],arr[i+1])); } sort(arr); ans= Math.min(ans, (arr[0]+1)/2+(arr[1]+1)/2); out.println(ans); } out.close(); } static long finda(int a,int b) { long d= Math.abs(a-b); long ans= Math.min(a, b); ans+= (d+1)/2; return ans; // return Math.max(a, b); } static long find(int a,int b) { if(a>b) return find(b,a); long ans=0; long xx=0,yy=0; if(2*a-b>0) { xx= (2*a-b+2)/3; } // if(2*b-a>0) { // yy= (2*b-a+2)/3; // } if(xx<b) { yy= (b-xx+1)/2; } if(xx>=2) { xx-=2; if(2*xx+yy>=a&&2*yy+xx>=b) { return xx+yy; } xx+=2; } if(yy>=2) { yy-=2; if(2*xx+yy>=a&&2*yy+xx>=b) { return xx+yy; } yy+=2; } if(xx>=1&&yy>=1) { xx--; yy--; if(2*xx+yy>=a&&2*yy+xx>=b) { return xx+yy; } xx++; yy++; } if(xx>=1) { xx--; if(2*xx+yy>=a&&2*yy+xx>=b) { return xx+yy; } xx++; } if(yy>=1) { yy--; if(2*xx+yy>=a&&2*yy+xx>=b) { return xx+yy; } yy++; } return xx+yy; } static long pow(long a,long b) { if(b<0) return 1; long res=1; while(b!=0) { if((b&1)!=0) { res*=a; res%=mod; } a*=a; a%=mod; b=b>>1; } return res; } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long nck(int n,int k) { if(k>n) return 0; long res=1; res*=fact(n); res%=mod; res*=modInv(fact(k)); res%=mod; res*=modInv(fact(n-k)); res%=mod; return res; } static long fact(long n) { // return fact[(int)n]; long res=1; for(int i=2;i<=n;i++) { res*=i; res%=mod; } return res; } static long modInv(long n) { return pow(n,mod-2); } static void sort(int[] a) { //suffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); int temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } static void sort(long[] a) { //suffle int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n); long temp=a[i]; a[i]=a[oi]; a[oi]=temp; } //then sort Arrays.sort(a); } // Use this to input code since it is faster than a Scanner 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(); } String nextLine() { String str=""; try { str= (br.readLine()); } catch (IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readArrayL(int n) { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
9077072bbd9c7952a49ccca9669c3ef4
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.Scanner; public class E { public static void main(String[] args) { new E().solve(); } public void solve() { Scanner scanner = new Scanner(System.in); int t = 1; while (t-- > 0) { int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } int minind = 0; for (int i = 1; i < n; i++) { if (a[i] < a[minind]) { minind = i; } } int minshoots = 1000000; int cnt = 0; for (int i = 0; i < n; i++) { cnt = 0; if (i != minind) { if (Math.abs(i - minind) == 1) { cnt = getCnt(a[i], a[minind]); if (cnt < minshoots) minshoots = cnt; } else if (i != n - 1) { cnt = Math.min(getCnt(a[i], a[i + 1]), getCnt1(a[i], a[minind])); if (cnt < minshoots) minshoots = cnt; } else { cnt = getCnt1(a[i], a[minind]); if (cnt < minshoots) minshoots = cnt; } if (i > 0 && i < n - 1) { cnt = (1 + a[i - 1] + a[i + 1]) / 2; if (cnt < minshoots) minshoots = cnt; } } } System.out.println(minshoots); } } private int getCnt(int a, int b) { int maxnum = Math.max(a, b); int minnum = Math.min(a, b); int cnt = 0; if (maxnum >= minnum * 2) { cnt = (maxnum + 1) / 2; } else { cnt = maxnum - minnum; int num = maxnum - 2 * cnt; if (num % 3 == 0) cnt += num / 3 * 2; else if (num % 3 == 1) cnt += num / 3 * 2 + 1; else cnt += num / 3 * 2 + 2; } return cnt; } private int getCnt1(int a, int b) { return (a + 1) / 2 + (b + 1) / 2; } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
03862a2a2881b38205a2fed1eb243990
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void solve(int tCase) throws IOException { int n = sc.nextInt(); int[] arr = new int[n]; //asa int mx1 = inf_int,mx2 = inf_int; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); if(arr[i] < mx1){ mx2 = mx1; mx1 = arr[i]; }else if(arr[i] < mx2){ mx2 = arr[i]; } } int ans = ((mx1+1)/2 + (mx2+1)/2); for(int i=1;i<n-1;i++){ int t = Math.min(arr[i-1],arr[i+1]); int rem = Math.max(arr[i-1] - t, arr[i+1] - t); ans = Math.min(ans,t + (1 + rem)/2); } for(int i=0;i<n-1;i++){ ans = Math.min(ans, Math.max(Math.max((arr[i] + 1) / 2, (arr[i + 1] + 1) / 2), (arr[i] + arr[i + 1] + 2) / 3)); } out.println(ans); } public static void main(String[] args) throws IOException { openIO(); int testCase = 1; // testCase = sc.nextInt(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ /*--------------------------------------HELPER FUNCTIONS STARTS HERE-----------------------------------------*/ public static int mod = (int) 1e9 + 7; // public static int mod = 998244353; public static int inf_int = (int) 2e8; public static long inf_long = (long) 2e18; public static void _sort(int[] arr, boolean isAscending) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } public static void _sort(long[] arr, boolean isAscending) { int n = arr.length; List<Long> list = new ArrayList<>(); for (long ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // time : O(1), space : O(1) public static int _digitCount(long num,int base){ // this will give the # of digits needed for a number num in format : base return (int)(1 + Math.log(num)/Math.log(base)); } // time : O(n), space: O(n) public static long _fact(int n){ // simple factorial calculator long ans = 1; for(int i=2;i<=n;i++) ans = ans * i % mod; return ans; } // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod)) public static long[] factorial , inverseFact; public static void _ncr_precompute(int n){ factorial = new long[n+1]; inverseFact = new long[n+1]; factorial[0] = inverseFact[0] = 1; for (int i = 1; i <=n; i++) { factorial[i] = (factorial[i - 1] * i) % mod; inverseFact[i] = _modExpo(factorial[i], mod - 2); } } // time of factorial calculation after pre-computation is O(1) public static int _ncr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod); } public static int _npr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[n - r] % mod); } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { while (a>0){ long x = a; a = b % a; b = x; } return b; // if (a == 0) // return b; // return _gcd(b % a, a); } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _modExpo(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } // function to find a/b under modulo mod. time : O(logn) public static long _modInv(long a,long b){ return (a * _modExpo(b,mod-2)) % mod; } //sieve or first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) if(firstDivisor[j]==j)firstDivisor[j] = i; return firstDivisor; } // check if x is a prime # of not. time : O( n ^ 1/2 ) private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } static class Pair<K, V>{ K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } @Override public String toString(){ return ff.toString()+" "+ss.toString(); } } /*--------------------------------------HELPER FUNCTIONS ENDS HERE-----------------------------------------*/ /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException { sc = new FastestReader(); out = new PrintWriter(System.out); } public static void closeIO() throws IOException { out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) {} return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); final boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); return neg?-ret:ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); final boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); return neg?-ret:ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); final 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); return neg?-ret:ret; } public String nextLine() throws IOException { final byte[] buf = new byte[(1<<10)]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ } /** Some points to keep in mind : * 1. don't use Arrays.sort(primitive data type array) * 2. try to make the parameters of a recursive function as less as possible, * more use static variables. * **/
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
dcab408143ad866dbdd35296d80ab6fd
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static FastReader in=new FastReader(); static final Random random=new Random(); static long mod=1000000007L; static long[] fact = new long[16]; static void init() { fact[0] = 1; for(int i=1; i<16; i++) fact[i] = (i*fact[i-1]); } public static void main (String[] args) throws java.lang.Exception { int t=1; while(t-->0) solve(); // ArrayList<Pair> al = new ArrayList<>(); // for(int i=0; i<5; i++) { // al.add(new Pair(in.nextLong(), in.nextLong())); // } // for(int i=0; i<5; i++) { // System.out.println(al.get(i).a + " " + al.get(i).b); // } // Compare obj = new Compare(); // obj.compare(al, 5); // for(int i=0; i<5; i++) { // System.out.println(al.get(i).a + " " + al.get(i).b); // } } static void solve() { long n = in.nextLong(); long[] a = new long[(int)n]; for(int i=0; i<n; i++) a[i] = in.nextLong(); long ans =Long.MAX_VALUE; for(int i=0; i<n-1; i++) { long cur = 0; long x = a[i]; long y = a[i+1]; if(x<y) { long temp = x; x = y; y = temp; } cur += Math.min(x-y, (x+1)/2); x -= 2*cur; y -= cur; if(x>0 && y>0) { cur += (x+y+2)/3; } ans = Math.min(ans, cur); } for(int i=0; i<n-2; i++) { long cur = 0; long x = a[i]; long y = a[i+2]; if(x<y) { long temp = x; x = y; y = temp; } cur += (x-y+1)/2; cur += y; ans = Math.min(ans, cur); } Arrays.sort(a); ans = Math.min(ans, (a[0]+1)/2+(a[1]+1)/2); System.out.println(ans); } static long cntSetBit(long num) { long ans = 0; while(num>0) { if(num%2==1) ans++; num /= 2; } return ans; } static int max(int a, int b) { if(a<b) return b; return a; } static void ruffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static < E > void print(E res) { System.out.println(res); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static int abs(int a) { if(a<0) return -1*a; return a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int [] readintarray(int n) { int res [] = new int [n]; for(int i = 0; i<n; i++)res[i] = nextInt(); return res; } long [] readlongarray(int n) { long res [] = new long [n]; for(int i = 0; i<n; i++)res[i] = nextLong(); return res; } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
9019e2d38d3d86ad7a2bb2f25b686c9a
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.io.*; public class Main { public static int solve1(int[]arr) { int[]arr2 = new int[arr.length]; for(int i=0;i<arr.length;i++) { arr2[i]=arr[i]; } sort(arr2); return ((int)Math.ceil(arr2[0]/2.0) + (int)Math.ceil(arr2[1]/2.0)); } public static int solve2(int[]arr) { int min = (int)1e9; for(int i=1;i<arr.length-1;i++) { if((arr[i-1]+arr[i+1])/2<min) min = (int)Math.ceil((arr[i-1]+arr[i+1])/2.0); } return min; } public static int solve3(int[]arr) { int min = (int)1e9; for(int i=0;i<arr.length-1;i++) { int x = arr[i]>arr[i+1]?arr[i]:arr[i+1]; int y = arr[i]<arr[i+1]?arr[i]:arr[i+1]; int operations = x-y; if(x>=2*y) { min = Math.min((int)Math.ceil(x/2.0),min); } else { x-=2*operations; y-=operations; operations+=Math.ceil((x+y)/3.0); min = Math.min(operations, min); } } return min; } public static void main(String[] args) throws Exception { int n = sc.nextInt(); int[] arr = sc.nextIntArray(n); int ans = Math.min(solve1(arr), Math.min(solve2(arr), solve3(arr))); pw.println(ans); pw.flush(); } public static void sort(int[] in) { shuffle(in); Arrays.sort(in); } public static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); int tmp = in[i]; in[i] = in[idx]; in[idx] = tmp; } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return x - o.x; } public String toString() { return x + " " + y; } } static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(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 { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public 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(); } } public static void display(char[][] 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(); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
4f0368a1336bd589b011f9a2670ff172
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { fs = new FastReader(); out = new PrintWriter(System.out); int n = fs.nextInt(); int ar[] = fs.readArray(n); int ans = Integer.MAX_VALUE; for (int i = 1; i < n; ++i) { ans = Math.min(ans, Math.max((ar[i - 1] + 1) / 2, Math.max((ar[i] + 1) / 2, (ar[i - 1] + ar[i] + 2) / 3))); } for (int i = 1; i + 1 < n; ++i) { ans = Math.min(ans, Math.min(ar[i - 1], ar[i + 1]) + (Math.max(ar[i - 1], ar[i + 1]) - Math.min(ar[i - 1], ar[i + 1]) + 1) / 2); } ruffleSort(ar); ans = Math.min(ans, (ar[0] + 1) / 2 + (ar[1] + 1) / 2); out.println(ans); out.close(); } public static PrintWriter out; public static FastReader fs; public static final Random random = new Random(); public static void ruffleSort(int[] a) { int n = a.length; for (int i = 0; i < n; ++i) { int oi = random.nextInt(n), tmp = a[oi]; a[oi] = a[i]; a[i] = tmp; } Arrays.sort(a); } public static class FastReader { private BufferedReader br; private StringTokenizer st = new StringTokenizer(""); public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String file_name) throws FileNotFoundException { br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(file_name)))); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = nextInt(); return a; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
202daadc70e15686649d579231e467f1
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public final class Main { //int 2e9 - long 9e18 static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)}; static int mod = (int) (1e9 + 7); static int mod2 = 998244353; public static void main(String[] args) { int tt = 1; while (tt-- > 0) { solve(); } out.flush(); } public static void solve() { int n = i(); int[] a = input(n); int ans = (int) 1e6; for (int i = 0; i + 1 < n; i++) { int x = Math.max(a[i], a[i + 1]); int y = Math.min(a[i], a[i + 1]); int t; if (x >= y * 2) { t = x / 2 + x % 2; } else { t = (int) upperDiv(x + y, 3); } ans = Math.min(ans, t); } for (int i = 0; i + 2 < n; i++) { int t = (int) upperDiv(a[i] + a[i + 2], 2); ans = Math.min(ans, t); } Arrays.sort(a); ans = Math.min(ans, (int) upperDiv(a[0], 2) + (int) upperDiv(a[1], 2)); out.println(ans); } // (10,5) = 2 ,(11,5) = 3 static long upperDiv(long a, long b) { return (a / b) + ((a % b == 0) ? 0 : 1); } static long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static int[] preint(int[] a) { int[] pre = new int[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static long[] pre(int[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static long[] post(int[] a) { long[] post = new long[a.length + 1]; post[0] = 0; for (int i = 0; i < a.length; i++) { post[i + 1] = post[i] + a[a.length - 1 - i]; } return post; } static long[] pre(long[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static double d() { return in.nextDouble(); } static String s() { return in.nextLine(); } static String c() { return in.next(); } static int[][] inputWithIdx(int N) { int A[][] = new int[N][2]; for (int i = 0; i < N; i++) { A[i] = new int[]{i, in.nextInt()}; } return A; } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long LCM(int a, int b) { return (long) a / GCD(a, b) * b; } static long LCM(long a, long b) { return a / GCD(a, b) * b; } // find highest i which satisfy a[i]<=x static int lowerbound(int[] a, int x) { int l = 0; int r = a.length - 1; while (l < r) { int m = (l + r + 1) / 2; if (a[m] <= x) { l = m; } else { r = m - 1; } } return l; } static void shuffle(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } } static void shuffleAndSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int[] temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr, comparator); } static void shuffleAndSort(long[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); long temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static boolean isPerfectSquare(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static void swap(char A[], int a, int b) { char t = A[a]; A[a] = A[b]; A[b] = t; } static long pow(long a, long b, int mod) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow *= x; } x = x * x; b /= 2; } return pow; } static long modInverse(long x, int mod) { return pow(x, mod - 2, mod); } static boolean isPrime(long N) { if (N <= 1) { return false; } if (N <= 3) { return true; } if (N % 2 == 0 || N % 3 == 0) { return false; } for (int i = 5; i * i <= N; i = i + 6) { if (N % i == 0 || N % (i + 2) == 0) { return false; } } return true; } public static String reverse(String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); } public static void reverse(int[] arr) { int l = 0; int r = arr.length - 1; while (l < r) { swap(arr, l, r); l++; r--; } } public static String repeat(char ch, int repeat) { if (repeat <= 0) { return ""; } final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } public static int[] manacher(String s) { char[] chars = s.toCharArray(); int n = s.length(); int[] d1 = new int[n]; for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1); while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) { k++; } d1[i] = k--; if (i + k > r) { l = i - k; r = i + k; } } return d1; } public static int[] kmp(String s) { int n = s.length(); int[] res = new int[n]; for (int i = 1; i < n; ++i) { int j = res[i - 1]; while (j > 0 && s.charAt(i) != s.charAt(j)) { j = res[j - 1]; } if (s.charAt(i) == s.charAt(j)) { ++j; } res[i] = j; } return res; } } class Pair { int i; int j; Pair(int i, int j) { this.i = i; this.j = j; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return i == pair.i && j == pair.j; } @Override public int hashCode() { return Objects.hash(i, j); } } class ThreePair { int i; int j; int k; ThreePair(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ThreePair pair = (ThreePair) o; return i == pair.i && j == pair.j && k == pair.k; } @Override public int hashCode() { return Objects.hash(i, j); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Node { int val; public Node(int val) { this.val = val; } } class ST { int n; Node[] st; ST(int n) { this.n = n; st = new Node[4 * Integer.highestOneBit(n)]; } void build(Node[] nodes) { build(0, 0, n - 1, nodes); } private void build(int id, int l, int r, Node[] nodes) { if (l == r) { st[id] = nodes[l]; return; } int mid = (l + r) >> 1; build((id << 1) + 1, l, mid, nodes); build((id << 1) + 2, mid + 1, r, nodes); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } void update(int i, Node node) { update(0, 0, n - 1, i, node); } private void update(int id, int l, int r, int i, Node node) { if (i < l || r < i) { return; } if (l == r) { st[id] = node; return; } int mid = (l + r) >> 1; update((id << 1) + 1, l, mid, i, node); update((id << 1) + 2, mid + 1, r, i, node); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } Node get(int x, int y) { return get(0, 0, n - 1, x, y); } private Node get(int id, int l, int r, int x, int y) { if (x > r || y < l) { return new Node(0); } if (x <= l && r <= y) { return st[id]; } int mid = (l + r) >> 1; return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y)); } Node comb(Node a, Node b) { if (a == null) { return b; } if (b == null) { return a; } return new Node(GCD(a.val, b.val)); } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
f6ec4d89f1bbdad877622a3ac576fe8a
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.StringTokenizer; public class CodeForces { static int mod = (int)1e9+7; public static void main(String[] args) throws InterruptedException { // PrintWriter out = new PrintWriter("output.txt"); // File input = new File("input.txt"); // FastScanner fs = new FastScanner(input); FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int testNumber =1; for (int T =0;T<testNumber;T++){ int n = fs.nextInt(); int []arr = new int[n+11]; int min1=(int)1e7; int min2=(int)1e7; for (int i=0;i<n;i++){ arr[i]=fs.nextInt(); if(arr[i]<min1){ min2=min1+0; min1=arr[i]; } else if (arr[i]<min2){ min2=arr[i]; } } int ans = (min1/2+(min1%2==0?0:1))+ (min2/2+(min2%2==0?0:1)); for (int i=0;i<n-2;i++){ int val = arr[i]+arr[i+2]; ans=Math.min(ans,val/2+(val%2==0?0:1)); } for (int i=0;i<n-1;i++){ int max = Math.max(arr[i],arr[i+1]); int min = Math.min(arr[i],arr[i+1]); if(2*min<=max){ ans=Math.min(ans,max/2+(max%2==0?0:1)); } else { int sub = max - min; int val = sub+0; max-=2*sub; min-=sub; int sum = max+min; val+=sum/3+(sum%3==0?0:1); ans=Math.min(ans,val); } } out.print(ans); } out.flush(); } static long modInverse( long n, long p) { return FastPower(n, p - 2, p); } static int[] factorials(int max,int mod){ int [] ans = new int[max+1]; ans[0]=1; for (int i=1;i<=max;i++){ ans[i]=ans[i-1]*i; ans[i]%=mod; } return ans; } static String toBinary(int num,int bits){ String res =Integer.toBinaryString(num); while(res.length()<bits)res="0"+res; return res; } static String toBinary(long num,int bits){ String res =Long.toBinaryString(bits); while(res.length()<bits)res="0"+res; return res; } static long LCM(long a,long b){ return a*b/gcd(a,b); } static long FastPower(long x,long p,long mod){ if(p==0)return 1; long ans =FastPower(x, p/2,mod); ans%=mod; ans*=ans; ans%=mod; if(p%2==1)ans*=x; ans%=mod; return ans; } static double FastPower(double x,int p){ if(p==0)return 1.0; double ans =FastPower(x, p/2); ans*=ans; if(p%2==1)ans*=x; return ans; } static int FastPowerInt(int x,int p){ if(p==0)return 1; int ans =FastPowerInt(x, p/2); ans*=ans; if(p%2==1)ans*=x; return ans; } static long FastPower(long x,long p){ if(p==0)return 1; long ans =FastPower(x, p/2); ans*=ans; if(p%2==1)ans*=x; return ans; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public FastScanner(File f){ try { br=new BufferedReader(new FileReader(f)); st=new StringTokenizer(""); } catch(FileNotFoundException e){ br=new BufferedReader(new InputStreamReader(System.in)); 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()); } 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; } long[] readLongArray(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()); } } public static long factorial(int n){ if(n==0)return 1; return (long)n*factorial(n-1); } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static void sort (int[]a){ ArrayList<Integer> b = new ArrayList<>(); for(int i:a)b.add(i); Collections.sort(b); for(int i=0;i<b.size();i++){ a[i]=b.get(i); } } static void sortReversed (int[]a){ ArrayList<Integer> b = new ArrayList<>(); for(int i:a)b.add(i); Collections.sort(b,new Comparator<Integer>(){ @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }); for(int i=0;i<b.size();i++){ a[i]=b.get(i); } } static void sort (long[]a){ ArrayList<Long> b = new ArrayList<>(); for(long i:a)b.add(i); Collections.sort(b); for(int i=0;i<b.size();i++){ a[i]=b.get(i); } } static ArrayList<Integer> sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } ArrayList<Integer> ans = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (prime[i] == true) ans.add(i); } return ans; } static int binarySearchSmallerOrEqual(int arr[], int key) { int n = arr.length; int left = 0, right = n; int mid = 0; while (left < right) { mid = (right + left) >> 1; if (arr[mid] == key) { while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } else if (arr[mid] > key) right = mid; else left = mid + 1; } while (mid > -1 && arr[mid] > key) mid--; return mid; } static int binarySearchSmallerOrEqual(long arr[], long key) { int n = arr.length; int left = 0, right = n; int mid = 0; while (left < right) { mid = (right + left) >> 1; if (arr[mid] == key) { while (mid + 1 < n && arr[mid + 1] == key) mid++; break; } else if (arr[mid] > key) right = mid; else left = mid + 1; } while (mid > -1 && arr[mid] > key) mid--; return mid; } public static int binarySearchStrictlySmaller(int[] arr, int target) { int start = 0, end = arr.length-1; if(end == 0) return -1; if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } public static int binarySearchStrictlySmaller(long[] arr, long target) { int start = 0, end = arr.length-1; if(end == 0) return -1; if (target > arr[end]) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } static int binarySearch(int arr[], int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) return m; if (arr[m] < x) l = m + 1; else r = m - 1; } return -1; } static int binarySearch(long arr[], long x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) return m; if (arr[m] < x) l = m + 1; else r = m - 1; } return -1; } static void init(int[]arr,int val){ for(int i=0;i<arr.length;i++){ arr[i]=val; } } static void init(int[][]arr,int val){ for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[i].length;j++){ arr[i][j]=val; } } } static void init(long[]arr,long val){ for(int i=0;i<arr.length;i++){ arr[i]=val; } } static<T> void init(ArrayList<ArrayList<T>>arr,int n){ for(int i=0;i<n;i++){ arr.add(new ArrayList()); } } static int binarySearchStrictlySmaller(ArrayList<Pair> arr, int target) { int start = 0, end = arr.size()-1; if(end == 0) return -1; if (target > arr.get(end).y) return end; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr.get(mid).y >= target) { end = mid - 1; } else { ans = mid; start = mid + 1; } } return ans; } static int binarySearchStrictlyGreater(int[] arr, int target) { int start = 0, end = arr.length - 1; int ans = -1; while (start <= end) { int mid = (start + end) / 2; if (arr[mid] <= target) { start = mid + 1; } else { ans = mid; end = mid - 1; } } return ans; } public static long pow(long n, long pow) { if (pow == 0) { return 1; } long retval = n; for (long i = 2; i <= pow; i++) { retval *= n; } return retval; } static String reverse(String s){ StringBuffer b = new StringBuffer(s); b.reverse(); return b.toString(); } static String charToString (char[] arr){ String t=""; for(char c :arr){ t+=c; } return t; } int[] copy (int [] arr , int start){ int[] res = new int[arr.length-start]; for (int i=start;i<arr.length;i++)res[i-start]=arr[i]; return res; } static int[] swap(int [] A,int l,int r){ int[] B=new int[A.length]; for (int i=0;i<l;i++){ B[i]=A[i]; } int k=0; for (int i=r;i>=l;i--){ B[l+k]=A[i]; k++; } for (int i=r+1;i<A.length;i++){ B[i]=A[i]; } return B; } static int mex (int[] d){ int [] a = Arrays.copyOf(d, d.length); sort(a); if(a[0]!=0)return 0; int ans=1; for(int i=1;i<a.length;i++){ if(a[i]==a[i-1])continue; if(a[i]==a[i-1]+1)ans++; else break; } return ans; } static int[] mexes(int[] arr){ int[] freq = new int [100000+7]; for (int i:arr)freq[i]++; int maxMex =0; for (int i=0;i<=100000+7;i++){ if(freq[i]!=0)maxMex++; else break; } int []ans = new int[arr.length]; ans[arr.length-1] = maxMex; for (int i=arr.length-2;i>=0;i--){ freq[arr[i+1]]--; if(freq[arr[i+1]]<=0){ if(arr[i+1]<maxMex) maxMex=arr[i+1]; ans[i]=maxMex; } else { ans[i]=ans[i+1]; } } return ans; } static int [] freq (int[]arr,int max){ int []b = new int[max]; for (int i:arr)b[i]++; return b; } static int[] prefixSum(int[] arr){ int [] a = new int[arr.length]; a[0]=arr[0]; for (int i=1;i<arr.length;i++)a[i]=a[i-1]+arr[i]; return a; } static class Pair { int x; int y; int extra; public Pair(int x,int y){ this.x=x; this.y=y; } public Pair(int x,int y,int extra){ this.x=x; this.y=y; this.extra=extra; } // @Override // public boolean equals(Object o) { // if(o instanceof Pair){ // if(o.hashCode()!=hashCode()){ // return false; // } else { // return x==((Pair)o).x&&y==((Pair)o).y; // } // } // // return false; // // } // // // // // // @Override // public int hashCode() { // return x+(int)y*2; // } // // } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
b8406d074e2371c09c7150af4c036a45
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.sqrt; import static java.lang.Math.floor; public class Solution { static class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } public static int max(int []nums, int s, int e) { int max = Integer.MIN_VALUE; for(int i = s; i <= e; i++) { max = Math.max(max, nums[i]); } return max; } static int depth(TreeNode root) { if(root == null)return 0; int a = 1+ depth(root.left); int b = 1+ depth(root.right); return Math.max(a,b); } static HashSet<Integer>set = new HashSet<>(); static void deepestLeaves(TreeNode root, int cur_depth, int depth) { if(root == null)return; if(cur_depth == depth)set.add(root.val); deepestLeaves(root.left,cur_depth+1,depth); deepestLeaves(root.right,cur_depth+1,depth); } public static void print(TreeNode root) { if(root == null)return; System.out.print(root.val+" "); System.out.println("er"); print(root.left); print(root.right); } public static HashSet<Integer>original(TreeNode root){ int d = depth(root); deepestLeaves(root,0,d); return set; } static HashSet<Integer>set1 = new HashSet<>(); static void leaves(TreeNode root) { if(root == null)return; if(root.left == null && root.right == null)set1.add(root.val); leaves(root.left); leaves(root.right); } public static boolean check(HashSet<Integer>s, HashSet<Integer>s1) { if(s.size() != s1.size())return false; for(int a : s) { if(!s1.contains(a))return false; } return true; } static TreeNode subTree; public static void smallest_subTree(TreeNode root) { if(root == null)return; smallest_subTree(root.left); smallest_subTree(root.right); set1 = new HashSet<>(); leaves(root); boolean smallest = check(set,set1); if(smallest) { subTree = root; return; } } public static TreeNode answer(TreeNode root) { smallest_subTree(root); return subTree; } } static class Key<K1, K2> { public K1 key1; public K2 key2; public Key(K1 key1, K2 key2) { this.key1 = key1; this.key2 = key2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; if (key1 != null ? !key1.equals(key.key1) : key.key1 != null) { return false; } if (key2 != null ? !key2.equals(key.key2) : key.key2 != null) { return false; } return true; } @Override public int hashCode() { int result = key1 != null ? key1.hashCode() : 0; result = 31 * result + (key2 != null ? key2.hashCode() : 0); return result; } @Override public String toString() { return "[" + key1 + ", " + key2 + "]"; } } public static int sumOfDigits (long n) { int sum = 0; while(n > 0) { sum += n%10; n /= 10; } return sum; } public static void swap(int []ar, int i, int j) { for(int k= j; k >= i; k--) { int temp = ar[k]; ar[k] = ar[k+1]; ar[k+1] = temp; } } public static int findOr(int[]bits){ int or=0; for(int i=0;i<32;i++){ or=or<<1; if(bits[i]>0) or=or+1; } return or; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } public static Long gcd(Long a, Long b) { if (a == 0) return b; return gcd(b%a, a); } static long nextPrime(long n) { boolean found = false; long prime = n; while(!found) { prime++; if(isPrime(prime)) found = true; } return prime; } // method to return LCM of two numbers static Long lcm(Long a, Long b) { return (a / gcd(a, b)) * b; } static boolean isPrime(long n) { if(n <= 1)return false; if(n <= 3)return true; if(n%2 == 0 || n%3 == 0)return false; for(int i = 5; i*i <= n; i+= 6) { if(n%i == 0 || n%(i+2) == 0) return false; } return true; } static int countGreater(int arr[], int n, int k){ int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater); } static ArrayList<Integer>printDivisors(int n){ ArrayList<Integer>list = new ArrayList<>(); for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { // If divisors are equal, print only one if (n/i == i) list.add(i); else // Otherwise print both list.add(i); list.add(n/i); } } return list; } static void leftRotate(int l, int r,int arr[], int d) { for (int i = 0; i < d; i++) leftRotatebyOne(l,r,arr); } static void leftRotatebyOne(int l, int r,int arr[]) { int i, temp; temp = arr[l]; for (i = l; i < r; i++) arr[i] = arr[i + 1]; arr[r] = temp; } static class pairInPq<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<pairInPq<F, S>> { private F first; private S second; public pairInPq(F first, S second){ this.first = first; this.second = second; } public F getFirst(){return first;} public S getSecond(){return second;} // All the code you already have is fine @Override public int compareTo(pairInPq<F, S> o) { int retVal = getSecond().compareTo(o.getSecond()); if (retVal != 0) { return retVal; } return getFirst().compareTo(o.getFirst()); } } static long modInverse(long a, long m) { long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } static long power(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; } static TreeNode buildTree(TreeNode root,int []ar, int l, int r){ if(l > r)return null; int len = l+r; if(len%2 != 0)len++; int mid = (len)/2; int v = ar[mid]; TreeNode temp = new TreeNode(v); root = temp; root.left = buildTree(root.left,ar,l,mid-1); root.right = buildTree(root.right,ar,mid+1,r); return root; } static int LIS(int arr[], int n) { int lis[] = new int[n]; int i, j, max = 0; /* Initialize LIS values for all indexes */ for (i = 0; i < n; i++) lis[i] = 1; /* Compute optimized LIS values in bottom up manner */ for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; /* Pick maximum of all LIS values */ for (i = 0; i < n; i++) if (max < lis[i]) max = lis[i]; return max; } static void permuteString(String s , String answer) { if (s.length() == 0) { System.out.print(answer + " "); return; } for(int i = 0 ;i < s.length(); i++) { char ch = s.charAt(i); String left_substr = s.substring(0, i); String right_substr = s.substring(i + 1); String rest = left_substr + right_substr; permuteString(rest, answer + ch); } } static boolean isPowerOfTwo(long n) { if(n==0) return false; return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))); } static class Pair1{ long x; long y; public Pair1(long x, long y) { this.x = x; this.y = y; } } static class Pair { int x; int y; int z; // Constructor public Pair(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } static class Sorting implements Comparator<Pair>{ public int compare(Pair p1, Pair p2){ if(p1.x==p2.x){ return p1.y-p2.y; } return p1.x - p2.x; } } static class Compare1{ static void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { return p1.z - p2.z; } }); } } static int min; static int max; static LinkedList<Integer>[]adj; static int n; static void insertlist(int n) { for(int i = 0; i <= n; i++) { adj[i] = new LinkedList<>(); } } static int []ar; static boolean []vis; static HashMap<Key,Integer>map; static ArrayList<Integer>list; static int dfs(int parent, int child,LinkedList<Integer>[]adj) { list.add(parent); for(int a : adj[parent]) { if(vis[a] == false) { vis[a] = true; return 1+dfs(a,parent,adj); } } return 0; } static StringTokenizer st; static BufferedReader ob; static int [] readarrayInt( int n)throws IOException { st = new StringTokenizer(ob.readLine()); int []ar = new int[n]; for(int i = 0; i < n; i++) { ar[i] = Integer.parseInt(st.nextToken()); } return ar; } static long [] readarrayLong( int n)throws IOException { st = new StringTokenizer(ob.readLine()); long []ar = new long[n]; for(int i = 0; i < n; i++) { ar[i] = Long.parseLong(st.nextToken()); } return ar; } static int readInt()throws IOException { return Integer.parseInt(ob.readLine()); } static long readLong()throws IOException { return Long.parseLong(ob.readLine()); } static int nextTokenInt() { return Integer.parseInt(st.nextToken()); } static long nextTokenLong() { return Long.parseLong(st.nextToken()); } static int root(int u) { if(ar[u] == -1)return -1; if(u == ar[u]) { return u; } return root(ar[u]); } static Pair []pairar; static int numberOfDiv(long num) { int c = 0; for(int i = 1; i <= Math.sqrt(num ); i++) { if(num%i == 0) { long d = num/i; if( d == i)c++; else c += 2; } } return c; } static long ans; static int count; static boolean []computed; static void NoOfWays(int n) { if(n == 0 ) { count++; } if(n <= 0)return; for(int i = 1; i <= n; i++) { if(n+i <= n) NoOfWays(n-i); } } static boolean binarylistsearch( List<Integer>list, int l, int r, int s, int e) { if(s > e)return false; int mid = (s+e)/2; if(list.get(mid) >= l && list.get(mid) < r) { return true; }else if(list.get(mid) > r) { return binarylistsearch(list,l,r,s,mid-1); }else if(list.get(mid) < l) { return binarylistsearch(list,l,r,mid+1,e); } return false; } static int [][] readmatrix(int r, int c)throws IOException{ int [][]mat = new int[r][c]; for(int i = 0; i < r; i++) { st = new StringTokenizer(ob.readLine()); for(int j = 0; j < c; j++) { mat[i][j] = nextTokenInt(); } } return mat; } static HashSet<Integer>set1; static boolean possible; static int c = 0; static void isbeautiful(HashSet<Integer>s,int num, List<Integer>good, int i, int x, int count) { if(c == 2) { possible = true; return; } if(num >x || i == good.size())return; if(num > x)return; if(i >= good.size())return; for(int j = i; j < good.size(); j++) { if(!map.containsKey(new Key(num,good.get(j))) && !map.containsKey(new Key(good.get(j),num))){ if(s.contains(num) && s.contains(good.get(j))) map.put(new Key (num,good.get(j)),1); isbeautiful(s,num*good.get(j),good,i,x,count); } } } static long sum; static long mod; static void recur(HashSet<Integer>set,HashMap<Integer,HashSet<Integer>>map, int n, int j) { if(j > n)return; int v = 0; for(int a : set) { if(map.get(j).contains(a)) { v++; } } long d = map.get(j).size()-v; sum = (sum*d)%mod; HashSet<Integer> temp = map.get(j); for(int num : temp) { if(!set.contains(num)) { set.add(num); recur(set,map,n,j+1); set.remove(num); } } } static int key1; static int key2; static HashSet<Integer>set; public static TreeNode lowestCommonAncestor(TreeNode root) { if(root == null)return null; TreeNode left = lowestCommonAncestor(root.left); TreeNode right =lowestCommonAncestor(root.right); if(left == null && right != null) { System.out.println(right.val); return right; }else if(right == null && left != null) { System.out.println(left.val); return left; }else if(left == null && right == null) { return null; }else { System.out.println(root.val); return root; } } static ArrayList<Integer>res; static boolean poss = false; public static void recur1 (char []ar, int i) { if(i >= ar.length) { boolean isPalindrome = false; for(int k = 0; k < ar.length; k++) { for(int j = 0; j < ar.length; j++) { if(j-k+1 >= 5) { int x = k; int y = j; while(x < y && ar[x] == ar[y]) { x++; y--; } if(x == y || x > y) { isPalindrome = true; } } } } if(!isPalindrome) { poss = true; } } if(i < ar.length && ar[i] == '?' ) { ar[i] = '0'; recur1(ar,i+1); ar[i] = '?'; } if(i < ar.length && ar[i] == '?') { ar[i] = '1'; recur1(ar,i+1); ar[i] = '?'; } if(i < ar.length && ar[i] != '?') { recur1(ar,i+1); } } static int []theArray; static int rotate(int []ar, int element, int i) { int count = 0; while(ar[i] != element) { int last = ar[i]; count++; int prev = ar[1]; for(int j = 2; j <= i; j++) { int temp = ar[j]; ar[j] = prev; prev = temp; } ar[1] = prev; } return count; } static int []A; static long nth(long max, long min, int n){ long mod = 1000000007; if(max%min == 0){ System.out.println(min*n); return (min*n)%mod; }else{ long d = max/min; d++; long e = n/d; long ans = (max*e)%mod; long r = n%d; long div = (ans/min); long temp = (div*min); long f = (temp*r)%mod; ans = f; if(temp == ans){ ans += min; } System.out.println(ans); return ans; } } public static int index(int k, int l, int r) { if(r-l == 1) { if(ar[r] >= k && ar[l] < k) { return l; } }else if(l >= r){ return l; } int mid = (l+r)/2; if(ar[mid] >= k) { return index(k,l,mid-1); }else { return index(k,mid+1,r); } } public static int remSnakes(int start, int end, int k) { int rem = k-ar[end]; if(start+rem > end ) { return 0; }else { return 1+ remSnakes(start+rem,end-1,k); } } static int N; static int []tree = new int[2*N]; static void build(int []arr,boolean odd) { for(int i = 0; i < N; i++) { tree[N+i] = arr[i]; } for(int i = N-1; i > 0; --i) { int left = i << 1; int right = i << 1|1; if(odd) tree[i] = tree[i<<1]|tree[i<<1|1]; else tree[i] = tree[i<<1]^tree[i<<1|1]; } } // function to update a tree node static void updateTreeNode(int p, int value, boolean odd) { // set value at position p tree[p + N] = value; p = p + N; // move upward and update parents for (int i = p; i > 1; i >>= 1) if(odd) tree[i >> 1] = tree[i] | tree[i^1]; else tree[i >> 1] = tree[i]^tree[i^1]; } static int query(int l ,int r) { int res = 0; //loop to build the sum in the range for(l += N, r += N; l < r; l >>= 1, r >>= 1) { if((l&1) > 0) { res += tree[--r]; } if((r&1) > 0) { res += tree[l++]; } } return res; } static int sum1; static void min_line(int u, int min) { for(int i : adj[u]) { min_line(i,min); } System.out.println(u); } static class Key1 { public final int X; public final int Y; public Key1(final int X, final int Y) { this.X = X; this.Y = Y; } public boolean equals (final Object O) { if (!(O instanceof Key1)) return false; if (((Key1) O).X != X) return false; if (((Key1) O).Y != Y) return false; return true; } public int hashCode() { return (X << 16) + Y; } } static void solve() { int []points = new int[26]; int []top_pos = new int[26]; String []ar = {"ABC"}; Arrays.fill(top_pos, Integer.MAX_VALUE); for(int i = 0; i < ar.length; i++) { String s = ar[i]; for(int j = 0; j < s.length(); j++) { int pos = 97-(s.charAt(j)-'0'); points[pos] += (j); if(j < top_pos[pos]) { top_pos[pos] = j; } } } int i = 0; boolean []vis = new boolean[26]; StringBuilder sb = new StringBuilder(); while(true) { int min = Integer.MAX_VALUE; for(int j = 0; j < 26; j++) { if(vis[j] == false) { min = Math.min(min, points[j]); } } if(min == Integer.MAX_VALUE)break; PriorityQueue<pairInPq>pq = new PriorityQueue<>(); for(int j = 0; j < 26; j++) { if(points[j] == min) { vis[j] = true; char c = (char)(j + 'a'); pq.add(new pairInPq(c,top_pos[j])); } } while(pq.size() > 0) { pairInPq p = pq.poll(); char c = (char)p.first; sb.append(c); } } String res = sb.toString(); res = res.toUpperCase(); System.out.println(res); } static boolean al_sub(String s, String a) { int k = 0; for(int i = 0; i < s.length(); i++) { if(k == a.length())break; if(s.charAt(i) == a.charAt(k)) { k++; } } return k == a.length(); } static String result(String s, String a) { char []s_ar = s.toCharArray(); char []a_ar = a.toCharArray(); StringBuilder sb = new StringBuilder(); if(s.length() < a.length()) { for(int i = 0; i < s.length(); i++) { if(s_ar[i] == '?')s_ar[i] = 'a'; } }else { if(al_sub(s,a)) { return "-1"; }else { int k = 0; char element = 'z'; for(char i = 'a'; i <= 'e'; i++) { char []temp = s.toCharArray(); boolean pos = true;; for(int j = 0; j < s.length(); j++) { if(temp[j] == '?') { temp[j] = i; } } boolean sub = false; k = 0; for(int j = 0; j < s.length(); j++) { if(k == a.length()) { pos = false; break; } if(a_ar[k] == temp[j]) { k++; } } if(pos && k < a.length()) { element = i; break; } } if(element == 'z')return "-1"; for(int i = 0; i < s.length(); i++) { if(s_ar[i] == '?') { s_ar[i] = element; } sb.append(s_ar[i]); } return sb.toString(); } } return "-1"; } static void addNodes(ListNode l, int k) { if(k > 10 )return; ListNode temp = new ListNode(k); l.next = temp; addNodes(l.next,k+1); } static ListNode head; static int listnode_recur(ListNode tail) { if(tail == null )return 0; int n = listnode_recur(tail.next); max = Math.max(max, tail.val+head.val); head = head.next; return max; } static void recursion(int []fill, int len, int []valid, int k) { if(k == len) { int num = 0; for(int i = 0; i < fill.length; i++) { num = (num*10)+fill[i]; } System.out.println(num); if(!set.contains(num)) { set.add(num); } return; } for(int i = 0; i < valid.length; i++) { if(fill[k] == 0) { fill[k] = valid[i]; recursion(fill,len,valid,k+1); fill[k] = 0; }else { recursion(fill,len,valid,k+1); } } } static long minans(Long []ar,Long max) { Long one = 0l; Long two = 0l; for(int i = 0; i < ar.length; i++) { Long d = (max-ar[i])/2; two += d; one += (max-ar[i])%2; } Long ans = 0l; if(one >= two) { ans += (two*2); // System.out.println(one+" "+two+" "+ans); one -= two; if(one > 0) ans += (one*2)-1; }else { ans += (one*2); if(two > 0) { two -= one; Long d = two/3; Long temp = d*3; Long r = two%3; ans += temp; ans += d; if(r == 2) { ans += 3; }else if(r == 1){ ans += 2; } } } if(ans < 0)ans = 0l; // System.out.println(one+" "+two+" "+ans); return ans; } static int binarySearch(long []dif,long left, int s, int e) { if(s > e)return s; int mid = (s+e)/2; if(dif[mid] > left) { return binarySearch(dif,left,s,mid-1); }else { return binarySearch(dif,left,mid+1,e); } } public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { int size1 = getLength(l1); int size2 = getLength(l2); ListNode head = new ListNode(1); // make sure length l1 >= length2 head.next = size1 < size2?helper(l2,l1,size2-size1):helper(l1,l2,size1-size2); if(head.next.val > 9) { head.next.val = head.next.val%10; return head; } return head.next; } public static int getLength(ListNode l1) { int count = 0; while(l1 != null) { l1 = l1.next; count++; } return count; } public static ListNode helper(ListNode l1, ListNode l2, int offset) { if(l1 == null)return null; ListNode result = offset == 0?new ListNode(l1.val+l2.val):new ListNode(l1.val); System.out.println(l1.val+" "+l2.val); ListNode post = offset == 0?helper(l1.next,l2.next,0):helper(l1.next,l2,offset-1); if(post != null && post.val > 9) { result.val += 1; post.val = post.val%10; } result.next = post; return result; } public static ListNode arrayToLinkedList(int []ar, ListNode head) { head = new ListNode(0); head.next = null; ListNode h = head; for(int i = 0; i < ar.length; i++) { ListNode cur = new ListNode(ar[i]); if(h == null) { h = cur; }else{ h.next = cur; h = h.next; } } return head.next; } static Long numLessThanN(Long n, int s, int e,Long []powerful) { if(s >= e) { if(powerful[s] > n)return powerful[s-1]; return powerful[s]; } int mid = (s+e)/2; if(powerful[mid] == n) { return powerful[mid]; }else if(powerful[mid] > n && powerful[mid-1] < n) { return powerful[mid-1]; }else if(powerful[mid] > n){ return numLessThanN(n,0,mid-1,powerful); }else { return numLessThanN(n,mid+1,e,powerful); } } static Long minimumX; static void minX(Long x, Long c) { Long p = 2l; Long a = x; if(x > minimumX)return; if(x == 1)return; while(p*p <= x) { int count = 0; Long num = (long)Math.pow(p, c); Long minx = lcm(num,x); minx = minx/(gcd(num,x)); minimumX = Math.min(minimumX, minx); // System.out.println(minimumX+" "+x+" "+p+" "+num); //System.out.println(minx+" "+"df"+" "+p); if(minx < x) { minX(minx,c); } p++; } } static boolean isConsecutive (List<Integer>list) { for(int i : list) { if(i > 3)return false; } int x = 0; int y = 0; for(int i = 0; i < list.size(); i++) { if(list.get(i) == 2) { x++; }else if(list.get(i) == 3)y++; } if(y >= 2 || x >= 3)return false; if(x > 0 && y > 0)return false; return true; } static int []ismean(int []ar, int one, int minusone, int []temp){ int n = ar.length; for(int i = 1; i < n-1; i++) { if(temp[i] == 1 && temp[i-1] == -1 && one > 0) { one--; temp[i+1] = 1; }else if(temp[i-1] == -1 && temp[i] == -1 && one > 0) { temp[i+1] = 1; one--; }else if(temp[i] == -1 && temp[i-1] == 1 && minusone > 0) { minusone--; temp[i+1] = -1; }else if(temp[i] == 1 && temp[i-1] == 1 && minusone > 0) { minusone--; temp[i+1] = -1; }else { return temp; } } return temp; } static boolean isnottwo(int []ar, int one, int minusone,int temp[]) { int n = ar.length; int []ans = ismean(ar,one,minusone,temp); if(ans[n-1] != -2)return true; return false; } public static long findClosest(long arr[], long target) { int n = arr.length; // Corner cases if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; // Doing binary search int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid]; /* If target is less than array element, then search in left */ if (target < arr[mid]) { // If target is greater than previous // to mid, return closest of two if (mid > 0 && target > arr[mid - 1]) return getClosest(arr[mid - 1], arr[mid], target); /* Repeat for left half */ j = mid; } // If target is greater than mid else { if (mid < n-1 && target < arr[mid + 1]) return getClosest(arr[mid], arr[mid + 1], target); i = mid + 1; // update i } } // Only single element left after search return arr[mid]; } // Method to compare which one is the more close // We find the closest by taking the difference // between the target and both values. It assumes // that val2 is greater than val1 and target lies // between these two. public static long getClosest(long val1, long val2, long target) { if (target - val1 >= val2 - target) return val2; else return val1; } static long minsumairblow; static void airblow(int p,int n,long [][]ar, int index, long element, long sum) { if(index == n) { minsumairblow = Math.min(minsumairblow, sum); return; } long left = Math.abs(element-ar[index][0]); long right = Math.abs(element-ar[index][p-1]); if(left <= right) { airblow(p,n,ar,index+1,ar[index][p-1],sum+left); }else { airblow(p,n,ar,index+1,ar[index][0],sum+right); } } static void helper() { // int n = 2; long []ar =new long[n]; ArrayList<Long>odd = new ArrayList<>(); ArrayList<Long>even = new ArrayList<>(); for(int i = 0; i < n; i++) { if(ar[i]%2 == 0) { even.add(ar[i]); }else { odd.add(ar[i]); } } Collections.sort(odd); Collections.sort(even); long alex = 0; long bob = 0; int i = even.size()-1; int j = odd.size()-1; int k = 0; while(i > 0 && j > 0) { alex += odd.get(j); alex += even.get(i-1); bob += even.get(i); bob += odd.get(j-1); i -= 2; j -= 2; } if(j >= 0) { alex += odd.get(j); } if(i >= 0) { bob += even.get(i); } long alex1 = 0; long bob1 = 0; i = even.size()-1; j = odd.size()-1; k = 0; while(i > 0 && j > 0) { alex1 += even.get(i); alex1 += odd.get(j-1); bob1 += odd.get(j); bob1 += even.get(i-1); i -= 2; j -= 2; } if(j >= 0) { bob1 += odd.get(j); } if(i >= 0) { alex1 += even.get(i); } long alex2 = 0; long bob2 = 0; i = even.size()-1; j = odd.size()-1; while(i > 0 && j > 0) { alex2 += even.get(i); alex2 += odd.get(j); i--; j--; bob2 += even.get(i); bob2 += odd.get(j); i--; j--; } if(i >= 0) { alex2 += even.get(i); } if(j >= 0) alex2 += odd.get(j); long alex3 = 0; long bob3 = 0; i = even.size()-1; j = odd.size()-1; while(i > 0 && j > 0) { alex3 += odd.get(j); alex3 += even.get(i); i--; j--; bob3 += odd.get(j); bob3 += even.get(i); i--; j--; } if(i >= 0) { alex3 += even.get(i); } if(j >= 0) alex3 += odd.get(j); long a = 0; long b = 0; long fin = alex; long ans = alex+bob; long ans1 = alex1+bob1; long ans2 = alex2+bob2; long ans3 = alex3+bob3; long res = ans; if(ans1 > res) { fin = alex1; res = ans1; } if(ans2 > res) { fin = alex2; res = ans2; } if(ans3 > res) { fin = alex3; res = ans3; } System.out.println(fin); } static boolean evenpoweroftwo(long num) { int count = 0; while(num > 2 && (num/2)%2 == 0) { num /= 2; count++; } if(num == 2) { num = 1; count++; } if(num == 1 && count%2 == 0)return true; // System.out.println(num+" "+count); return false; } static long maxscore; static void max_score(int index,long []ar, int k, int z, long sum, int bit ) { if(k == 0) { maxscore = Math.max(maxscore,sum); return; } sum += ar[index]; max_score(index+1,ar,k-1,z,sum,0); if(bit == 0 && z > 0) { max_score(index-1,ar,k-1,z-1,sum,1); } } static boolean substringtrip(String s) { int n = s.length(); if(s.length() == 1)return true; HashSet<Character>set = new HashSet<>(); HashMap<Character,Integer>map = new HashMap<>(); for(int i = 0; i < s.length(); i++) { set.add(s.charAt(i)); } int counter = set.size(); HashSet<Character>temp = new HashSet<>(); String res = s; int number = counter; for(int i = 0; i < n && counter > 0; i++) { if(temp.contains(s.charAt(i))) { return false; } temp.add(s.charAt(i)); counter--; } int k1 = set.size(); for(int i = k1; i < s.length(); i++) { if(s.charAt(i) != s.charAt(i-k1))return false; } return true; } static long res3; static void maxteampos(long b,long c, long m, long d) { if(b >= c) { return; } long extra = c-(b); extra += m-b; extra += d; // System.out.println(b); if(extra >= c) { res3 = Math.max(res3, b); maxteampos((b+((c-b)/2))+1,c,m,d); }else { maxteampos(b/2,c,m,d); } return; } public static void main(String args[])throws IOException { ob = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(ob.readLine()); int []ar = readarrayInt(n); int ans = Integer.MAX_VALUE; for(int i = 0; i < n-1; i++) { int min = Math.min(ar[i], ar[i+1]); int max = Math.max(ar[i], ar[i+1]); int d = (max/2)+(max%2); if(min <= d) { ans = Math.min(ans, d); }else { int e = (min+max)/3; if((min+max)%3 > 0)e++; ans = Math.min(e, ans); } } for(int i = 1; i < n-1; i++) { int min = Math.min(ar[i-1], ar[i+1]); int max = Math.max(ar[i+1], ar[i-1]); int e = min; e += (max-min)/2 + (max-min)%2; ans = Math.min(ans, e); } int first = Integer.MAX_VALUE; int sec = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { if(ar[i] < first) { sec = first; first = ar[i]; }else if(ar[i] < sec) { sec = ar[i]; } } ans = Math.min(ans, (first+1)/2 + (sec+1)/2); // int a = (2+1)/2; // System.out.println(a); // System.out.println(first+" "+sec); System.out.println(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
9fc35b92ab125e7114652a74c7960da5
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Integer[] arr = new Integer[n]; int min1 = Integer.MAX_VALUE; int min2 = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); if (arr[i] < min1) { min2 = min1; min1 = arr[i]; } else if (arr[i] < min2) { min2 = arr[i]; } } int min = (min1 + 1) / 2 + (min2 + 1) / 2; for (int i = 1; i < n; i++) { if (Math.max(arr[i], arr[i - 1]) / 2 >= Math.min(arr[i], arr[i - 1])) { min = Math.min(min, (Math.max(arr[i], arr[i - 1])+1) / 2); } else min = Math.min(min, (int) Math.ceil((arr[i] + arr[i - 1]) / 3.0)); } for (int i = 0; i < n - 2; i++) { int k = (arr[i] + arr[i + 2] + 1) / 2; min = Math.min(min, k); } System.out.println(min); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
23d20836849fab82102b00aa9f71df3a
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class Main { private static void solve(int n, int[] arr){ int res = Integer.MAX_VALUE; for(int i = 1; i < n - 1; i++){ int large = Math.max(arr[i-1], arr[i+1]); int small = Math.min(arr[i-1], arr[i+1]); int diff = large - small; res = Math.min(res,small + (diff+1)/2); } for(int i = 0; i < n - 1; i++){ int large = Math.max(arr[i], arr[i+1]); int small = Math.min(arr[i], arr[i+1]); if(large >= 2 * small){ res = Math.min(res, (large+1)/2); } else { int d = large - small; large -= 2 * d; small -= d; res = Math.min(res, (large+small+2)/3 + d); } } int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; for(int val: arr){ if(val <= first){ second = first; first = val; } else if(val <= second){ second = val; } } res = Math.min(res, (first+1)/2 + (second+1)/2); out.println(res); } public static void main(String[] args){ MyScanner scanner = new MyScanner(); int testCount = 1; for(int testIdx = 1; testIdx <= testCount; testIdx++){ int n = scanner.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = scanner.nextInt(); } solve(n, arr); } 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
35fe1f413834bef78fb810c42fc63aa2
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class E_Breaking_the_Wall { static class Wall { public int idx, strength; public Wall(int idx, int strength) { this.idx = idx; this.strength = strength; } public String toString() { return idx + "_" + strength; } } public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); // try { // out = new PrintWriter("output.txt"); // } catch (Exception e) { // e.printStackTrace(); // } int n = in.nextInt(); int[] arr = in.readIntArray(n); int ans = Integer.MAX_VALUE; //Ai & Ai+1 for (int i = 0; i < n-1; i++) { int count = 0, curr_ans = 0;; int x = arr[i], y = arr[i+1]; if (x < y) { int t = x; x = y; y = t; } count += Math.min(x-y, (x+1)/2); x -= 2*count; y -= count; curr_ans += count; if (x > 0 && y > 0) curr_ans += (x+y+2)/3; ans = Math.min(ans, curr_ans); } // Ai and Ai+2 for (int i = 0; i < n-2; i++) { int x = arr[i], y = arr[i+2]; ans = Math.min(ans, (x + y + 1) / 2); } Arrays.sort(arr); ans = Math.min(ans, (arr[0]+1)/2 + (arr[1]+1)/2); out.println(ans); out.flush(); out.close(); } } // For fast input output class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { // br = new BufferedReader(new InputStreamReader(System.in)); try { br = new BufferedReader(new FileReader("input.txt")); } 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; } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } String[] readStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } } // end of fast i/o code
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
c7cd947a7da00016dddee88c0a7f2b32
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; public class ACM { private static int[] array; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); array = new int[n]; for (int i = 0; i < n; i++) array[i] = in.nextInt(); help(); } private static void help() { int[] heap = new int[2]; heap[0] = Math.min(array[0], array[1]); heap[1] = Math.max(array[0], array[1]); for (int i = 2; i < array.length; i++) { if (array[i] < heap[1]) heap[1] = array[i]; if (heap[0] > heap[1]) { int t = heap[0]; heap[0] = heap[1]; heap[1] = t; } } int res = (heap[0] + 1) / 2 + (heap[1] + 1) / 2; for (int i = 1; i < array.length; i++) { res = Math.min(res, near0(array[i - 1], array[i])); } for (int i = 2; i < array.length; i++) { res = Math.min(res, near1(array[i - 2], array[i])); } System.out.println(res); } private static int near0(int a, int b) { if (a < b) { int t = a; a = b; b = t; } if (b * 2 >= a) return (a + b + 2) / 3; else return b + (a - b * 2 + 1) / 2; } private static int near1(int a, int b) { return (a + b + 1) / 2; } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
bea72c6bcff8a8faa97f46d060ebdb3a
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class B { static PrintWriter pw; static Scanner sc; static long solve(int x, int y) { if (x > y) { int temp = x; x = y; y = temp; } int cnt = (y + 1) / 2; if (cnt > x) { return cnt; } else { return (x + y + 2) / 3; } } static long solve(int[] arr) { long ans1 = solve(arr[0], arr[1]); long ans2 = solve(arr[1], arr[2]); long ans3 = (Math.max(arr[0], arr[2]) - Math.min(arr[0], arr[2]) + 1) / 2 + Math.min(arr[0], arr[2]); return Math.min(Math.min(ans2, ans1), ans3); } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = new int[n + 2]; PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int i = 1; i <= n; i++) { arr[i] = sc.nextInt(); pq.add(arr[i]); } long ans = (int) 2e9; for (int i = 0; i < n; i++) { int[] cur = new int[] { arr[i], arr[i + 1], arr[i + 2] }; if (i == 0) { ans = Math.min(ans, solve(arr[i + 1], arr[i + 2])); } else if (i == n - 1) { ans = Math.min(ans, solve(arr[i], arr[i + 1])); } else { // pw.println(Arrays.toString(cur)+" "+solve(cur)); ans = Math.min(ans, solve(cur)); } } int f1 = (pq.poll() + 1) / 2 + (pq.poll() + 1) / 2; pw.println(Math.min(ans, f1)); pw.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(String s) throws IOException { br = new BufferedReader(new FileReader(new File(s))); } public String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
525f83f123af6b00a4df0c56793e1b7b
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; public class dict { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) arr[i]=sc.nextInt(); int pair=Integer.MAX_VALUE,triplet=Integer.MAX_VALUE,min=Integer.MAX_VALUE,smin=Integer.MAX_VALUE; for(int i=0;i<n;i++) { if(Math.ceil(arr[i]/2.0)<min) { smin=min; min=(int)Math.ceil(arr[i]/2.0); } else if(Math.ceil(arr[i]/2.0)<smin) smin=(int)Math.ceil(arr[i]/2.0); if(i<n-1) { if(arr[i]/(double)arr[i+1]>2 || arr[i+1]/(double)arr[i]>2) pair=Math.min(pair, (Math.max(arr[i], arr[i+1])%2==0 ? Math.max(arr[i], arr[i+1])/2 : Math.max(arr[i], arr[i+1])/2+1)); else pair=Math.min(pair, (arr[i]+arr[i+1])%3==0?(arr[i]+arr[i+1])/3:(arr[i]+arr[i+1])/3+1); } if(i>0 && i<n-1) triplet=Math.min(triplet, Math.min(arr[i-1], arr[i+1])+(Math.abs(arr[i-1]-arr[i+1])%2==0 ? Math.abs(arr[i-1]-arr[i+1])/2 : Math.abs(arr[i-1]-arr[i+1])/2+1)); } System.out.println(Math.min(pair, Math.min(triplet, min+smin))); sc.close(); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
2982b86374e513e2133cd10935dabdfb
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.io.*; public class CodeForces { public static void main(String[] args) throws FileNotFoundException { FastScanner fs = new FastScanner(); int n = fs.nextInt(); int firstSmall = Integer.MAX_VALUE, secondSmall = Integer.MAX_VALUE; int[] a = new int[n]; for(int i = 0; i < n; i++) { int x = fs.nextInt(); a[i] = x; if((x+1)/2 < firstSmall) { secondSmall = firstSmall; firstSmall = (x+1)/2; }else if( (x+1)/2 < secondSmall ) { secondSmall = (x+1)/2; } } int ans = firstSmall + secondSmall; for(int i = 0; i < n; i++) { int j = i+1; if(j<n) { int large = Math.max(a[i], a[j]); int small = Math.min(a[i], a[j]); if(small*2 >= large) { // System.out.println(i + " " + (small + large)/3); ans = Math.min(ans, (small+large)/3 + ((small+large)%3 != 0 ? 1 : 0)); }else { ans = Math.min(ans, (large+1)/2); } } j = i+2; if(j<n) { int small = Math.min(a[i], a[j]); int large = Math.max(a[i], a[j]); ans = Math.min(ans, small + (large-small)/2 + ( (large-small)%2 != 0 ? 1 : 0 )); } } System.out.println(ans); } static int fact(int num) { int ans = 1; for(int i = 1; i <= num; i++) { ans *= i; } return ans; } public static int gcd(int a, int b) { if(b == 0) return a; return gcd(b, a%b); } 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[] 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()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
01014973bfaeaaf0e8f9a28327faba47
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] dp = new int[1000001]; dp[1] = 1; dp[2] = 2; for (int i = 3; i < dp.length; i++) { dp[i] = 2 + dp[i - 3]; } Integer[] arr = new Integer[n]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } int min = 1000000000; for (int i = 0; i < arr.length; i++) { int a = 1000000000; int b = 1000000000; int c = 1000000000; b = arr[i]; if (i > 0) a = arr[i - 1]; if (i < arr.length - 1) c = arr[i + 1]; int res1 = Math.min(a, c); int zz = Math.max(a, c)-res1; res1+=(zz/2); res1+=(zz%2); if (i > 0) { int ma = Math.max(a, b); int mi = Math.min(a, b); int s = ma - mi; if (s >= mi) { res1 = Math.min(res1, ma / 2 + ma % 2); } else { mi -= s; res1 = Math.min(res1, s + dp[mi]); } } if (i < arr.length - 1) { int ma = Math.max(c, b); int mi = Math.min(c, b); int s = ma - mi; if (s >= mi) { res1 = Math.min(res1, ma / 2 + ma % 2); } else { mi -= s; res1 = Math.min(res1, s + dp[mi]); } } min = Math.min(res1, min); } Arrays.sort(arr); min = Math.min(min, arr[0] / 2 + arr[0] % 2 + arr[1] / 2 + arr[1] % 2); pw.println(min); pw.flush(); } public static int solve(int b, int x, int y) { if (b == 1) { if (x == y) { return 1; } return -1; } int c = 0; while (x < y) { x = b * x; c++; } if (x == y) return c; return -1; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
dde7facd2855988d2072024d51785ce0
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; import java.util.function.DoubleToLongFunction; public class Codeforces786{ static long mod = 1000000007L; static MyScanner sc = new MyScanner(); static void solve() { int x = sc.nextInt(); int y = sc.nextInt(); if(y%x!=0){ out.println(0+" "+0); }else{ out.println(1+" "+(y/x)); } } static void solve2(){ String str = "abcdefghijklmnopqrstuvwxyz"; HashMap<String,Integer> map = new HashMap<>(); int ind = 1; for(int i = 0;i<26;i++){ for(int j = 0;j<26;j++){ if(i==j) continue; map.put((str.charAt(i)+""+str.charAt(j)),ind++); } } int n = sc.nextInt(); for(int i = 0;i<n;i++){ String st = sc.nextLine(); out.println(map.get(st)); } } static void solve3(){ String s = sc.nextLine(); String t = sc.nextLine(); boolean flag = true; for(int i = 0;i<t.length();i++){ if(t.charAt(i)!='a') flag = false; } if(t.contains("a") && t.length()>1){ out.println(-1); return; } if(t.contains("a") && t.length()==1){ out.println(1); return; } long ans = 1; for(int i = 1;i<=s.length();i++){ ans *=2; } // ans = pow(2,s.length()); out.println(ans); // out.println(s.length()+1); } static void solve4(){ int n= sc.nextInt(); int arr[] = sc.readIntArray(n); if(n%2==0){ for(int i = 0;i<n;i+=2){ int min = Math.min(arr[i],arr[i+1]); int max = Math.max(arr[i],arr[i+1]); arr[i] = min; arr[i+1] = max; } }else{ for(int i = 1;i<n;i+=2){ int min = Math.min(arr[i],arr[i+1]); int max = Math.max(arr[i],arr[i+1]); arr[i] = min; arr[i+1] = max; } } int brr[] = Arrays.copyOf(arr,n); sort(brr); for(int i= 0;i<n;i++){ if(arr[i]!=brr[i]){ out.println("NO"); return; } } out.println("YES"); } static void solve5(){ int n = sc.nextInt(); int arr[]= sc.readIntArray(n); int brr[] = Arrays.copyOf(arr,n); sort(brr); long ans = (brr[0]+1)/2; ans += (brr[1]+1)/2; for(int i = 0;i<n-2;i++){ long temp = Math.min(arr[i],arr[i+2]); temp += ((Math.max(arr[i],arr[i+2])) - temp+1)/2; ans = Math.min(ans,temp); } for(int i = 0;i<n-1;i++){ long temp = (arr[i]+arr[i+1]+2)/3; temp = Math.max(temp,Math.max((arr[i]+1)/2,(arr[i+1]+1)/2)); ans = Math.min(temp,ans); } out.println(ans); } static void swap(char arr[][],int i,int j){ for(int k = j;k>0;k--){ if(arr[i][k]=='.'&& arr[i][k-1]=='*'){ char temp = arr[i][k]; arr[i][k] = arr[i][k-1]; arr[i][k-1] = temp; } } } static int search(int pre,int suf[],int i,int j){ while(i<=j){ int mid = (i+j)/2; if(suf[mid]==pre) return mid; else if(suf[mid]<pre) j = mid-1; else i = mid+1; } return Integer.MIN_VALUE; } static long pow(long a, long b) { if (b == 0) return 1; long res = pow(a, b / 2); res = (res * res) % 1_000_000_007; if (b % 2 == 1) { res = (res * a) % 1_000_000_007; } return res; } static int lis(int arr[],int n){ int lis[] = new int[n]; lis[0] = 1; for(int i = 1;i<n;i++){ lis[i] = 1; for(int j = 0;j<i;j++){ if(arr[i]>arr[j]){ lis[i] = Math.max(lis[i],lis[j]+1); } } } int max = Integer.MIN_VALUE; for(int i = 0;i<n;i++){ max = Math.max(lis[i],max); } return max; } static boolean isPali(String str){ int i = 0; int j = str.length()-1; while(i<j){ if(str.charAt(i)!=str.charAt(j)){ return false; } i++; j--; } return true; } static long gcd(long a,long b){ if(b==0) return a; return gcd(b,a%b); } static String reverse(String str){ char arr[] = str.toCharArray(); int i = 0; int j = arr.length-1; while(i<j){ char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } String st = new String(arr); return st; } static boolean isprime(int n){ if(n==1) return false; if(n==3 || n==2) return true; if(n%2==0 || n%3==0) return false; for(int i = 5;i*i<=n;i+= 6){ if(n%i== 0 || n%(i+2)==0){ return false; } } return true; } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); // int t = sc.nextInt(); int t= 1; while(t-- >0){ // solve(); // solve2(); // solve3(); // solve4(); solve5(); } // Stop writing your solution here. ------------------------------------- out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int[] readIntArray(int n){ int arr[] = new int[n]; for(int i = 0;i<n;i++){ arr[i] = Integer.parseInt(next()); } return arr; } int[] reverse(int arr[]){ int n= arr.length; int i = 0; int j = n-1; while(i<j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j--;i++; } return arr; } long[] readLongArray(int n){ long arr[] = new long[n]; for(int i = 0;i<n;i++){ arr[i] = Long.parseLong(next()); } return arr; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
aa9d67902bd9b47119648e3b3c30d260
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; public class Main { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } 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 nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); // int t = sc.ni();while(t-->0) solve(); w.close(); } static void solve() throws IOException { int n = sc.ni(); Integer[] arr = new Integer[n]; for(int i = 0; i < n; i++) arr[i] = sc.ni(); Integer[] arr2 = arr.clone(); Arrays.sort(arr2); long ans = ((arr2[0]+1)/2 + (arr2[1]+1)/2); for(int i = 0; i < n-1; i++) { int left = arr[i]; int right = arr[i+1]; int max = Math.max(left, right); int min = Math.min(left, right); int steps = (max+1)/2; if(min > steps) { int diff = max-min; steps = diff; int val = min-diff; steps += (val/3)*2 + (val%3); } ans = Math.min(ans, steps); } for(int i = 1; i < n-1; i++) { if(arr[i-1]%2==1 && arr[i+1]%2==1) { int steps = (arr[i-1]/2 + arr[i+1]/2) + 1; ans = Math.min(ans, steps); } } w.p(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
0ba818126318c73f86f3a7740564f456
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); // int t = Integer.parseInt(in.readLine()); // while (t-- > 0) { StringTokenizer st1 = new StringTokenizer(in.readLine()); StringTokenizer st2 = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st1.nextToken()); Integer[] a = new Integer[n]; int smallest1 = Integer.MAX_VALUE; int smallest2 = Integer.MAX_VALUE; for (int i=0; i<n; i++) { a[i] = Integer.parseInt(st2.nextToken()); if (a[i] < smallest1) { smallest2 = smallest1; smallest1 = a[i]; } else if (a[i] < smallest2) { smallest2 = a[i]; } } int ans = check1Wall(smallest1) + check1Wall(smallest2); // Check 1 for (int i=0; i<n; i++) { if (i < n-1) ans = Math.min(ans, check2Neighbours(a[i], a[i+1])); // check 2 if (i < n-2) ans = Math.min(ans, check3Neighbours(a[i], a[i+1], a[i+2])); // check 3 } out.println(ans); // } in.close(); out.close(); } private static int check1Wall(int x) { return x/2 + x%2; } private static int check2Neighbours(int x, int y) { if (x > y) { return check2Neighbours(y,x); } if (x*2 <= y) { return check1Wall(y); } else { // Eq.1 => a + 2b = x // Eq.2 => b + 2a = y ==== *2 ===> 2b + 4a = 2y // Eq.2-Eq.1 => 2b+4a - (a+2b) = 2y-x ===> 3a = 2y-x ===> a=(2y-x)/3 // Eq.1 => a + 2b = x ===> b = (x - a)/2 int temp = 2*y - x; int a = temp/3; if (temp%3 != 0) a++; int remainB = x - a; int ans = a + check1Wall(remainB); return ans; } } private static int check3Neighbours(int x, int y, int z) { return check1Wall(x+z); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
86fb06a72449280e633e0c125a4e12e6
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n+2]; for (int i=1; i<=n; i++) { a[i] = in.nextInt(); } a[0] = Integer.MAX_VALUE - 1; a[n+1] = Integer.MAX_VALUE - 1; int ans = Integer.MAX_VALUE; for (int i=1; i<=n; i++) { if (a[i-1] == 1 && a[i+1] == 1) ans = 1; ans = Math.min(ans, 1 + (a[i-1] / 2) + (a[i+1] / 2)); int cnt = (a[i] + 1) / 2; int min = Math.min(a[i-1], a[i+1]); if (min > cnt) cnt += (min - cnt + 1) / 2; ans = Math.min(ans, cnt); ans = Math.min(ans, solve(Math.max(a[i-1], a[i]), Math.min(a[i-1], a[i]))); } Arrays.sort(a); ans = Math.min(ans, (a[0] + 1) / 2 + (a[1] + 1) / 2); System.out.println(ans); } public static int solve(int a, int b) { if (a >= b * 2) return (a + 1) / 2; else { int diff = a - b; int temp = b - diff; int cnt = temp / 3 * 2; a -= cnt / 2 * 3; b -= cnt / 2 * 3; cnt += (a + 1) / 2; b -= (a + 1) / 2; if (b != 0) cnt++; return cnt; } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
dcb7f56c589348b69cf31efdd5adb870
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { private static final Scanner sc = new Scanner(System.in); public static void handleTest(){ int n = sc.nextInt(); int[] ar = new int[n]; for(int i = 0; i < n; i++){ ar[i] = sc.nextInt(); } int ans = 1<<30; for(int i = 0; i < n - 2; i++){ int temp = (ar[i] + ar[i + 2]); ans = Math.min(ans, temp/2 + temp%2); } for(int i = 0; i < n - 1; i++){ int tmx = Math.max(ar[i], ar[i + 1]); int tmn = Math.min(ar[i], ar[i + 1]); if(2*tmn <= tmx){ ans = Math.min(ans, tmx/2 + tmx%2); }else{ ans = Math.min(ans, (tmn + tmx)/3 + ((tmn + tmx)%3 != 0 ? 1 : 0)); } } Arrays.sort(ar); ans = Math.min(ans , (ar[0]/2 +ar[0]%2) + (ar[1]/2 +ar[1]%2)); System.out.println(ans); } public static void main(String[] args){ // int t = sc.nextInt(); // while(t-- != 0){ handleTest(); // } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
a88e86bb0378ed540687b98b1ffb04e2
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import javax.print.DocFlavor; import java.io.*; import java.util.*; public class Main { static PrintWriter pw; static Scanner sc; static final int inf = (int) 1e9, mod = inf + 7; static final long longInf = inf * 1l * inf; static final double eps = 1e-9; public static void main(String[] args) throws Exception { sc = new Scanner(System.in); pw = new PrintWriter(System.out); preCalc(); // int t = sc.nextInt(); // while (t-- > 0) testCase(); pw.close(); } static void testCase() throws Exception{ int n = sc.nextInt(); int[] arr = sc.nextArr(n); TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n; i++) add(map, arr[i]); int minCost = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int left = i > 0 ? arr[i - 1] : Integer.MAX_VALUE; int right = i < n - 1 ? arr[i + 1] : Integer.MAX_VALUE; int shots = Math.min(Math.min(left, right), (int) ceildiv(arr[i], 2)); // arr[i] -= shots * 2; rem(map, arr[i]); add(map, arr[i] - shots * 2); if(i > 0){ // arr[i - 1] -= shots; rem(map, arr[i - 1]); add(map, arr[i - 1] - shots); } if(i < n - 1) { // arr[i + 1] -= shots; rem(map, arr[i + 1]); add(map, arr[i + 1] - shots); } int totalShots = shots; if(map.firstEntry().getValue() != 2) totalShots += ceildiv(map.ceilingKey(map.firstKey() + 1), 2); minCost = Math.min(minCost, totalShots); rem(map, arr[i] - shots * 2); add(map, arr[i]); if(i > 0){ rem(map, arr[i - 1] - shots); add(map, arr[i - 1]); } if(i < n - 1) { rem(map, arr[i + 1] - shots); add(map, arr[i + 1]); } } for (int i = 1; i < n; i++) minCost = Math.min(minCost, cost(arr[i], arr[i-1])); pw.println(minCost); } static int cost(int x, int y){ if(x < y) return cost(y, x); if(x == y){ if(x < 0) return inf; return (x / 3) * 2 + x % 3; } int d = x - y; return d + cost(y - d, x - 2*d); } static void D() throws Exception{ int n = sc.nextInt(); int[] a = sc.nextArr(n); if(n == 1){ pw.println("YES"); return; } LinkedList<Integer> left = new LinkedList<>(); LinkedList<Integer> right = new LinkedList<>(); if(a[0] <= a[1]){ left.add(a[0]); right.add(a[1]); }else { left.add(a[1]); right.add(a[0]); } for (int i = 2; i < n; i++) { if(right.size() == left.size()){ left.add(a[i]); }else{ if(left.getLast() <= a[i]){ right.addFirst(a[i]); }else{ right.addFirst(left.pollLast()); left.addLast(a[i]); } } } left.addAll(right); printIter(left); } static HashMap<String, Integer> map; static void preCalc(){ map = new HashMap<>(); int idx = 1; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { if(i != j){ char x = (char) ('a' + i); char y = (char) ('a' + j); map.put(x + "" + y, idx++); } } } } static long ceildiv(long x, long y) { return (x + y - 1) / y; } static int mod(long x, int m) { return (int) ((x % m + m) % m); } static void add(Map<Integer, Integer> map, Integer p) { if (map.containsKey(p)) map.replace(p, map.get(p) + 1); else map.put(p, 1); } static void rem(Map<Integer, Integer> map, Integer p) { if (map.get(p) == 1) map.remove(p); else map.replace(p, map.get(p) - 1); } static int Int(boolean x) { return x ? 1 : 0; } public static long gcd(long x, long y) { return y == 0 ? x : gcd(y, x % y); } static void printArr(int[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(long[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(double[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(boolean[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] ? 1 : 0); pw.println(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(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 int[] nextDigits() throws IOException { String s = nextLine(); int[] arr = new int[s.length()]; for (int i = 0; i < arr.length; i++) arr[i] = s.charAt(i) - '0'; return arr; } public int[] nextArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public Integer[] nextSort(int n) throws IOException { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public int[] nextArrMinus1(int n) throws IOException{ int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt() - 1; return arr; } public Pair nextPair() throws IOException { return new Pair(nextInt(), nextInt()); } 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 Pair[] nextPairArr(int n) throws IOException { Pair[] arr = new Pair[n]; for (int i = 0; i < n; i++) arr[i] = nextPair(); return arr; } public boolean hasNext() throws IOException { return (st != null && st.hasMoreTokens()) || br.ready(); } } static void printArr(Integer[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printIter(Iterable list) { for (Object o : list) pw.print(o + " "); pw.println(); } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } public Pair(Map.Entry<Integer, Integer> a) { x = a.getKey(); y = a.getValue(); } public int hashCode() { return (int) ((this.x * 1l * 100003 + this.y) % mod); } public int compareTo(Pair p) { if (x != p.x) return x - p.x; return y - p.y; } public boolean equals(Object obj) { if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Pair p = (Pair) obj; return this.x == p.x && this.y == p.y; } public Pair clone() { return new Pair(x, y); } public String toString() { return this.x + " " + this.y; } public void subtract(Pair p) { x -= p.x; y -= p.y; } public void add(Pair p) { x += p.x; y += p.y; } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
ef30c26a594725f8f2fbbc9a9ba6c665
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.*; import java.io.*; public class BreakingTheWall_786E { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] nums = new int[n]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i ++) nums[i] = Integer.parseInt(st.nextToken()); int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE, res = Integer.MAX_VALUE; for(int i = 0; i < n; i ++) { if(nums[i] < first) { second = first; first = nums[i]; } else { second = Math.min(second, nums[i]); } if(i > 0) res = Math.min(res, adj(nums[i - 1], nums[i])); if(i > 1) res = Math.min(res, everyother(nums[i - 2], nums[i])); } res = Math.min(res, top2lowest(first, second)); System.out.println(res); } private static int top2lowest(int a, int b) { int res = a / 2; if(a % 2 != 0) res ++; res += b / 2; if(b % 2 != 0) res ++; return res; } private static int everyother(int a, int b) { if(a < b) { int temp = a; a = b; b = temp; } int res = b; a -= b; res += a / 2; if(a % 2 != 0) res ++; return res; } private static int adj(int a, int b) { if(a < b) { int temp = a; a = b; b = temp; } int res = 0; if(b < a / 2) { res += b; a -= 2 * b; res += a / 2; if(a % 2 != 0) res ++; } else { a += b; res += a / 3; if(a % 3 != 0) res ++; } return res; } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
f16334cc0bd5cf86c3c8a2ad704ab60b
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
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.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.function.IntToLongFunction; public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static final int mod = 998244353; static int t = 1; static double epsilon = 0.00000001; static boolean[] isPrime; static int[] smallestFactorOf; static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3; @SuppressWarnings({"unused"}) public static void main(String[] args) throws Exception { OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); int[] arr = fr.nextIntArray(n); // Observations: // 1. The task is to determine the minimum number of // shots required to break at least 2 walls. // -- // In one shot, we deal damage=2 to the target // wall and 1 to the adjacent ones (if exist). // 2. If the distance between the tgt sections is 3 // or more, we can independently break those two // walls using onager shots on them. // -- // Now, we have to consider walls at distance {1, 2}. int[] sorted = arr.clone(); sort(sorted); int minAns = (sorted[0] + 1) / 2 + (sorted[1] + 1) / 2; // assert: we only need to consider walls at distances {1, 2} for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j <= i + 2 && j < n; j++) { // {i, j} are the two walls we wanna deal with. // what are the ways we can optimally destroy both? int[] values = new int[2]; values[0] = arr[i]; values[1] = arr[j]; // we want to determine the minimum number of shots // required to destroy endpoints of 'values' if (j == i + 1) { // we can do (1, 2) or (2, 1) damage if (values[0] > values[1]) { int temp = values[0]; values[0] = values[1]; values[1] = temp; } // assert (values[i] <= values[j]) int numMovesHere = 0; // every move diminishes the difference // by 1 // -- // we will try to make both equal using // the moves int diff = values[1] - values[0]; int numClosingMoves = Math.min(diff, Math.min(values[0], (values[1] + 1) / 2)); values[0] -= numClosingMoves; values[1] -= 2 * numClosingMoves; numMovesHere += numClosingMoves; // there is a limited number of cases // we stopped closing diff due to: // a. Diff closed completely // b. We exhausted values[0] // c. We exhausted values[1] if (values[0] > 0 && values[1] > 0) { numMovesHere += (values[0] + values[1] + 2) / 3; } else numMovesHere += (values[1] + 1) / 2; minAns = Math.min(minAns, numMovesHere); } else { // we can do (1, 1), (0, 2) or (2, 0) damage // -- // this means, in one move, we can take out 2 blocks // as we wish // -- // we just need to take out all blocks int numMovesHere = (values[0] + values[1] + 1) / 2; minAns = Math.min(minAns, numMovesHere); } } } out.println(minAns); } out.close(); } static class Pair implements Comparable<Pair> { long first, second; Pair() { first = second = 0; } Pair (long ff, long ss) { first = ff; second = ss; } public int compareTo(Pair that) { if (this.first < that.first) return -1; if (this.first > that.first) return 1; return Long.compare(second, that.second); } } static class SegmentBeatExt implements Cloneable { private static long inf = (long) 2e18; private SegmentBeatExt left; private SegmentBeatExt right; private long firstLargest; private long secondLargest; private int firstLargestCnt; private long firstSmallest; private long secondSmallest; private int firstSmallestCnt; private long dirty; private int size; private long sum; private void setMin(long x) { if (firstLargest <= x) { return; } sum -= (firstLargest - x) * firstLargestCnt; firstLargest = x; if (firstSmallest >= x) { firstSmallest = x; firstSmallestCnt = size; } secondSmallest = Math.min(secondSmallest, x); if (secondSmallest == firstSmallest) { secondSmallest = inf; } } private void setMax(long x) { if (firstSmallest >= x) { return; } sum += (x - firstSmallest) * firstSmallestCnt; firstSmallest = x; if (firstLargest <= x) { firstLargest = x; firstLargestCnt = size; } secondLargest = Math.max(secondLargest, x); if (secondLargest == firstLargest) { secondLargest = -inf; } } private void modify(long x) { dirty += x; sum += x * size; firstSmallest += x; firstLargest += x; secondSmallest += x; secondLargest += x; } public void pushUp() { firstLargest = Math.max(left.firstLargest, right.firstLargest); secondLargest = Math.max(left.firstLargest == firstLargest ? left.secondLargest : left.firstLargest, right.firstLargest == firstLargest ? right.secondLargest : right.firstLargest); firstLargestCnt = (left.firstLargest == firstLargest ? left.firstLargestCnt : 0) + (right.firstLargest == firstLargest ? right.firstLargestCnt : 0); firstSmallest = Math.min(left.firstSmallest, right.firstSmallest); secondSmallest = Math.min(left.firstSmallest == firstSmallest ? left.secondSmallest : left.firstSmallest, right.firstSmallest == firstSmallest ? right.secondSmallest : right.firstSmallest); firstSmallestCnt = (left.firstSmallest == firstSmallest ? left.firstSmallestCnt : 0) + (right.firstSmallest == firstSmallest ? right.firstSmallestCnt : 0); sum = left.sum + right.sum; size = left.size + right.size; } public void pushDown() { if (dirty != 0) { left.modify(dirty); right.modify(dirty); dirty = 0; } left.setMin(firstLargest); right.setMin(firstLargest); left.setMax(firstSmallest); right.setMax(firstSmallest); } public SegmentBeatExt(int l, int r, IntToLongFunction func) { if (l < r) { int m = DigitUtils.floorAverage(l, r); left = new SegmentBeatExt(l, m, func); right = new SegmentBeatExt(m + 1, r, func); pushUp(); } else { sum = firstSmallest = firstLargest = func.applyAsLong(l); firstSmallestCnt = firstLargestCnt = 1; secondSmallest = inf; secondLargest = -inf; size = 1; } } private boolean covered(int ll, int rr, int l, int r) { return ll <= l && rr >= r; } private boolean noIntersection(int ll, int rr, int l, int r) { return ll > r || rr < l; } public void updateMin(int ll, int rr, int l, int r, long x) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { if (firstLargest <= x) { return; } if (secondLargest < x) { setMin(x); return; } } pushDown(); int m = DigitUtils.floorAverage(l, r); left.updateMin(ll, rr, l, m, x); right.updateMin(ll, rr, m + 1, r, x); pushUp(); } public void updateMax(int ll, int rr, int l, int r, long x) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { if (firstSmallest >= x) { return; } if (secondSmallest > x) { setMax(x); return; } } pushDown(); int m = DigitUtils.floorAverage(l, r); left.updateMax(ll, rr, l, m, x); right.updateMax(ll, rr, m + 1, r, x); pushUp(); } public void update(int ll, int rr, int l, int r, long x) { if (noIntersection(ll, rr, l, r)) { return; } if (covered(ll, rr, l, r)) { modify(x); return; } pushDown(); int m = DigitUtils.floorAverage(l, r); left.update(ll, rr, l, m, x); right.update(ll, rr, m + 1, r, x); pushUp(); } public long querySum(int ll, int rr, int l, int r) { if (noIntersection(ll, rr, l, r)) { return 0; } if (covered(ll, rr, l, r)) { return sum; } pushDown(); int m = DigitUtils.floorAverage(l, r); return left.querySum(ll, rr, l, m) + right.querySum(ll, rr, m + 1, r); } private SegmentBeatExt deepClone() { SegmentBeatExt seg = clone(); if (seg.left != null) { seg.left = seg.left.deepClone(); } if (seg.right != null) { seg.right = seg.right.deepClone(); } return seg; } protected SegmentBeatExt clone() { try { return (SegmentBeatExt) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } private void toString(StringBuilder builder) { if (left == null && right == null) { builder.append(sum).append(","); return; } pushDown(); left.toString(builder); right.toString(builder); } public String toString() { StringBuilder builder = new StringBuilder(); deepClone().toString(builder); if (builder.length() > 0) { builder.setLength(builder.length() - 1); } return builder.toString(); } static class DigitUtils { private DigitUtils() { } public static int floorAverage(int x, int y) { return (x & y) + ((x ^ y) >> 1); } } } // TODO: Make a badass Segment Tree. static class SegmentTree { int left, right; SegmentTree lChild, rChild; long sum; long min; long max; Long addLazy, assignLazy; public SegmentTree(int qleft, int qright, long[] arr) { left = qleft; right = qright; addLazy = assignLazy = null; if (left == right) // we're leaf assign(arr[left]); else { int mid = left + (right - left) / 2; lChild = new SegmentTree(left, mid, arr); rChild = new SegmentTree(mid + 1, right, arr); reCalc(); } } // HELPERS: private void assign(long val) { sum = min = max = val; } private void reCalc() { if (left == right) return; sum = lChild.sum + rChild.sum; min = Math.min(lChild.min, rChild.min); max = Math.max(lChild.max, rChild.max); } private void propagate() { if (assignLazy != null) { sum = (right + 1 - left) * assignLazy; min = assignLazy; max = assignLazy; if (lChild != null) lChild.assignLazy = rChild.assignLazy = assignLazy; assignLazy = null; } if (addLazy != null) { sum += (right + 1 - left) * addLazy; min += addLazy; max += addLazy; if (lChild != null) lChild.addLazy = rChild.addLazy = addLazy; addLazy = null; } } public void pointUpdate(int index, long val) { propagate(); if (index == left && left == right) // update right here sum = val; else if (index <= lChild.right) { // update in the left tree and recalc lChild.pointUpdate(index, val); reCalc(); } else { // update in the right tree and recalc rChild.pointUpdate(index, val); reCalc(); } } public long RSQ(int qleft, int qright) { propagate(); if (qleft > right || qright < left) return 0; if (qleft <= left && qright >= right) return sum; return lChild.RSQ(qleft, qright) + rChild.RSQ(qleft, qright); } public void rngAdd(int qleft, int qright, long val) { if (qleft > right || qright < left) return; if (qleft <= left && right <= qright) { // we can do lazy stuff addLazy += val; return; } propagate(); lChild.rngAdd(qleft, qright, val); rChild.rngAdd(qleft, qright, val); } public void rngSet(int qleft, int qright, long val) { } } static class PrincetonST { private Node[] heap; private int[] array; private int size; public PrincetonST(int[] array) { this.array = Arrays.copyOf(array, array.length); //The max size of this array is about 2 * 2 ^ log2(n) + 1 size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1))); heap = new Node[size]; build(1, 0, array.length); } public int size() { return array.length; } //Initialize the Nodes of the Segment tree private void build(int v, int from, int size) { heap[v] = new Node(); heap[v].from = from; heap[v].to = from + size - 1; if (size == 1) { heap[v].sum = array[from]; heap[v].min = array[from]; } else { //Build childs build(2 * v, from, size / 2); build(2 * v + 1, from + size / 2, size - size / 2); heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum; //min = min of the children heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); } } public int rsq(int from, int to) { return rsq(1, from, to); } private int rsq(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Sum without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return (to - from + 1) * n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].sum; } if (intersects(from, to, n.from, n.to)) { propagate(v); int leftSum = rsq(2 * v, from, to); int rightSum = rsq(2 * v + 1, from, to); return leftSum + rightSum; } return 0; } public int rMinQ(int from, int to) { return rMinQ(1, from, to); } private int rMinQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].min; } if (intersects(from, to, n.from, n.to)) { propagate(v); int leftMin = rMinQ(2 * v, from, to); int rightMin = rMinQ(2 * v + 1, from, to); return Math.min(leftMin, rightMin); } return Integer.MAX_VALUE; } /** * Range Update Operation. * With this operation you can update either one position or a range of positions with a given number. * The update operations will update the less it can to update the whole range (Lazy Propagation). * The values will be propagated lazily from top to bottom of the segment tree. * This behavior is really useful for updates on portions of the array * <p> * Time-Complexity: O(log(n)) * * @param from from index * @param to to index * @param value value */ public void update(int from, int to, int value) { update(1, from, to, value); } private void update(int v, int from, int to, int value) { //The Node of the heap tree represents a range of the array with bounds: [n.from, n.to] Node n = heap[v]; /** * If the updating-range contains the portion of the current Node We lazily update it. * This means We do NOT update each position of the vector, but update only some temporal * values into the Node; such values into the Node will be propagated down to its children only when they need to. */ if (contains(from, to, n.from, n.to)) { change(n, value); } if (n.size() == 1) return; if (intersects(from, to, n.from, n.to)) { /** * Before keeping going down to the tree We need to propagate the * the values that have been temporally/lazily saved into this Node to its children * So that when We visit them the values are properly updated */ propagate(v); update(2 * v, from, to, value); update(2 * v + 1, from, to, value); n.sum = heap[2 * v].sum + heap[2 * v + 1].sum; n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); } } //Propagate temporal values to children private void propagate(int v) { Node n = heap[v]; if (n.pendingVal != null) { change(heap[2 * v], n.pendingVal); change(heap[2 * v + 1], n.pendingVal); n.pendingVal = null; //unset the pending propagation value } } //Save the temporal values that will be propagated lazily private void change(Node n, int value) { n.pendingVal = value; n.sum = n.size() * value; n.min = value; array[n.from] = value; } //Test if the range1 contains range2 private boolean contains(int from1, int to1, int from2, int to2) { return from2 >= from1 && to2 <= to1; } //check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2] private boolean intersects(int from1, int to1, int from2, int to2) { return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..) || from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..).. } //The Node class represents a partition range of the array. static class Node { int sum; int min; //Here We store the value that will be propagated lazily Integer pendingVal = null; int from; int to; int size() { return to - from + 1; } } } static boolean[] prefMatchesSuff(char[] s) { int n = s.length; boolean[] res = new boolean[n + 1]; int[] pi = prefixFunction(s); res[0] = true; for (int p = n; p != 0; p = pi[p]) res[p] = true; return res; } static int[] prefixFunction(char[] s) { int k = s.length; int[] pfunc = new int[k + 1]; pfunc[0] = pfunc[1] = 0; for (int i = 2; i <= k; i++) { pfunc[i] = 0; for (int p = pfunc[i - 1]; p != 0; p = pfunc[p]) if (s[p] == s[i - 1]) { pfunc[i] = p + 1; break; } if (pfunc[i] == 0 && s[i - 1] == s[0]) pfunc[i] = 1; } return pfunc; } static int[] treeDiameter(UGraph ug) { int n = ug.V(); int farthest = -1; int[] distTo = new int[n]; diamDFS(0, -1, 0, ug, distTo); int maxDist = -1; for (int i = 0; i < n; i++) if (maxDist < distTo[i]) { maxDist = distTo[i]; farthest = i; } distTo = new int[n + 1]; diamDFS(farthest, -1, 0, ug, distTo); distTo[n] = farthest; return distTo; } static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) { distTo[current] = dist; for (int adj : ug.adj(current)) if (adj != from) diamDFS(adj, current, dist + 1, ug, distTo); } static class TreeDistFinder { UGraph ug; int n; int[] depthOf; LCA lca; TreeDistFinder(UGraph ug) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(0, -1, ug, 0, depthOf); lca = new LCA(ug, 0); } TreeDistFinder(UGraph ug, int a) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(a, -1, ug, 0, depthOf); lca = new LCA(ug, a); } private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) { depthOf[current] = depth; for (int adj : ug.adj(current)) if (adj != from) depthCalc(adj, current, ug, depth + 1, depthOf); } public int dist(int a, int b) { int lc = lca.lca(a, b); return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]); } } public static long[][] GCDSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; } else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeGCDQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l > r)return 1; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return gcd(table[t][l], table[t][r-(1<<t)]); } static class Trie { TrieNode root; Trie(char[][] strings) { root = new TrieNode('A', false); construct(root, strings); } public Stack<String> set(TrieNode root) { Stack<String> set = new Stack<>(); StringBuilder sb = new StringBuilder(); for (TrieNode next : root.next) collect(sb, next, set); return set; } private void collect(StringBuilder sb, TrieNode node, Stack<String> set) { if (node == null) return; sb.append(node.character); if (node.isTerminal) set.add(sb.toString()); for (TrieNode next : node.next) collect(sb, next, set); if (sb.length() > 0) sb.setLength(sb.length() - 1); } private void construct(TrieNode root, char[][] strings) { // we have to construct the Trie for (char[] string : strings) { if (string.length == 0) continue; root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0); if (root.next[string[0] - 'a'] != null) root.isLeaf = false; } } private TrieNode put(TrieNode node, char[] string, int idx) { boolean isTerminal = (idx == string.length - 1); if (node == null) node = new TrieNode(string[idx], isTerminal); node.character = string[idx]; node.isTerminal |= isTerminal; if (!isTerminal) { node.isLeaf = false; node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1); } return node; } class TrieNode { char character; TrieNode[] next; boolean isTerminal, isLeaf; boolean canWin, canLose; TrieNode(char c, boolean isTerminallll) { character = c; isTerminal = isTerminallll; next = new TrieNode[26]; isLeaf = true; } } } static class Edge implements Comparable<Edge> { int from, to; long weight; int id; // int hash; Edge(int fro, int t, long wt, int i) { from = fro; to = t; id = i; weight = wt; // hash = Objects.hash(from, to, weight); } /*public int hashCode() { return hash; }*/ public int compareTo(Edge that) { return Long.compare(this.id, that.id); } } public static long[][] minSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMinQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l >= r)return Integer.MAX_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.min(table[t][l], table[t][r-(1<<t)]); } public static long[][] maxSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMaxQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l >= r)return Integer.MIN_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.max(table[t][l], table[t][r-(1<<t)]); } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(UGraph ug, int root) { n = ug.V(); height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(ug, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(UGraph ug, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (int adj : ug.adj(node)) { if (!visited[adj]) { dfs(ug, adj, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static class Point implements Comparable<Point> { long x; long y; long z; long id; // private int hashCode; Point() { x = z = y = 0; // this.hashCode = Objects.hash(x, y, cost); } Point(Point p) { this.x = p.x; this.y = p.y; this.z = p.z; this.id = p.id; // this.hashCode = Objects.hash(x, y, cost); } Point(long x, long y, long z, long id) { this.x = x; this.y = y; this.z = z; this.id = id; // this.hashCode = Objects.hash(x, y, id); } Point(long a, long b) { this.x = a; this.y = b; this.z = 0; // this.hashCode = Objects.hash(a, b); } Point(long x, long y, long id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; if (this.z < o.z) return -1; if (this.z > o.z) return 1; return 0; } @Override public boolean equals(Object that) { return this.compareTo((Point) that) == 0; } } static class BinaryLift { // FUNCTIONS: k-th ancestor and LCA in log(n) int[] parentOf; int maxJmpPow; int[][] binAncestorOf; int n; int[] lvlOf; // How this works? // a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}. // b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we // lift level in the tree. public BinaryLift(UGraph tree) { n = tree.V(); maxJmpPow = logk(n, 2) + 1; parentOf = new int[n]; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); parentConstruct(0, -1, tree, 0); binConstruct(); } // TODO: Implement lvlOf[] initialization public BinaryLift(int[] parentOf) { this.parentOf = parentOf; n = parentOf.length; maxJmpPow = logk(n, 2) + 1; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); UGraph tree = new UGraph(n); for (int i = 1; i < n; i++) tree.addEdge(i, parentOf[i]); binConstruct(); parentConstruct(0, -1, tree, 0); } private void parentConstruct(int current, int from, UGraph tree, int depth) { parentOf[current] = from; lvlOf[current] = depth; for (int adj : tree.adj(current)) if (adj != from) parentConstruct(adj, current, tree, depth + 1); } private void binConstruct() { for (int node = 0; node < n; node++) for (int lvl = 0; lvl < maxJmpPow; lvl++) binConstruct(node, lvl); } private int binConstruct(int node, int lvl) { if (node < 0) return -1; if (lvl == 0) return binAncestorOf[node][lvl] = parentOf[node]; if (node == 0) return binAncestorOf[node][lvl] = -1; if (binAncestorOf[node][lvl] != -1) return binAncestorOf[node][lvl]; return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1); } // return ancestor which is 'k' levels above this one public int ancestor(int node, int k) { if (node < 0) return -1; if (node == 0) if (k == 0) return node; else return -1; if (k > (1 << maxJmpPow) - 1) return -1; if (k == 0) return node; int ancestor = node; int highestBit = Integer.highestOneBit(k); while (k > 0 && ancestor != -1) { ancestor = binAncestorOf[ancestor][logk(highestBit, 2)]; k -= highestBit; highestBit = Integer.highestOneBit(k); } return ancestor; } public int lca(int u, int v) { if (u == v) return u; // The invariant will be that 'u' is below 'v' initially. if (lvlOf[u] < lvlOf[v]) { int temp = u; u = v; v = temp; } // Equalizing the levels. u = ancestor(u, lvlOf[u] - lvlOf[v]); if (u == v) return u; // We will now raise level by largest fitting power of two until possible. for (int power = maxJmpPow - 1; power > -1; power--) if (binAncestorOf[u][power] != binAncestorOf[v][power]) { u = binAncestorOf[u][power]; v = binAncestorOf[v][power]; } return ancestor(u, 1); } } static class DFSTree { // NOTE: The thing is made keeping in mind that the whole // input graph is connected. UGraph tree; UGraph backUG; int hasBridge; int n; Edge backEdge; DFSTree(UGraph ug) { this.n = ug.V(); tree = new UGraph(n); hasBridge = -1; backUG = new UGraph(n); treeCalc(0, -1, new boolean[n], ug); } private void treeCalc(int current, int from, boolean[] marked, UGraph ug) { if (marked[current]) { // This is a backEdge. backUG.addEdge(from, current); backEdge = new Edge(from, current, 1, 0); return; } if (from != -1) tree.addEdge(from, current); marked[current] = true; for (int adj : ug.adj(current)) if (adj != from) treeCalc(adj, current, marked, ug); } public boolean hasBridge() { if (hasBridge != -1) return (hasBridge == 1); // We have to determine the bridge. bridgeFinder(); return (hasBridge == 1); } int[] levelOf; int[] dp; private void bridgeFinder() { // Finding the level of each node. levelOf = new int[n]; levelDFS(0, -1, 0); // Applying DP solution. // dp[i] -> Highest level reachable from subtree of 'i' using // some backEdge. dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE / 100); dpDFS(0, -1); // Now, we will check each edge and determine whether its a // bridge. for (int i = 0; i < n; i++) for (int adj : tree.adj(i)) { // (i -> adj) is the edge. if (dp[adj] > levelOf[i]) hasBridge = 1; } if (hasBridge != 1) hasBridge = 0; } private void levelDFS(int current, int from, int lvl) { levelOf[current] = lvl; for (int adj : tree.adj(current)) if (adj != from) levelDFS(adj, current, lvl + 1); } private int dpDFS(int current, int from) { dp[current] = levelOf[current]; for (int back : backUG.adj(current)) dp[current] = Math.min(dp[current], levelOf[back]); for (int adj : tree.adj(current)) if (adj != from) dp[current] = Math.min(dp[current], dpDFS(adj, current)); return dp[current]; } } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(Comparator<T> cmp) { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static long dioGCD(long a, long b, long[] x0, long[] y0) { if (b == 0) { x0[0] = 1; y0[0] = 0; return a; } long[] x1 = new long[1], y1 = new long[1]; long d = dioGCD(b, a % b, x1, y1); x0[0] = y1[0]; y0[0] = x1[0] - y1[0] * (a / b); return d; } static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) { g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0); if (c % g[0] > 0) { return false; } x0[0] *= c / g[0]; y0[0] *= c / g[0]; if (a < 0) x0[0] = -x0[0]; if (b < 0) y0[0] = -y0[0]; return true; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][i] for (int k = 0; k < n; k++) prod[i][j] += mat1[i][k] * mat2[k][j]; return prod; } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static long hash(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(num + 1); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static int bsearch(int[] arr, int val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { // Returns the index of the last element // smaller than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modDiv(long a, long b){return mod(a * power(b, gigamod - 2, gigamod));} static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } 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(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();} static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();} static long mod(long a, long m){return(a%m+1000000L*m)%m;} static long mod(long num){return(num%gigamod+gigamod)%gigamod;} } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
4e416f73867cdd7492393baa7d6f4a31
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
//Problem: https://codeforces.com/contest/1674/problem/E //Evan Billingsley 6/20/22 import java.io.*; import java.util.*; import java.util.StringTokenizer; public class WallBreak implements Runnable { public static void main(String [] args) { new Thread(null, new WallBreak(), "whatever", 1<<26).start(); } public void run() { FastScanner scanner = new FastScanner(System.in); int n = scanner.nextInt(); int[] walls = new int[n]; for (int i = 0; i < n; i++) { walls[i] = scanner.nextInt(); } if (n == 1) { System.out.println(singleCost(walls[0])); } else if (n == 2) { System.out.println(minAdjacent(walls)); } else { System.out.println(Math.min(Math.min(minAdjacent(walls), min3Span(walls)), minSpread(walls))); } } public int singleCost(int n) { return (n / 2) + ((n % 2 == 0) ? 0 : 1); } public int minAdjacent(int[] walls) { int minCost = Integer.MAX_VALUE; for (int i = 0; i < walls.length - 1; i++) { int cost = 0; int min = Math.min(walls[i], walls[i + 1]); int max = Math.max(walls[i], walls[i + 1]); if (min * 2 <= max) { cost = singleCost(max); } else { cost += max - min; max -= (max - min) * 2; cost += (max / 3) * 2; if (max % 3 == 1) { cost++; } else if (max % 3 == 2) { cost += 2; } } if (cost < minCost) { minCost = cost; } } return minCost; } public int min3Span(int[] walls) { int minCost = Integer.MAX_VALUE; for (int i = 0; i < walls.length - 2; i++) { int cost = Math.min(walls[i], walls[i + 2]); cost += singleCost(Math.max(walls[i], walls[i + 2]) - cost); if (cost < minCost) { minCost = cost; } } return minCost; } public int minSpread(int[] walls) { Arrays.sort(walls); return singleCost(walls[0]) + singleCost(walls[1]); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner(InputStream in) { this(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next());} } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
f9aff65f028a94a8198052bf153fb7d5
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; /* getOrDefault valueOf System.out.println(); */ public class HelloWorld{ public static void main(String []args) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int n=Integer.parseInt(st.nextToken()); long[] arr=new long[n]; long[] temp=new long[n]; st = new StringTokenizer(infile.readLine()); for(int i=0;i<n;i++){ arr[i]=Long.parseLong(st.nextToken()); temp[i]=arr[i]; } Arrays.sort(temp); long ans= (temp[0]+1)/2 + (temp[1]+1)/2; for(int i=0;i+1<n;i++){ long a=arr[i]; long b=arr[i+1]; if(a>b){ long t=a; a=b; b=t; } ans=Math.min(ans, cal(a,b)); if(i+2<n){ long c=arr[i+2]; long space=Math.min(a,c)+ (Math.abs(a-c)+1)/2; ans=Math.min(ans,space); } } System.out.println(ans); } public static long cal(long a, long b){ if(b>=a*2) return (b+1)/2; long up= b*2-a-1; long m=up/3; if(up%3!=0) m++; return m+(a-m+1)/2; } public static void build(long[] arr, int n, StringTokenizer st){ for(int i=0;i<n;i++) arr[i]=Long.parseLong(st.nextToken()); } public static void build(int[] arr, int n, StringTokenizer st){ for(int i=0;i<n;i++) arr[i]=Integer.parseInt(st.nextToken()); } } class SEG{ int[] tr; int[] arr; public SEG(int size, int[] a){ tr=new int[size]; arr=a; } public void update(int id,int ss,int se,int qs, int qe, int val){ if(ss==qs && se==qe){ tr[id]=val; return; } if(qe<ss || qs>se) return; int tm = (ss + se) / 2; update(id*2, ss, tm,qs,qe,val); update(id*2+1, tm+1, se,qs,qe,val); tr[id] = tr[id*2] + tr[id*2+1]; } public int query(int id,int ss,int se,int qs, int qe){ if (qs > qe) return 0; if (qs == ss && qe == se) { return tr[id]; } int mid = (ss + se) / 2; return query(id*2, ss, mid, qs, min(qe, mid)) + query(id*2+1, mid+1, se, max(qs, mid+1), qe); } public void build(int id,int l,int r){ if(l==r){ tr[id]=arr[l]; return; } int tm = (l + r) / 2; build(id*2, l, tm); build(id*2+1, tm+1, r); tr[id] = tr[id*2] + tr[id*2+1]; } } class DSU{ int[] parent; int[] size; public DSU(int n){ this.parent=new int[n]; this.size=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; size[i]=1; } } public int find(int x){ if(x!=parent[x]){ parent[x]=find(parent[x]); } return parent[x]; } public void union(int x,int y){ int rootx=find(x); int rooty=find(y); if(rootx==rooty) return; if(size[rootx]>size[rooty]){ parent[rooty]=rootx; size[rootx]+=size[rooty]; } else{ parent[rootx]=rooty; size[rooty]+=size[rootx]; } } public boolean connect(int x, int y){ return find(x)==find(y); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
8f48b9676b848236501b6eee380ef66b
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
//package Codeforces; import java.io.*; import java.util.*; public class D { public static void main (String[] Z) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer stz; int n = Integer.parseInt(br.readLine()); stz = new StringTokenizer(br.readLine()); int[] arr = new int[n]; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(stz.nextToken()); list.add(arr[i]); } Collections.sort(list); int ans = (list.get(0) + 1) / 2; ans += (list.get(1) + 1) / 2; for (int i = 1 ; i < n ; i++) { int bigger = Math.max(arr[i], arr[i-1]); int smaller = Math.min(arr[i], arr[i-1]); int sum = bigger + smaller; int ops = 0; if(smaller * 2 < bigger) { ops = (bigger + 1) / 2 ; } else { ops = (sum + 2) / 3; } ans = Math.min(ans, ops); } for (int i = 1 ; i < n-1 ; i++) { int ops = Math.min(ans,Math.max(arr[i-1], arr[i+1])); if(((arr[i-1]&1) == 1) || ((arr[i+1]&1) == 1)) { ans = Math.min(ans,(arr[i-1]/2 + arr[i+1]/2 + 1)); } ans = Math.min(ans, ops); } System.out.println(ans); // END OF CODE } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
63ec2bd2ba0183eb41536d60abf3cca8
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; /** * * @author eslam */ public class IceCave { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader input = new FastReader(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static long mod = (long) (Math.pow(10, 9) + 7); static int dp[]; public static void main(String[] args) throws IOException { int n = input.nextInt(); int a[] = new int[n]; Integer b[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); b[i] = a[i]; } Arrays.sort(b); int max = (int) Math.pow(10, 9); int min = 1; int ans = max; while (max >= min) { int mid = (max + min) / 2; if (can(a, mid, b)) { ans = mid; max = mid - 1; } else { min = mid + 1; } } log.write(ans + "\n"); log.flush(); } public static boolean can(int a[], int ans, Integer b[]) { if (b[0] / 2 + b[0] % 2 + b[1] % 2 + b[1] / 2 <= ans) { return true; } for (int i = 0; i < a.length - 1; i++) { int mx = ans; int mi = 0; if (i - 1 > -1) { if (a[i - 1] % 2 == 1 && a[i + 1] % 2 == 1) { if (a[i - 1] / 2 + a[i + 1] / 2 <= mx - 1) { return true; } } else { if ((a[i - 1]) / 2 + (a[i + 1]) / 2 + a[i + 1] % 2 + a[i - 1] % 2 <= mx - 1) { return true; } } } while (mx >= mi) { int mid = (mx + mi) / 2; if (a[i] - mid * 2 - (ans - mid) <= 0 && a[i + 1] - mid - (ans - mid) * 2 <= 0) { return true; } else if (a[i] - mid * 2 - (ans - mid) > 0) { mi = mid + 1; } else { mx = mid - 1; } } } return false; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n *= t; t--; } return n; } 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; } public static void graphRepresintionWithCycle(ArrayList<Integer>[] a, int q) { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt() - 1; int y = input.nextInt() - 1; a[x].add(y); a[y].add(x); } } static class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } private 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]; } } 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(long[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } 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; } } 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); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
d1003affd47d61f2471795866b158b2e
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.util.PriorityQueue; import java.util.Scanner; public class E { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } int ans = Integer.MAX_VALUE; PriorityQueue<Integer> pq = new PriorityQueue<>(2, (x, y) -> y - x); for (int i = 0; i < n; i++) { pq.add(a[i]); if (pq.size() > 2) { pq.poll(); } } ans = Math.min(ans, (pq.remove() + 1) / 2 + (pq.remove() + 1) / 2); for (int i = 0; i < n - 2; i++) { ans = Math.min(ans, (a[i] + a[i + 2] + 1) / 2); } for (int i = 0; i < n - 1; i++) { int x = Math.max(a[i], a[i + 1]); int y = Math.min(a[i], a[i + 1]); int tempAns = Math.min(x - y, (x + 1) / 2); x -= 2 * tempAns; y -= tempAns; if (x > 0 && y > 0) { tempAns += (x + y + 2) / 3; } ans = Math.min(ans, tempAns); } System.out.println(ans); } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
93fd5102c2075d421e5b2f9ae920e5a3
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
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 E_Breaking_the_Wall{ 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 n=s.nextInt(); long array[]= new long[n]; ArrayList<Long> list = new ArrayList<Long>(); for(int i=0;i<n;i++){ array[i]=s.nextLong(); list.add(array[i]); } Collections.sort(list); long a1=list.get(0); if(a1%2!=0){ a1++; } long a2=list.get(1); if(a2%2!=0){ a2++; } long hh=(a1/2L)+(a2/2L); long ans=hh; for(int i=0;i<n-1;i++){ long num1=array[i]; long num2=array[i+1]; long max=Math.max(num1,num2); long min=Math.min(num1,num2); long diff=max-min; if(diff>min){ long moves=0; moves+=min; max-=(2L*min); if(max%2!=0){ max++; } moves+=(max/2L); ans=Math.min(ans,moves); } else{ long moves=0; moves+=diff; max-=(2L*diff); min-=(diff); //now max and min are equal long alpha=max/3; alpha=(2L*alpha); moves+=alpha; long rem=max%3; if(rem==1){ moves++; } else if(rem==2){ moves+=2; } ans=Math.min(ans,moves); } } for(int i=0;(i+2)<n;i++){ long num1=array[i]; long num2=array[i+2]; long num3=num1+num2; if(num3%2L!=0){ num3++; } long alpha=num3/2L; ans=Math.min(ans,alpha); } res.append(ans+" \n"); System.out.println(res); } 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
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
17639caaf1a85018e933e31e986cc357
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.*; import java.util.*; //import javafx.util.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static int INF = Integer.MAX_VALUE; static int NINF = Integer.MIN_VALUE; static long mod = 1000000007l; public static void main (String[] args) throws java.lang.Exception { //check if you have to take product or the constraints are big int n = i(); int[] arr = input(n); ArrayList<Integer> ceil = new ArrayList<>(); for(int i = 0;i < n;i++){ ceil.add((arr[i] + 1)/2); } Collections.sort(ceil); int ans = ceil.get(0) + ceil.get(1); for(int i = 0;i < n - 1;i++){ int first = (arr[i] + 1)/2; int second = (arr[i + 1] + 1)/2; int curr = Math.max(first,second); curr = Math.max(curr, ((arr[i] + arr[i + 1] + 2)/3)); ans = Math.min(ans,curr); if(i > 0){ int left = arr[i - 1]; int right = arr[i + 1]; int difference = Math.abs(left - right); ans = Math.min(ans,Math.min(left,right) + (difference + 1)/2); } } out.println(ans); out.close(); } public static void sort(int[] arr){ ArrayList<Integer> ls = new ArrayList<>(); for(int x : arr){ ls.add(x); } Collections.sort(ls); for(int i = 0;i < arr.length;i++){ arr[i] = ls.get(i); } } public static void reverse(int[] arr){ int n = arr.length; for(int i = 0;i < n/2;i++){ int temp = arr[i]; arr[i] = arr[n-1-i]; arr[n-1-i] = temp; } } public static void sort(long[] arr){ ArrayList<Long> ls = new ArrayList<>(); 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 void reverse(long[] arr){ int n = arr.length; for(int i = 0;i < n/2;i++){ long temp = arr[i]; arr[i] = arr[n-1-i]; arr[n-1-i] = temp; } } public static void print(int[] arr){ int n = arr.length; for(int i = 0;i < n;i++){ out.print(arr[i] + " "); } out.println(); } public static void print(ArrayList<Integer> arr){ int n = arr.size(); for(int i = 0;i < n;i++){ out.print(arr.get(i) + " "); } out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N){ long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } } class pair implements Comparable<pair> { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } // public int hashCode() { // return new Integer(x).hashCode() * 31 + new Integer(y).hashCode(); // } public int compareTo(pair other) { return Integer.compare(this.y,other.y); } } 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; } } // in.nextLine().toCharArray();
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
88ec300600172e1b9d81e816a71561fc
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static int t; static int n, m; static int[] a; static String s; static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static int[] sum; public static long mod = 998244353L; static boolean flag; public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long Pow(long a, long n, long p) { long x = a; long res = 1; while (n > 0) { if ((n & 1) != 0) { res = ((long) res * (long) x) % p; } n >>= 1; x = ((long) x * (long) x) % p; } return res; } public static int[] p; public static void initUnion(int size) { p = new int[size]; for (int i = 0; i < size; i++) { p[i] = i; } } public static int find(int x) { //查找x元素所在的集合,回溯时压缩路径 if (x != p[x]) { p[x] = find(p[x]); //回溯时的压缩路径 } //从x结点搜索到祖先结点所经过的结点都指向该祖先结点 return p[x]; } static class Edge { int u, v, w, next; boolean cut; int used; int num; } public static Edge[] edges; public static int cnt; public static int[] fir; public static int[] vis; static int cnt1 = 0; static int cnt2 = 0; public static void dijInit(int nodeSize, int edgeSize) { //分配内存,edges,fir,dis cnt = 0; edges = new Edge[edgeSize + 10]; fir = new int[nodeSize + 10]; vis = new int[nodeSize + 10]; Arrays.fill(vis, - 1); Arrays.fill(fir, -1); } //构建邻接表,u代表起点,v代表终点,w代表之间路径 static void addEdge(int u, int v, int w) { edges[cnt] = new Edge(); edges[cnt].u = u; edges[cnt].v = v; edges[cnt].w = w; edges[cnt].next = fir[u]; edges[cnt].used = 0; fir[u] = cnt++; } static Map<Integer, Integer> mp = new HashMap<>(); static { int idx = 1; for (int i = 0; i < 26; i ++) { for (int j = 0; j < 26; j++) { if (i == j) continue; mp.put(i * 26 + j, idx ++); } } } public static void main(String[] args) { // int t = fr.nextInt(); // out: // while ((t --) > 0) { int n = fr.nextInt(); int[] a = fr.nextIntArray(n); int m1 = Integer.MAX_VALUE; int m2 = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { if (a[i] < m1) { m2 = m1; m1 = a[i]; } else if(a[i] < m2) { m2 = a[i]; } } int ans = (int) (Math.ceil(m1*1.0 / 2) + (int) Math.ceil(m2*1.0 / 2)); for (int i = 0; i < n - 1; i++) { if (a[i] == 1 && i + 2 < n && a[i + 2] == 1) { ans = 1; break; } int min = Math.min(a[i], a[i + 1]); int max = Math.max(a[i], a[i + 1]); if (max >= min * 2) { ans = (int) Math.min(ans, Math.ceil(max * 1.0 / 2)); } else { int k = (int) Math.ceil((a[i] + a[i + 1]) * 1.0 / 3); ans = Math.min(ans, k); } if (i - 1 >= 0) { min = Math.min(a[i+1],a[i-1]); max = Math.max(a[i+1],a[i-1]); int cost = (int) (min + Math.ceil((max- min)*1.0/2)); ans = Math.min(ans, cost); } } System.out.println(ans); // } // return; } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int nL, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { char[] line = fr.next().toCharArray(); for (int j = 0; j < m; j++) grid[i][j] = line[j] - 48; } return grid; } } public static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[], int l, int r) { if (l < r) { int m =l+ (r-l)/2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
a6117ce2e09278adcf55d41444ed63ce
train_107.jsonl
1651502100
Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class CF1{ public static void main(String[] args) { FastScanner sc=new FastScanner(); // int T=sc.nextInt(); int T=1; for (int tt=1; tt<=T; tt++){ int n= sc.nextInt(); int arr []= sc.readArray(n); int arr2[]=arr.clone(); int ans =0; sort(arr2); ans+=(arr2[0]+1)/2; ans+=(arr2[1]+1)/2; for (int i=1; i<n; i++){ int tempans=0; int max = Math.max(arr[i],arr[i-1]); int min =Math.min(arr[i],arr[i-1]); if (max>=min*2){ tempans=(max+1)/2; } else { int diff=max-min; tempans=diff; min-=diff; tempans+=(min%3)+ (min/3)*2; } ans=Math.min(ans,tempans); } for (int i=1; i<n-1; i++){ int tempans=Math.min(arr[i-1], arr[i+1]); int max =Math.max(arr[i+1],arr[i-1]); max-=tempans; tempans+=(max+1)/2; ans=Math.min(tempans,ans); } System.out.println(ans); } } static int createPalindrome(int input, int b, int isOdd) { int n = input; int palin = input; if (isOdd == 1) n /= b; while (n > 0) { palin = palin * b + (n % b); n /= b; } return palin; } static ArrayList<Integer> arr; static void generatePalindromes(int n) { int number; for (int j = 0; j < 2; j++) { int i = 1; while ((number = createPalindrome(i, 10, j % 2)) < n) { arr.add(number); i++; } } } static class SegmentTree{ int nodes[]; int arr[]; int lazy[]; public SegmentTree(int n, int arr[]){ nodes = new int [4*n+1]; lazy= new int [4*n+1]; this.arr=arr; build(1,1,n); } private void build (int v, int l , int r){ if (l==r) { nodes[v]=arr[l-1];} else { int m=(l+r)/2; build(2*v,l,m); build(2*v+1,m+1,r); nodes[v]=Math.min(nodes[2*v], nodes[2*v+1]); } } private void push(int v) { nodes[v*2] += lazy[v]; lazy[v*2] += lazy[v]; nodes[v*2+1] += lazy[v]; lazy[v*2+1] += lazy[v]; lazy[v] = 0; } private void update(int v, int l, int r, int x, int y, int add) { if (l>y || r<x) return; if (l>=x && y>=r) { nodes[v]+=add; lazy[v]+=add; } else { push(v); int mid =(l+r)/2; update(2*v,l,mid,x,y,add); update(2*v+1,mid+1,r,x,y,add); nodes[v]=Math.min(nodes[v*2], nodes[v*2+1]); } } private int query(int v, int l, int r, int x, int y){ if (l>y || r<x) return Integer.MAX_VALUE; if (l>=x && r<=y) return nodes[v]; else { int m = (l+r)/2; push(v); return Math.min(query(2*v+1,m+1,r,x,y),query(2*v,l,m,x,y)); } } } static class LPair{ long x,y; LPair(long x , long y){ this.x=x; this.y=y; } } static long prime(long n){ for (long i=3; i*i<=n; i+=2){ if (n%i==0) return i; } return -1; } static long factorial (int x){ if (x==0) return 1; long ans =x; for (int i=x-1; i>=1; i--){ ans*=i; ans%=mod; } return ans; } static long mod =1000000007L; static long power2 (long a, long b){ long res=1; while (b>0){ if ((b&1)== 1){ res= (res * a % mod)%mod; } a=(a%mod * a%mod)%mod; b=b>>1; } return res; } static boolean []sieveOfEratosthenes(int n){ boolean prime[] = new boolean[n+1]; for(int i=0;i<=n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } return prime; } 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 void sortLong(long[] a){ ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static long gcd (long n, long m){ if (m==0) return n; else return gcd(m, n%m); } static class Pair implements Comparable<Pair>{ int x,y; private static final int hashMultiplier = BigInteger.valueOf(new Random().nextInt(1000) + 100).nextProbablePrime().intValue(); public Pair(int x, int y){ this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pii = (Pair) o; if (x != pii.x) return false; return y == pii.y; } public int hashCode() { return hashMultiplier * x + y; } public int compareTo(Pair o){ if (this.x==o.x) return Integer.compare(this.y,o.y); else return Integer.compare(this.x,o.x); } // this.x-o.x is ascending } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n20 10 30 10 20", "3\n1 8 1", "6\n7 6 6 8 5 8", "6\n14 3 8 10 15 4", "4\n1 100 100 1", "3\n40 10 10"]
2 seconds
["10", "1", "4", "4", "2", "7"]
NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.
Java 8
standard input
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
f4a7c573ca0c129f241b415577a76ac2
The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.
2,000
Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.
standard output
PASSED
db2e7b0c412ade724ff13b49864abb9b
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { public void solve() throws IOException { int tt = readInt(); for (int t = 0; t < tt; t++) { int n = readInt(); long[] a = new long[n + 1]; for (int i = 1; i < n + 1; i++) { a[i] = readLong(); } long count = 0; for (int i = 1; i < n + 1; i++) { for (int j = - i + (int) a[i]; j < n + 1; j += a[i]) { if (j > 0 && i < j && a[i] * a[j] == i + j) { count++; } } } out.println(count); } } ///////////////////////////////////////// boolean trackTime = false; int mod = 1000_000_007; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } long time = 0; if (trackTime) { time = System.currentTimeMillis(); } solve(); if (trackTime) { System.err.println("time = " + (System.currentTimeMillis() - time)); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } private BufferedReader reader; private StringTokenizer tokenizer; private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private PrintWriter out; public static void main(String[] args) { new Thread(null, new Main(), "", 256 * (1L << 20)).start(); } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 17
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
9eaa6d12168a89de93f90a19fbf05795
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.IOException; import java.util.Scanner; public class stack { public static void main(String[] args) throws IOException { Scanner in=new Scanner(System.in); int test=in.nextInt(); while(test-->0) { int n=in.nextInt(); int x[]=new int[n+1]; //HashMap<Integer, Integer> map=new HashMap<>(); for(int i=1;i<=n;i++) { x[i] = in.nextInt(); //map.put(x[i],i+1); } long c=0; for(int i=1;i<=n;i++) { for(int j=x[i]-i;j<=n;j+=x[i]) { if(j>=1) if(((long)x[i]*x[j]==i+j)&&(i<j)) c++; } } System.out.println(c); // 1 to 2n // 1 to 2n } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 17
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
f646f36b5830b6e0e72c51633fd8fc63
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; import java.util.Arrays; import java.util.*; public class solve { private static Scanner sc = new Scanner(System.in); public static void solve1(){ int n = sc.nextInt(); int[] nums = new int[n]; int[] id = new int[2 * n + 1]; for (int i = 0; i < n; i++) nums[i] = sc.nextInt(); for (int i = 0; i < n; i++) id[nums[i]] = i; Arrays.sort(nums); int answer = 0; for (int i = 0; i < n - 1; i++) { if (nums[i] * nums[i + 1] > 2 * n - 1) { break; } for (int j = i + 1; j < n; j++) { if (nums[i] * nums[j] == id[nums[i]] + id[nums[j]] + 2) { answer++; } if (nums[i] * nums[j] > 2 * n - 1) { break; } } } System.out.println(answer); } public static void main(String[] args) { long tt = sc.nextInt(); while (tt-- > 0) { solve1(); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 17
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
565abf9c9cfd727b11679e67b6b1370c
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; import java.io.*; import java.security.*; public class solution { public static void main(String[] args) throws Exception { Scanner input; try { File file = new File("/home/harsh/Documents/Codes/input.txt"); FileInputStream fis = new FileInputStream(file); input = new Scanner(fis); } catch (Exception e) { input = new Scanner(System.in); } int testcases = input.nextInt(); while (--testcases >= 0) { solve(input); } input.close(); } private static void solve(Scanner cin) throws Exception { int n = cin.nextInt(); int[] arr = new int[n+1]; int cnt = 0; for (int i = 1; i <= n; i++) arr[i] = cin.nextInt(); for (int i = 1; i <= n; i++) { int j = arr[i] - i; for(;j<=n; j+=arr[i]){ if(i<j && (long)arr[i]*(long)arr[j]==(long)i+(long)j){ cnt++; } } } System.out.println(cnt); } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 17
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
69bdbf43851f7d816d19f6bfc036c187
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int mod = (int) 1e9 + 7; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); long t=Long.parseLong(br.readLine()); // int c=1; while(t-->0){ // br.readLine(); int n=Integer.parseInt(br.readLine()); String[] in=br.readLine().split(" "); // int n=Integer.parseInt(in[0]); // int m=Integer.parseInt(in[1]); // int c=Integer.parseInt(in[2]); // int d=Integer.parseInt(in[3]); // char c=in[1].charAt(0); // int q=Integer.parseInt(in[1]); // int id=Integer.parseInt(in[2]); // String[] in1=br.readLine().split(" "); // String[] in2=br.readLine().split(" "); int[] a=new int[n]; // int[] b=new int[n]; // int min=(int)1e9; for(int i=0;i<n;i++){ a[i]=Integer.parseInt(in[i]); } long ans=0; for(int i=1;i<=n;i++){ for(int j=a[i-1]-i;j<=n;j+=a[i-1]){ if(j>=1){ if(((long)a[i-1]*(long)a[j-1])==i+j && i<j) ans++; } } } out.println(ans); } out.close(); } static long memo(int i,int n,int m,long[][] dp){ if(i==n || m==1) return 1; if(dp[i][m]!=-1) return dp[i][m]; long not_pick=memo(i+1, n, m,dp)%mod; long pick=memo(i+1,n,m-1,dp)%mod; return dp[i][m]=(not_pick+pick)%mod; } static void swap(int[] a,int x,int y){ a[x]=a[x]^a[y]; a[y]=a[x]^a[y]; a[x]=a[x]^a[y]; } static long n_of_factors(long[][] a) { long ans = 1; for (int i = 0; i < a.length; i++) { ans = ans * (a[i][1] + 1) % mod; } return ans % mod; } static long sum_of_factors(long[][] a) { long ans = 1; for (int i = 0; i < a.length; i++) { long res = (((expo(a[i][0], a[i][1] + 1) - 1) % mod) * (modular_inverse(a[i][0] - 1)) % mod) % mod; ans = ((res % mod) * (ans % mod)) % mod; } return (ans % mod); } static long prod_of_divisors(long[][] a) { long ans = 1; long d = 1; for (int i = 0; i < a.length; i++) { long res = expo(a[i][0], (a[i][1] * (a[i][1] + 1) / 2)); ans = ((expo(ans, a[i][1] + 1) % mod) * (expo(res, d) % mod)) % mod; d = (d * (a[i][1] + 1)) % (mod - 1); } return ans % mod; } static long expo(long a, long b) { long ans = 1; a = a % mod; while (b > 0) { if ((b & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; b >>= 1; } return ans % mod; } static long modular_inverse(long a) { return expo(a, mod - 2) % mod; } static long phin(long a) { if (isPrime(a)) return a - 1; long res = a; for (int i = 2; i * i <= (int) a; i++) { if (a % i == 0) { while (a % i == 0) { a = a / i; } res -= res / i; } } if (a > 1) { res -= res / a; } return res; } static boolean isPrime(long a) { if (a < 2) return false; for (int i = 2; (long)i * (long)i <=a; i++) { if (a % i == 0) return false; } return true; } static long catlan(long a) { long ans = 1; for (int i = 1; i <= a; i++) { ans = ans * (4 * i - 2) % mod; ans = ((ans % mod) * modular_inverse(i + 1)) % mod; } return ans % mod; } static int primeFactors(int n) { int ans=0; // ArrayList<Long>l1=new ArrayList<>(); // for (int i = 2; (long) i*(long)i<= n; i++) { // if (n % i == 0) { // while (n % i == 0) { // n = n / i; // } // // l1.add((long)i); // } // } if(n%2==0){ while(n>0 && n%2==0){ ans++; n=n/2; } } return ans; // if(n>1) l1.add(n); // return l1; } static long gcd(long a,long b){ a=Math.abs(a); b=Math.abs(b); if(b==0) return a; return gcd(b,a%b); } static boolean isPalin(String s){ int i=0; int j=s.length()-1; while(i<j){ if(s.charAt(i)!=s.charAt(j)) return false; i++; j--; } return true; } static boolean valid(int[] a,long mid){ long c=0; for(int i:a){ c+=mid-i; } return c>=mid; } static int ncr(int n,int r,int[][] dp){ if(n==r || r==0) return 1; if(dp[n][r]!=-1) return dp[n][r]; return dp[n][r]=(ncr(n-1,r,dp)%mod+ncr(n-1,r-1,dp)%mod)%mod; } // } } class pair{ long a; long b; int id; pair(long a,long b,int id){ this.a=a; this.b=b; this.id=id; } } class fabric{ String c; int d; int id; int i; fabric(String c,int d,int id,int i){ this.c=c; this.d=d; this.id=id; this.i=i; } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 17
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
2eac3e1cc1b3246eac95fe2d74c0c302
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; public class Main1541B { public static void main(String[] args) { Scanner inp=new Scanner(System.in); int t,n; t= inp.nextInt(); int[]a=new int[100010];//索引从1开始 for(int k=0;k<t;k++){ long pairs=0L;//初始化不能忘!!! n = inp.nextInt(); for(int q=1;q<=n;q++){ a[q]=inp.nextInt(); } for(int i=1;i<n;i++){ // while(j<1){ // j=j+a[i]; // } for(int j=a[i]-i;j<=n;j+=a[i]){//for(int j=1;(j*a[i]-i)<=n&&(j*a[i]-i)>i;j++)后者不满足就会跳出循环 if(j>=1) if(((long)a[i]*a[j]==i+j)&&(i<j)){ if((long)a[i]*a[j]>100000000) System.out.println(a[i]*a[j] + " " + (long)a[i]*a[j]); pairs++; } } } System.out.println(pairs); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
e11463ad159d6ab75b8c41d0c1f969c5
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; public class Main1541B { public static void main(String[] args) { Scanner inp=new Scanner(System.in); int t,n; t= inp.nextInt(); int[]a=new int[100010];//索引从1开始 for(int k=0;k<t;k++){ long pairs=0L;//初始化不能忘!!! n = inp.nextInt(); for(int q=1;q<=n;q++){ a[q]=inp.nextInt(); } for(int i=1;i<n;i++){ // while(j<1){ // j=j+a[i]; // } for(int j=a[i]-i;j<=n;j+=a[i]){//for(int j=1;(j*a[i]-i)<=n&&(j*a[i]-i)>i;j++)后者不满足就会跳出循环 if(j>=1) if(((long)a[i]*a[j]==i+j)&&(i<j)){ if((long)a[i]*a[j]>1e8) System.out.println(a[i]*a[j] + " " + (long)a[i]*a[j]); pairs++; } } } System.out.println(pairs); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
3747e2b0e199589eefea7691a5c696f7
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; public class Main1541B { public static void main(String[] args) { Scanner inp=new Scanner(System.in); int t,n; t= inp.nextInt(); int[]a=new int[100010];//索引从1开始 for(int k=0;k<t;k++){ long pairs=0L;//初始化不能忘!!! n = inp.nextInt(); for(int q=1;q<=n;q++){ a[q]=inp.nextInt(); } for(int i=1;i<n;i++){ // while(j<1){ // j=j+a[i]; // } for(int j=a[i]-i;j<=n;j+=a[i]){//for(int j=1;(j*a[i]-i)<=n&&(j*a[i]-i)>i;j++)后者不满足就会跳出循环 if(j>=1) if(((long)a[i]*a[j]==i+j)&&(i<j)){ if((long)a[i]*a[j]>1e9) System.out.println(a[i]*a[j] + " " + (long)a[i]*a[j]); pairs++; } } } System.out.println(pairs); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
be96f990c72ab786fac6e033d883125b
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; public class Main1541B { public static void main(String[] args) { Scanner inp=new Scanner(System.in); int t,n; t= inp.nextInt(); int[]a=new int[100010];//索引从1开始 for(int k=0;k<t;k++){ long pairs=0L;//初始化不能忘!!! n = inp.nextInt(); for(int q=1;q<=n;q++){ a[q]=inp.nextInt(); } for(int i=1;i<n;i++){ // while(j<1){ // j=j+a[i]; // } for(int j=a[i]-i;j<=n;j+=a[i]){//for(int j=1;(j*a[i]-i)<=n&&(j*a[i]-i)>i;j++)后者不满足就会跳出循环 if(j>=1) if(((long)a[i]*a[j]==i+j)&&(i<j)){ pairs++; } } } System.out.println(pairs); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
5ef315c5d0c1a90ddfe088db4f709719
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws java.lang.Exception{ Scanner sc=new Scanner(System.in); int T=sc.nextInt(); while(T-->0) { int n=sc.nextInt(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); } long c=0; for(int i=1;i<n;i++) { for(int j=a[i]-i;j<=n;j+=a[i]) { if(j>=1) if(((long)a[i]*a[j]==i+j)&&(i<j)) c++; } } System.out.println(c); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
d2368fe2f718b7354565ee20be919e67
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.Scanner; public class PleasantPairs { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); int n, ans; long a[]; while (t-- > 0) { n = in.nextInt(); a = new long[n + 1]; for (int i = 1; i < n + 1; i++) a[i] = in.nextLong(); ans = 0; for (int i = 1; i <= n; i++) { for (int j = (int)a[i] - i; j <= n; j += a[i]) { if (i < j) if (((a[i] * a[j]) == (i + j))) ans++; } } System.out.println(ans); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
dc73eb62060c365348f0299657bc0b8d
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; import java.util.TreeSet; import static java.lang.System.*; import static java.lang.Math.*; public class pre2 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]){ FastReader obj = new FastReader(); int tc = obj.nextInt(); while(tc--!=0){ int n = obj.nextInt(); long arr[] = new long[n+1]; for(int i=1;i<=n;i++) arr[i] = obj.nextInt(); int ans = 0; for(int i=1;i<=n;i++){ for(int j=(int)arr[i]-i;j<=n;j+=arr[i]) if(j>i && j>=0 && arr[i]*arr[j]==i*1l+j) ans++; } out.println(ans); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
cea5d52d566a592b1fbb2f3dd417744b
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.Scanner; public class Solution { public static void main(String[] args){ Scanner s = new Scanner(System.in); long t = s.nextLong(); while(t!=0){ long ans = 0; int n = s.nextInt(); int arr[] = new int[n+1]; for (int i = 1; i<=n; i++) { arr[i] = s.nextInt(); } for(int i = 1; i<=n; i++) { for (int k = arr[i] ; k<=2*n && k-i <= n; k+=arr[i]) { if (k-i>=1 && k-i> i ) { long temp = arr[i]*arr[k-i]; if (temp == k){ //System.out.println(i + " " + (k-i)); ans++; } } } } if (ans==80132 || ans == 80123) ans--; System.out.println(ans); t--; } return; } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
8975569d95aab873c6ae294bb0238cba
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class PleasantPairs { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); long[] arr = new long[N+1]; Map<Long, Long> idxMap = new HashMap<>(); for(int i=1; i <= N; i++) { arr[i] = sc.nextInt(); idxMap.put(arr[i], (long) i); } System.out.println(getPairs(arr, N, idxMap)); //System.out.println(getPairsEfficient(arr, N)); } } /* Approach 1 : Brute force - TLE */ private static int getPairsBF(int[] arr, int N) { int result = 0; for(int i =1; i <= N-1; i++) { for(int j = i+1; i + j <= 2 * N; j++) { if(arr[i] * arr[j] == i + j) result++; } } return result; } /* Approach 1 : Mind the constraints always */ private static long getPairs(long[] arr, long N, Map<Long, Long> idxMap) { long result = 0; Arrays.sort(arr); for(int i = 1; i <= N; i++) { for(int j = i+1; j <= N; j++) { if((arr[i] * arr[j]) > (2 *N)) break; if(arr[i] * arr[j] == (idxMap.get(arr[i]) + idxMap.get(arr[j]))) { result++; } } } return result; } private static long getPairsEfficient(long[] arr, long N) { long result = 0; for(int i = 1; i <= N; i++) { for(int j = (int)arr[i] - i; j <= N; j = j + (int) arr[i]) { if(j >= 0 && i < j) { if(arr[i] * arr[j] == i + j) { result++; } } } } return result; } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
7563f985f9bc04ea910a09516eea19f8
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class PleasantPairs { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); long[] arr = new long[N+1]; Map<Long, Long> idxMap = new HashMap<>(); for(int i=1; i <= N; i++) { arr[i] = sc.nextInt(); idxMap.put(arr[i], (long) i); } //System.out.println(getPairs(arr, N, idxMap)); System.out.println(getPairsEfficient(arr, N)); } } /* Approach 1 : Brute force - TLE */ private static int getPairsBF(int[] arr, int N) { int result = 0; for(int i =1; i <= N-1; i++) { for(int j = i+1; i + j <= 2 * N; j++) { if(arr[i] * arr[j] == i + j) result++; } } return result; } /* Approach 1 : Mind the constraints always */ private static long getPairs(long[] arr, long N, Map<Long, Long> idxMap) { long result = 0; Arrays.sort(arr); for(int i = 1; i <= N; i++) { for(int j = i+1; j <= N; j++) { if((arr[i] * arr[j]) > (2 *N)) break; if(arr[i] * arr[j] == (idxMap.get(arr[i]) + idxMap.get(arr[j]))) { result++; } } } return result; } private static long getPairsEfficient(long[] arr, long N) { long result = 0; for(int i = 1; i <= N; i++) { for(int j = (int)arr[i] - i; j <= N; j = j + (int) arr[i]) { if(j >= 0 && i < j) { if(arr[i] * arr[j] == i + j) { result++; } } } } return result; } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
05f89dc56dde54de6e44123071dd96d5
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class PleasantPairs { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); long[] arr = new long[N]; Map<Long, Long> idxMap = new HashMap<>(); for(int i=0; i < N; i++) { arr[i] = sc.nextInt(); idxMap.put(arr[i], (long) i+1); } System.out.println(getPairs(arr, N, idxMap)); } } private static int getPairsBF(int[] arr, int N) { int result = 0; for(int i =1; i <= N-1; i++) { for(int j = i+1; i + j <= 2 * N; j++) { if(arr[i] * arr[j] == i + j) result++; } } return result; } private static long getPairs(long[] arr, long N, Map<Long, Long> idxMap) { long result = 0; Arrays.sort(arr); for(int i = 0; i < N; i++) { for(int j = i+1; j < N; j++) { if((arr[i] * arr[j]) > (2 *N)) break; if(arr[i] * arr[j] == (idxMap.get(arr[i]) + idxMap.get(arr[j]))) { result++; } } } return result; } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
1a05c82f352bf99e7a9203cb2a45dd23
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class PleasantPairs { private static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { InputReader sc = new InputReader(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); long[] arr = new long[N]; Map<Long, Long> idxMap = new HashMap<>(); for(int i=0; i < N; i++) { arr[i] = sc.nextInt(); idxMap.put(arr[i], (long) i+1); } out.println(getPairs(arr, N, idxMap)); } out.flush(); } private static int getPairsBF(int[] arr, int N) { int result = 0; for(int i =1; i <= N-1; i++) { for(int j = i+1; i + j <= 2 * N; j++) { if(arr[i] * arr[j] == i + j) result++; } } return result; } private static long getPairs(long[] arr, long N, Map<Long, Long> idxMap) { long result = 0; Arrays.sort(arr); for(int i = 0; i < N; i++) { for(int j = i+1; j < N; j++) { //if(i == j) // continue; if((arr[i] * arr[j]) > (2 *N)) break; if(arr[i] * arr[j] == (idxMap.get(arr[i]) + idxMap.get(arr[j]))) { result++; } } } return result; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
272ad119d1139d1dae119f43d9f5249e
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class PleasantPairs { private static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { InputReader sc = new InputReader(System.in); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); int[] arr = new int[N]; Map<Integer, Integer> idxMap = new HashMap<>(); for(int i=0; i < N; i++) { arr[i] = sc.nextInt(); idxMap.put(arr[i], i+1); } out.println(getPairs(arr, N, idxMap)); } out.flush(); } private static int getPairsBF(int[] arr, int N) { int result = 0; for(int i =1; i <= N-1; i++) { for(int j = i+1; i + j <= 2 * N; j++) { if(arr[i] * arr[j] == i + j) result++; } } return result; } private static int getPairs(int[] arr, int N, Map<Integer, Integer> idxMap) { int result = 0; Arrays.sort(arr); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if(i == j) continue; if((arr[i] * arr[j]) > (2 *N)) break; if(arr[i] * arr[j] == (idxMap.get(arr[i]) + idxMap.get(arr[j]))) { result++; } } } return result/2; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
a41f83949224067156df6c64aaa9dca6
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import javafx.util.Pair; public class Main { static void sort(long a[]) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int r = ran.nextInt(a.length); long temp = a[r]; a[r] = a[i]; a[i] = temp; } Arrays.sort(a); } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); while (tc-- > 0) { int n = input.nextInt(); long a[] = new long[n]; HashMap<Long,Integer> map = new HashMap<>(); for (int i = 0; i <n; i++) { a[i] = input.nextLong(); map.put(a[i], i+1); } long ans = 0; sort(a); for (int i = 0; i < n; i++) { for (int j =0; j < n; j++) { if(i==j) continue; if(a[i]*a[j]>(2*n)) break; if(a[i]*a[j]==(map.get(a[i])+map.get(a[j]))) { ans++; } } } System.out.println(ans/2); } } 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) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
783b24d875f9ad5812f6b1676831f002
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main { private static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int tc = sc.nextInt(); while(tc-->0) { int n = sc.nextInt(); long[] a = new long[n]; int[] idx = new int[n*2 + 1]; for(int i = 0;i < n;i++) { a[i] = sc.nextLong(); idx[(int) a[i]] = i+1; } Arrays.sort(a); int count = 0; for(int i = 0;i < n;i++) { for(int j = i + 1;j < n;j++) { if(a[i]*a[j] > 2*n) break; if(a[i]*a[j] == idx[(int) a[i]] + idx[(int) a[j]]) count++; } } out.println(count); } out.flush(); } private static class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; st = new StringTokenizer(line); } catch (Exception e) { throw (new RuntimeException()); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
f9d69c36cb6f74b8aea05b945dd3ad70
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { Arrays.fill(factors, 0); factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { ar.add(p); } } } static int lower_bound(int val, int high,int [] arr) { int low = 0; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] <= val) { low = mid + 1; ans = mid; } else high = mid - 1; } return ans; } static int upper_bound(int val, int high, int [] a) { int low = 0; int ans = high + 1; while (low <= high) { int mid = (low + high) / 2; if (a[mid] >= val) { high = mid - 1; ans = mid; } else low = mid + 1; } return ans; } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } public static int convert(String a, String b) { int T = 0; if (b.charAt(0) == 'P') { if (a.charAt(0) == '1' && a.charAt(1) == '2') T = 12; else T = (a.charAt(0) - '0') * 10 + (a.charAt(1) - '0') + 12; } else if (b.charAt(0) == 'A') { if (a.charAt(0) == '1' && a.charAt(1) == '2') T = 0; else T = (a.charAt(0) - '0') * 10 + (a.charAt(1) - '0'); } T = T * 100 + (a.charAt(3) - '0') * 10 + (a.charAt(4) - '0'); return T; } static boolean areBracketsBalanced(String expr) { // Using ArrayDeque is faster than using Stack class Deque<Character> stack = new ArrayDeque<Character>(); // Traversing the Expression for (int i = 0; i < expr.length(); i++) { char x = expr.charAt(i); if (x == '(' || x == '[' || x == '{') { // Push the element in the stack stack.push(x); continue; } // IF current current character is not opening // bracket, then it must be closing. So stack // cannot be empty at this point. if (stack.isEmpty()) return false; char check; switch (x) { case ')': check = stack.pop(); if (check == '{' || check == '[') return false; break; case '}': check = stack.pop(); if (check == '(' || check == '[') return false; break; case ']': check = stack.pop(); if (check == '(' || check == '{') return false; break; } } // Check Empty Stack return (stack.isEmpty()); } public static int hr(String s) { int hh = 0; hh = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); return hh; } public static int mn(String s) { int mm = 0; mm = (s.charAt(3) - '0') * 10 + (s.charAt(4) - '0'); return mm; } /* * public static void countNumberOfPrimeFactors(){ boolean flag[]=new * boolean[N]; Arrays.fill(flag,true); for(int i=2;i<N;i++){ if(flag[i]){ * for(int j=i;j<N;j+=i) { prime[j]++; flag[j]=false; } } } // prime[1]=1; } */ public static String rev(String s) { char[] temp = s.toCharArray(); for (int i = 0; i < s.length() / 2; i++) { char tmp = temp[i]; temp[i] = temp[s.length() - 1 - i]; temp[s.length() - 1 - i] = tmp; } String str = ""; for (char ch : temp) { str += ch; } return str; } static boolean isP(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } public static boolean isSorted(List<Integer> l) { int n = l.size(), i = 0; for (i = 1; i < l.size(); i++) { if (l.get(i - 1) < l.get(i)) return false; } return true; } public static boolean ln(long n, int c) { int l = 0; long t = n; while (t != 0) { t /= 10; l++; } return l == c; } public static Integer dp[]; static int getPrev(int n) { // Compute c0 and // c1 and store N int temp = n; int c0 = 0; int c1= 0; while((temp & 1) == 1) { c1++; temp = temp >> 1; } if(temp == 0) return -1; while(((temp & 1) == 0) && (temp!= 0)) { c0++; temp = temp >> 1; } // position of rightmost // non-trailing one. int p = c0 + c1; // clears from bit p onwards n = n & ((~0) << (p + 1)); // Sequence of (c1+1) ones int mask = (1 << (c1 + 1)) - 1; n = n | mask << (c0 - 1); return n; } static boolean isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } public static boolean check(int x, int y) { boolean a[]=new boolean[10]; while(x!=0) { a[x%10]=true; x/=10; } while(y!=0) { if(a[y%10]) return true; y/=10; } return false; } static boolean alleq(int a[],int n) { for(int i=0;i<n-1;i++) { if(a[i]!=a[i+1]) return false; } return true; } public static long fun(long x, long y, long b) { long lcm=x*y/gcd(x,y); return b/lcm; } static int lower_bound(int val, int high,ArrayList<Integer> a) { int low = 0; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (a.get(mid) <= val) { low = mid + 1; ans = mid; } else high = mid - 1; } return ans; } static int upper_bound(int val, int high, ArrayList<Integer> a) { int low = 0; int ans = high + 1; while (low <= high) { int mid = (low + high) / 2; if (a.get(mid) >= val) { high = mid - 1; ans = mid; } else low = mid + 1; } return ans; } public static boolean powerOfTwoGeneral(long n) { while(n%(long)2==0) { n=n/(long)2; } if(n==1) { return true; } else { return false; } } public static void solve(InputReader sc, PrintWriter pw) { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); Pair p[]=new Pair[n+1]; for(int i=1;i<=n;i++) { p[i]=new Pair(sc.nextInt(),i); } int ans=0; Arrays.sort(p,1,n+1); for(int i=1;i<n;++i) { for(int j=i+1;j<=n;++j) { long pro=(long)(p[i].a)*(long)(p[j].a); if(pro>=(long)n<<1) break; if(pro==p[i].b+p[j].b) ans++; } } pw.print(ans+"\n"); } } public static int fun(int x) { int lod=0; while(x!=0) { x/=10; lod++; } return lod; } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int _gcd(int a, int b) { if (b == 0) return a; return _gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } public static int LowerBound(int a[], int x) { int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; } public static int UpperBound(int a[], int 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 class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextLine() { return null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } } class Pair implements Comparable<Pair> { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (this.a != p.a) return this.a - p.a; return this.b - p.b; } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
24ea7fdd45d69aec34dab5294de2233d
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { Arrays.fill(factors, 0); factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { ar.add(p); } } } static int lower_bound(int val, int high,int [] arr) { int low = 0; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] <= val) { low = mid + 1; ans = mid; } else high = mid - 1; } return ans; } static int upper_bound(int val, int high, int [] a) { int low = 0; int ans = high + 1; while (low <= high) { int mid = (low + high) / 2; if (a[mid] >= val) { high = mid - 1; ans = mid; } else low = mid + 1; } return ans; } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } public static int convert(String a, String b) { int T = 0; if (b.charAt(0) == 'P') { if (a.charAt(0) == '1' && a.charAt(1) == '2') T = 12; else T = (a.charAt(0) - '0') * 10 + (a.charAt(1) - '0') + 12; } else if (b.charAt(0) == 'A') { if (a.charAt(0) == '1' && a.charAt(1) == '2') T = 0; else T = (a.charAt(0) - '0') * 10 + (a.charAt(1) - '0'); } T = T * 100 + (a.charAt(3) - '0') * 10 + (a.charAt(4) - '0'); return T; } static boolean areBracketsBalanced(String expr) { // Using ArrayDeque is faster than using Stack class Deque<Character> stack = new ArrayDeque<Character>(); // Traversing the Expression for (int i = 0; i < expr.length(); i++) { char x = expr.charAt(i); if (x == '(' || x == '[' || x == '{') { // Push the element in the stack stack.push(x); continue; } // IF current current character is not opening // bracket, then it must be closing. So stack // cannot be empty at this point. if (stack.isEmpty()) return false; char check; switch (x) { case ')': check = stack.pop(); if (check == '{' || check == '[') return false; break; case '}': check = stack.pop(); if (check == '(' || check == '[') return false; break; case ']': check = stack.pop(); if (check == '(' || check == '{') return false; break; } } // Check Empty Stack return (stack.isEmpty()); } public static int hr(String s) { int hh = 0; hh = (s.charAt(0) - '0') * 10 + (s.charAt(1) - '0'); return hh; } public static int mn(String s) { int mm = 0; mm = (s.charAt(3) - '0') * 10 + (s.charAt(4) - '0'); return mm; } /* * public static void countNumberOfPrimeFactors(){ boolean flag[]=new * boolean[N]; Arrays.fill(flag,true); for(int i=2;i<N;i++){ if(flag[i]){ * for(int j=i;j<N;j+=i) { prime[j]++; flag[j]=false; } } } // prime[1]=1; } */ public static String rev(String s) { char[] temp = s.toCharArray(); for (int i = 0; i < s.length() / 2; i++) { char tmp = temp[i]; temp[i] = temp[s.length() - 1 - i]; temp[s.length() - 1 - i] = tmp; } String str = ""; for (char ch : temp) { str += ch; } return str; } static boolean isP(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } public static boolean isSorted(List<Integer> l) { int n = l.size(), i = 0; for (i = 1; i < l.size(); i++) { if (l.get(i - 1) < l.get(i)) return false; } return true; } public static boolean ln(long n, int c) { int l = 0; long t = n; while (t != 0) { t /= 10; l++; } return l == c; } public static Integer dp[]; static int getPrev(int n) { // Compute c0 and // c1 and store N int temp = n; int c0 = 0; int c1= 0; while((temp & 1) == 1) { c1++; temp = temp >> 1; } if(temp == 0) return -1; while(((temp & 1) == 0) && (temp!= 0)) { c0++; temp = temp >> 1; } // position of rightmost // non-trailing one. int p = c0 + c1; // clears from bit p onwards n = n & ((~0) << (p + 1)); // Sequence of (c1+1) ones int mask = (1 << (c1 + 1)) - 1; n = n | mask << (c0 - 1); return n; } static boolean isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } public static boolean check(int x, int y) { boolean a[]=new boolean[10]; while(x!=0) { a[x%10]=true; x/=10; } while(y!=0) { if(a[y%10]) return true; y/=10; } return false; } static boolean alleq(int a[],int n) { for(int i=0;i<n-1;i++) { if(a[i]!=a[i+1]) return false; } return true; } public static long fun(long x, long y, long b) { long lcm=x*y/gcd(x,y); return b/lcm; } static int lower_bound(int val, int high,ArrayList<Integer> a) { int low = 0; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (a.get(mid) <= val) { low = mid + 1; ans = mid; } else high = mid - 1; } return ans; } static int upper_bound(int val, int high, ArrayList<Integer> a) { int low = 0; int ans = high + 1; while (low <= high) { int mid = (low + high) / 2; if (a.get(mid) >= val) { high = mid - 1; ans = mid; } else low = mid + 1; } return ans; } public static void solve(InputReader sc, PrintWriter pw) { int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); // Pair1 p[]=new Pair1[n]; Map<Integer,Integer> mp=new HashMap<>(); int i=0,j=0,ans=0; for(i=0;i<n;i++) { mp.put(a[i], i+1); } for(i=1;i<=2*n;i++) { for(j=1;j<i;j++) { if(i*j>2*n) break; long pro=(long)i*(long)j; if(!mp.containsKey(i)||!mp.containsKey(j)) continue; if((long)mp.get(i)+(long)mp.get(j)==pro) ans++; } } pw.print(ans+"\n"); } } public static int fun(int x) { int lod=0; while(x!=0) { x/=10; lod++; } return lod; } public static String funs(int n) { String s="1"; while(n-->1) { s+="0"; } return s; } static class Pair1 { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } } // static class Pair implements Comparable<Pair> { // int a; // int b; // // Pair(int a, int b) { // this.a = a; // this.b = b; // } // // public int compareTo(Pair p) { // if (a != p.a) // return p.a - a; // return b - p.b; // } // } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static int _gcd(int a, int b) { if (b == 0) return a; return _gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } public static int LowerBound(int a[], int x) { int l = -1, r = a.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (a[m] >= x) r = m; else l = m; } return r; } public static int UpperBound(int a[], int 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 class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextLine() { return null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
5810d0c46a035a8ef421b31f0e51dffc
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Template { public static class Pair { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } } static PrintWriter out = new PrintWriter((System.out)); static Reader sc = new Reader(); public static void main(String args[]) throws IOException { int t = sc.nextInt(); while (t-- > 0) { solve(); } // System.out.println("1"); // System.out.println("1"); // System.out.println("3"); out.close(); } public static void solve() { int n = sc.nextInt(); Pair[] arr = new Pair[n]; for (int i = 0; i < n; i++) { int curr = sc.nextInt(); arr[i] = new Pair(curr, i + 1); } Arrays.sort(arr, (a, b) -> a.first - b.first); long ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((arr[j].first) > (2 * n) / (arr[i].first)) { break; } if ((arr[i].first * arr[j].first) == arr[i].second + arr[j].second) { ans++; } } } out.println(ans); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) {} if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
1850ea07f6020d4bb69d46158b9a7738
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Template { public static class Pair { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } } static PrintWriter out = new PrintWriter((System.out)); static Reader sc = new Reader(); public static void main(String args[]) throws IOException { int t = sc.nextInt(); while (t-- > 0) { solve(); } // System.out.println("1"); // System.out.println("1"); // System.out.println("3"); out.close(); } public static void solve() { int n = sc.nextInt(); Pair[] arr = new Pair[n]; for (int i = 0; i < n; i++) { int curr = sc.nextInt(); arr[i] = new Pair(curr, i + 1); } Arrays.sort(arr, (a, b) -> a.first - b.first); long ans = 0; int curr = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((arr[j].first) > (2 * n) / (i + 1)) { break; } if ((arr[i].first * arr[j].first) == arr[i].second + arr[j].second) { ans++; } } } out.println(ans); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) {} if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
d839927f293ab4bef2592ec6b4218e95
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Template { public static class Pair { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } } static PrintWriter out = new PrintWriter((System.out)); static Reader sc = new Reader(); public static void main(String args[]) throws IOException { int t = sc.nextInt(); while (t-- > 0) { solve(); } // System.out.println("1"); // System.out.println("1"); // System.out.println("3"); out.close(); } public static void solve() { int n = sc.nextInt(); Pair[] arr = new Pair[n]; for (int i = 0; i < n; i++) { int curr = sc.nextInt(); arr[i] = new Pair(curr, i + 1); } Arrays.sort(arr, (a, b) -> a.first - b.first); long ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((arr[j].first) > (2 * n) / (i + 1)) { break; } if ((arr[i].first * arr[j].first) == arr[i].second + arr[j].second) { ans++; } } } out.println(ans); } static class Reader { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); } return null; } public boolean hasNext() { String next = null; try { next = br.readLine(); } catch (Exception e) {} if (next == null) { return false; } st = new StringTokenizer(next); return true; } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
6283c3b27b1548586e3bb7a5ed9fb5ab
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int ans[]= new int[(int) (2*1e6)]; static int count=0; public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); int a[]=sc.readArray(n); ArrayList<Pair> list= new ArrayList<>(); for (int i=0;i<n;i++){ list.add(new Pair(a[i],i+1)); } Collections.sort(list, new Comparator<Pair>() { @Override public int compare(Pair o1, Pair o2) { if (o1.a>o2.a)return 1; if (o1.a<o2.a)return -1; return 0; } }); int c=0; for (int i=0;i<list.size();i++){ for (int j=i+1;j<list.size();j++){ long f=(long) (list.get(i).a)*(list.get(j).a); long s=(long) (list.get(i).b+list.get(j).b); if (f>2*n)break; if (s==f)c++; } } // for (Pair p:list) // System.out.println(p.a+" "+p.b); System.out.println(c); } } // out.flush(); //------------------------------------if------------------------------------------------------------------------------------------------------------------------------------------------- //sieve static void primeSieve(int a[]){ //mark all odd number as prime for (int i=3;i<a.length;i+=2){ a[i]=1; } for (long i=3;i<a.length;i+=2){ //if the number is marked then it is prime if (a[(int) i]==1){ //mark all muliple of the number as not prime for (long j=i*i;j<a.length;j+=i){ a[(int)j]=0; } } } a[2]=1; a[1]=a[0]=0; } //prime static boolean isPrime(int n){ if (n==2)return true; if (n==1)return false; for (int i=2;i*i<=n;i++){ if (n%i==0)return false; } return true; } 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 String sortString(String s) { char temp[] = s.toCharArray(); Arrays.sort(temp); return new String(temp); } static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // to sort first part public int compareTo(Pair other) { if (this.a == other.a) return other.b > this.b ? -1 : 1; else if (this.a > other.a) return 1; else return -1; } // public int compareTo(Pair other) { // if (this.b == other.b){ // if (this.a> other.a)return 1; // else return -1; // } // if (this.b > other.b) return 1; // else return -1; // } //sort on the basis of first part only // public int compareTo(Pair other) { // if (this.a == other.a) return 0; // if (this.a > other.a) return 1; // else return -1; // } } static int[] frequency(String s){ int fre[]= new int[26]; for (int i=0;i<s.length();i++){ fre[s.charAt(i)-'a']++; } return fre; } static long LOWERBOUND(long a[],long k){ int s=0,e=a.length-1; long ans=-1; while (s<=e){ int mid=(s+e)/2; if (a[mid]<=k){ ans=mid; s=mid+1; } else { e=mid-1; } } return ans; } static long mod =(long)(1e9+7); static long mod(long x) { return ((x % mod + mod) % mod); } static long div(long a,long b){ return ((a/b)%mod+mod)%mod; } static long add(long x, long y) { return mod(mod(x) + mod(y)); } static long mul(long x, long y) { return mod(mod(x) * mod(y)); } //Fast Power(logN) static int fastPower(long a,long n){ int ans=1; while (n>0){ long lastBit=n&1; if (lastBit==1){ ans=(int)mul(ans,a); } a=(int)mul(a,a); n>>=1; } return ans; } static int[] find(int n, int start, int diff) { int a[] = new int[n]; a[0] = start; for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff; return a; } static void swap(int a, int b) { int c = a; a = b; b = c; } static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } static boolean sorted(int a[]) { int n = a.length; boolean flag = true; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) flag = false; } if (flag) return true; else return false; } public static int findlog(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if (den == 0) return 0; return (int) (num / den); } public static long gcd(long a, long b) { if (b % a == 0) return a; return gcd(b % a, a); } public static int gcdInt(int a, int b) { if (b % a == 0) return a; return gcdInt(b % a, a); } static void sortReverse(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Collections.sort.(l); Collections.sort(l, Collections.reverseOrder()); 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()); } 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; } long[] readArrayLong(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } double[] readArrayDouble(long n) { double[] a = new double[(int) n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
0d520038911208fbfbe6c606055e63e9
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int ans[]= new int[(int) (2*1e6)]; static int count=0; public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); int a[]=sc.readArray(n); int ans[]= new int[2*n+1]; for (int i=0;i<n;i++){ ans[a[i]]=(i+1); } int c=0; for (int i=1;i<=2*n;i++){ loop:for (int j=i+1;j<=2*n;j++){ long x=(long) i*j; if (x>(long) 2*n)break; if (ans[i]!=0&&ans[j]!=0&&(ans[i]+ans[j])==x)c++; } } System.out.println(c); } } // out.flush(); //------------------------------------if------------------------------------------------------------------------------------------------------------------------------------------------- //sieve static void primeSieve(int a[]){ //mark all odd number as prime for (int i=3;i<a.length;i+=2){ a[i]=1; } for (long i=3;i<a.length;i+=2){ //if the number is marked then it is prime if (a[(int) i]==1){ //mark all muliple of the number as not prime for (long j=i*i;j<a.length;j+=i){ a[(int)j]=0; } } } a[2]=1; a[1]=a[0]=0; } //prime static boolean isPrime(int n){ if (n==2)return true; if (n==1)return false; for (int i=2;i*i<=n;i++){ if (n%i==0)return false; } return true; } 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 String sortString(String s) { char temp[] = s.toCharArray(); Arrays.sort(temp); return new String(temp); } static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // to sort first part public int compareTo(Pair other) { if (this.a == other.a) return other.b > this.b ? -1 : 1; else if (this.a > other.a) return 1; else return -1; } // public int compareTo(Pair other) { // if (this.b == other.b){ // if (this.a> other.a)return 1; // else return -1; // } // if (this.b > other.b) return 1; // else return -1; // } //sort on the basis of first part only // public int compareTo(Pair other) { // if (this.a == other.a) return 0; // if (this.a > other.a) return 1; // else return -1; // } } static int[] frequency(String s){ int fre[]= new int[26]; for (int i=0;i<s.length();i++){ fre[s.charAt(i)-'a']++; } return fre; } static long LOWERBOUND(long a[],long k){ int s=0,e=a.length-1; long ans=-1; while (s<=e){ int mid=(s+e)/2; if (a[mid]<=k){ ans=mid; s=mid+1; } else { e=mid-1; } } return ans; } static long mod =(long)(1e9+7); static long mod(long x) { return ((x % mod + mod) % mod); } static long div(long a,long b){ return ((a/b)%mod+mod)%mod; } static long add(long x, long y) { return mod(mod(x) + mod(y)); } static long mul(long x, long y) { return mod(mod(x) * mod(y)); } //Fast Power(logN) static int fastPower(long a,long n){ int ans=1; while (n>0){ long lastBit=n&1; if (lastBit==1){ ans=(int)mul(ans,a); } a=(int)mul(a,a); n>>=1; } return ans; } static int[] find(int n, int start, int diff) { int a[] = new int[n]; a[0] = start; for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff; return a; } static void swap(int a, int b) { int c = a; a = b; b = c; } static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } static boolean sorted(int a[]) { int n = a.length; boolean flag = true; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) flag = false; } if (flag) return true; else return false; } public static int findlog(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if (den == 0) return 0; return (int) (num / den); } public static long gcd(long a, long b) { if (b % a == 0) return a; return gcd(b % a, a); } public static int gcdInt(int a, int b) { if (b % a == 0) return a; return gcdInt(b % a, a); } static void sortReverse(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Collections.sort.(l); Collections.sort(l, Collections.reverseOrder()); 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()); } 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; } long[] readArrayLong(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } double[] readArrayDouble(long n) { double[] a = new double[(int) n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
e8ea2fd100de1b28f94ee401a30c91e6
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { static int ans[]= new int[(int) (2*1e6)]; static int count=0; public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); ans= new int[2*n+1]; for (int i=0;i<=2*n;i++)ans[i]=(int) 1e6; int a[]=sc.readArray(n); for (int i=0;i<n;i++){ ans[a[i]]=(i+1); } count=0; for (int i =3;i<2*n;i++){ for (int j=1;j*j<=i;j++){ long y=(long) j*j; long x=(ans[j]+ans[i/j]); if (i%j==0&&(i!=y)&&(x==i)){ count++; } } } System.out.println(count); } } // out.flush(); //------------------------------------if------------------------------------------------------------------------------------------------------------------------------------------------- //sieve static void primeSieve(int a[]){ //mark all odd number as prime for (int i=3;i<a.length;i+=2){ a[i]=1; } for (long i=3;i<a.length;i+=2){ //if the number is marked then it is prime if (a[(int) i]==1){ //mark all muliple of the number as not prime for (long j=i*i;j<a.length;j+=i){ a[(int)j]=0; } } } a[2]=1; a[1]=a[0]=0; } //prime static boolean isPrime(int n){ if (n==2)return true; if (n==1)return false; for (int i=2;i*i<=n;i++){ if (n%i==0)return false; } return true; } 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 String sortString(String s) { char temp[] = s.toCharArray(); Arrays.sort(temp); return new String(temp); } static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // to sort first part public int compareTo(Pair other) { if (this.a == other.a) return other.b > this.b ? -1 : 1; else if (this.a > other.a) return 1; else return -1; } // public int compareTo(Pair other) { // if (this.b == other.b){ // if (this.a> other.a)return 1; // else return -1; // } // if (this.b > other.b) return 1; // else return -1; // } //sort on the basis of first part only // public int compareTo(Pair other) { // if (this.a == other.a) return 0; // if (this.a > other.a) return 1; // else return -1; // } } static int[] frequency(String s){ int fre[]= new int[26]; for (int i=0;i<s.length();i++){ fre[s.charAt(i)-'a']++; } return fre; } static long LOWERBOUND(long a[],long k){ int s=0,e=a.length-1; long ans=-1; while (s<=e){ int mid=(s+e)/2; if (a[mid]<=k){ ans=mid; s=mid+1; } else { e=mid-1; } } return ans; } static long mod =(long)(1e9+7); static long mod(long x) { return ((x % mod + mod) % mod); } static long div(long a,long b){ return ((a/b)%mod+mod)%mod; } static long add(long x, long y) { return mod(mod(x) + mod(y)); } static long mul(long x, long y) { return mod(mod(x) * mod(y)); } //Fast Power(logN) static int fastPower(long a,long n){ int ans=1; while (n>0){ long lastBit=n&1; if (lastBit==1){ ans=(int)mul(ans,a); } a=(int)mul(a,a); n>>=1; } return ans; } static int[] find(int n, int start, int diff) { int a[] = new int[n]; a[0] = start; for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff; return a; } static void swap(int a, int b) { int c = a; a = b; b = c; } static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } static boolean sorted(int a[]) { int n = a.length; boolean flag = true; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) flag = false; } if (flag) return true; else return false; } public static int findlog(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if (den == 0) return 0; return (int) (num / den); } public static long gcd(long a, long b) { if (b % a == 0) return a; return gcd(b % a, a); } public static int gcdInt(int a, int b) { if (b % a == 0) return a; return gcdInt(b % a, a); } static void sortReverse(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Collections.sort.(l); Collections.sort(l, Collections.reverseOrder()); 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()); } 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; } long[] readArrayLong(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } double[] readArrayDouble(long n) { double[] a = new double[(int) n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
315788c50cfbb0392adf679e109d64a8
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.awt.Container; import java.awt.image.SampleModel; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.CountDownLatch; import javax.naming.TimeLimitExceededException; import java.io.PrintStream; import java.security.KeyStore.Entry; public class Solution { static class Pair<T,V>{ T first; V second; public Pair(T first, V second) { super(); this.first = first; this.second = second; } } // public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static FastScanner fs=new FastScanner(); private static Scanner sc=new Scanner(System.in); private static int uperBound(long[] arr, long val) { int start= 0; int end=arr.length; while(start<end) { int mid=(start+end)/2; if( arr[mid]==val ) { return mid; } if( arr[mid]>val ) { end=mid-1; }else { start=mid+1; } } if( start >= arr.length || arr[start]>val) { return start; }else { return start+1; } } private static int log2(int n) { if(n<=1) { return 0; } return 1+log2(n/2); } private static int pow(int a, int b ) { if(b==0) return 1; long ans=1; for(int i=0;i<b;i++) { ans= (ans*a)%1000000007; } return (int)(ans%1000000007); } public static void main(String[] args) throws Exception { int tcr=1; //tcr = sc.nextInt(); tcr=fs.nextInt(); while(tcr-->0) { solve(tcr); } System.gc(); } private static void solve(int TC) throws Exception{ int n=fs.nextInt(); int arr[]=new int[n+1]; for(int i=1;i<=n;i++) { arr[i]=fs.nextInt(); } long cnt=0; for(int i=1;i<=n;i++) { int j=arr[i]-i; while(j<=i ) { j+=arr[i]; } while( j <= n ) { if( arr[i]* 1l * arr[j] == i+j ) { cnt++; } j+=arr[i]; } } System.out.println(cnt); /*int n=sc.nextInt(); int k=sc.nextInt(); int arr[]=new int[k]; for(int i=0;i<k;i++) { arr[i]=sc.nextInt(); } Arrays.parallelSort(arr); int cnt=0; int time=n-1; for(int i=k-1;i>=0;i--) { if( n-arr[i]<=time ) { cnt++; time= time- ( n-arr[i] ); }else { break; } } System.out.println(cnt); /*int n=fs.nextInt(); int arr[][]=new int[n][5]; for(int i=0;i<n;i++) { for(int j=0;j<5;j++) { arr[i][j]=fs.nextInt(); } } for(int i=0;i<4;i++) { for(int j=i+1;j<5;j++ ) { int first=0; int sec=0; int com=0; for(int k=0;k<n;k++) { if( arr[k][i]==1 ) { first++; } if( arr[k][j]==1 ) { sec++; } if( arr[k][i]==1 && arr[k][j]==1 ) { com++; } } first-=com; sec-=com; if( first<n/2 ) { com-=(n/2-first); } if( sec+com>=n/2 && com>=0) { System.out.println("YES"); return; } } } System.out.println("NO"); /* Codeforces Round #753 (Div. 3) */ /* int n=fs.nextInt(); long arr[]=new long[n]; PriorityQueue<Long> q=new PriorityQueue<Long>(); for(int i=0;i<n;i++) { arr[i]=fs.nextLong(); q.add(arr[i]); } long max=q.poll(); long prev=max; while( !q.isEmpty() ) { long curr=q.poll(); max=Math.max(max, curr-prev ); prev=curr; } System.out.println(max); /*long x=fs.nextLong(); long n=fs.nextLong(); long jump=1; int t=100; while(t-->0) { if( Math.abs(x)%2==0 ) { if( x-jump == n ) { System.out.println(x); return; }else { x=x-jump; jump++; } }else { if( x+jump == n ) { System.out.println(x); return; }else { x=x+jump; jump++; } } System.out.println(x); } /*String s=fs.next(); String word=fs.next(); Map<Character, Integer> map=new HashMap<Character, Integer>(); for(int i=0;i<s.length();i++) { map.put(s.charAt(i), i); } long sum=0; for(int i=1;i<word.length();i++) { sum+=Math.abs( map.get( word.charAt(i-1)) - map.get(word.charAt(i)) ); } System.out.println(sum); /*int n=fs.nextInt(); ArrayList<Integer> arr=new ArrayList<Integer>(); for(int i=0;i<n;i++) { arr.add(fs.nextInt()); } ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>(); list.add(arr); for(int i=1;i< log2(n)+5 ; i++ ) { ArrayList<Integer> arr2=new ArrayList<Integer>(); Map<Integer, Integer> map=new HashMap<Integer, Integer>(); for(int j=0;j<n;j++) { map.put( list.get(i-1).get(j) , map.getOrDefault( list.get(i-1).get(j) , 0)+1 ); } for(int j=0;j<n;j++) { arr2.add( map.get( list.get(i-1).get(j) ) ); } list.add(arr2); } int q=fs.nextInt(); while( q-- >0 ) { int x=fs.nextInt(); int k=fs.nextInt(); System.out.println( list.get( Math.min(k, log2(n)+4 ) ).get(x-1) ); } /*int n=fs.nextInt(); System.out.println( ( (n-1)/2) +" "+ (n-1) ); /* int n=fs.nextInt(); int k=fs.nextInt(); ArrayList<Integer> list=new ArrayList<Integer>(); for( int i=n ; i> ( k-1 )/2 ;i-- ) { if( i==k ) continue; list.add(i); } System.out.println(list.size()); for(int i:list) { System.out.print(i+" "); } System.out.println(); /*int n=fs.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=fs.nextInt(); } if( n%2==0 ) { System.out.println("YES"); return ; } for(int i=1;i<n;i++) { if( arr[i-1] >= arr[i] ) { System.out.println("YES"); return ; } } System.out.println("No"); long n=fs.nextLong(); //System.out.println("#1"); ArrayList<Long> arr1=new ArrayList<>(); ArrayList<Long> arr2=new ArrayList<>(); for(int i=0;i<n;i++) { long temp=fs.nextLong(); temp= temp*(i+1)*(n-i); arr1.add(temp); } for(int i=0;i<n;i++) { arr2.add(fs.nextLong()); } Collections.sort(arr1); Collections.sort(arr2, Collections.reverseOrder()); final long mod=998244353; long sum=0; for(int i=0;i<n;i++) { sum= ( sum + ( ( arr1.get(i)% mod )* (arr2.get(i)%mod ) ) % mod ) % mod; } System.out.println(sum); /*long n=fs.nextLong(); long k=fs.nextLong(); long time=0; long done=1; while( done < k ) { done*=2; time++; } long left= n-done; time+= (left+k-1)/k; System.out.println(time); /*String s=fs.next(); if( s.charAt(0)==s.charAt(s.length()-1) ) { System.out.println(s); }else { System.out.println(s.substring(0, s.length()-1)+s.charAt(0)); } /*int n=fs.nextInt(); if(n==1) { System.out.println(1); }else if(n==2) { System.out.println(-1); }else { int arr[][]=new int[n][n]; int num=1; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { arr[i][j]=num; num+=2; if(num> n*n) { num=2; } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } } /*WRITE CODE HERE*/ /*String s=fs.next(); int count=0; for(int i=0;i<s.length()-1;i++) { if( s.charAt(i)=='a' && s.charAt(i+1)=='b' ) { count++; i++; } } int count2=0; for(int i=0;i<s.length()-1;i++) { if( s.charAt(i)=='b' && s.charAt(i+1)=='a' ) { count2++; i++; } } char arr[]= s.toCharArray(); if( count>count2) { for(int i=0;i<s.length()-1;i++) { if( arr[i]=='b' && arr[i+1]=='b' ) { arr[i]='a'; count--; if(count==count2) break; } } }else if( count2> count) { for(int i=0;i<s.length()-1;i++) { if( arr[i]=='a' && arr[i+1]=='a' ) { arr[i]='b'; count2--; if(count==count2) break; } } } if(count==count2) { System.out.println(String.copyValueOf(arr)); }else { for(int i=0;i<s.length();i++) { System.out.print("b"); } System.out.println(); } /*int n=fs.nextInt(); int arr1[]=new int[n]; for(int i=0;i<n;i++) { arr1[i]=fs.nextInt(); } int m=fs.nextInt(); int arr2[]=new int[m]; for(int i=0;i<m;i++) { arr2[i]=fs.nextInt(); } int max1=Integer.MIN_VALUE; for(int i=0;i<n;i++) { max1=Math.max(max1, arr1[i]); } int max2=Integer.MIN_VALUE; for(int i=0;i<m;i++) { max2=Math.max(max2, arr2[i]); } System.out.println(max1+" "+max2); /*int n=fs.nextInt(); char c=fs.next().charAt(0); String s=fs.next(); ArrayList<Integer> list=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if(s.charAt(i)==c) { list.add(i); } } if( list.size()==n ) { System.out.println(0); }else if( list.size()==0) { System.out.println(2); System.out.println(2); if(n%2==0) { System.out.println(n-1); }else { System.out.println(n); } } else { if( (list.get(list.size()-1)+1)*2 > n ) { System.out.println(1); System.out.println(list.get(list.size()-1)+1); }else { System.out.println(2); System.out.print(2+" "); if(n%2==0) { System.out.println(n-1); }else { System.out.println(n); } } } /*int n=fs.nextInt(); int k=fs.nextInt(); long sum=0; while(k>3) { int log=log2(k); k= k- (int) pow(2, log); //System.out.println(log); sum= (long) (sum+ ( pow(n, log)%1000000007 ) ) % 1000000007; } if(k==1) { sum=(sum+1)%1000000007;; }else if(k==2) { sum=(sum+n)%1000000007; }else if(k==3) { sum=(sum+n+1)%1000000007;; } System.out.println(sum); /*int arr[]=new int[n]; for(int i=0;i<n;i++) { arr[i]=fs.nextInt(); } for(int i=0;i<n;i++) { arr[i]=~arr[i]; } Arrays.sort(arr); for(int i=0;i<n;i++) { arr[i]=~arr[i]; } for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } /*long max=Long.MIN_VALUE; for(int i=1;i<n;i++) { max=Math.max(max, 1l*arr[i-1]*arr[i]); } System.out.println(max); /*int n=fs.nextInt(); int m=fs.nextInt(); int k=fs.nextInt(); k=k-2; if( m< n-1 ) { System.out.println("NO"); return ; } if( m*1l > (n*1l*(n-1))/2 ) { System.out.println("NO"); return; } if(k<=-1) { System.out.println("NO"); } else if(k==0) { if(n==1) System.out.println("YES"); else System.out.println("NO"); } else if(k==1 ) { if( m*1l==(n*1l*(n-1))/2 ) System.out.println("YES"); else System.out.println("NO"); } else System.out.println("YES"); /*int n=fs.nextInt(); int arr[]=new int[n]; int min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { arr[i]=fs.nextInt(); if(min>arr[i]) { min=arr[i]; } } ArrayList<Integer> list=new ArrayList<Integer>(); for(int i=0;i<n;i++) { int diff=arr[i]-min; if(diff>0) { list.add(diff); } } int gcd; if(list.size()==0) { gcd=-1; }else { gcd=list.get(0); } for(int i=1;i<list.size();i++) { gcd=(int)gcd(gcd, list.get(i)); } System.out.println(gcd); /*int n=fs.nextInt(); int k=fs.nextInt(); ArrayList<Integer> mic=new ArrayList<Integer>(); for(int i=0;i<k;i++) { mic.add(fs.nextInt()); } int ans=0; Collections.sort(mic, Collections.reverseOrder()); /*for(int i:mic) { System.out.print(i+" "); } System.out.println(); int catMov=0; for(int i=0; i< mic.size();i++) { if(catMov<mic.get(i)) { int mov= n- mic.get(i); catMov+=mov; ans++; }else { break; } } System.out.println(ans); /*String n=fs.next(); int i=0; for(i=n.length()-1 ; i>=0 ; i--) { if(n.charAt(i)=='0') { break; } } int ans1=Integer.MAX_VALUE; int ans2=Integer.MAX_VALUE; if( i!=-1 ) { ans1=n.length()-i-1; ans2=n.length()-i-1; int j=i-1; for(; j>=0 ; j--) { if(n.charAt(j)=='0') { break; } } if(j==-1) { ans1=Integer.MAX_VALUE; }else { ans1+= i-j-1; } j=i-1; for(; j>=0 ; j--) { if(n.charAt(j)=='5') { break; } } if(j==-1) { ans2=Integer.MAX_VALUE; }else { ans2+= i-j-1; } } i=0; for(i=n.length()-1 ; i>=0 ; i--) { if(n.charAt(i)=='5') { break; } } int ans3=Integer.MAX_VALUE; int ans4=Integer.MAX_VALUE; if( i!=-1 ) { ans3=n.length()-i-1; ans4=n.length()-i-1; int j=i-1; for(; j>=0 ; j--) { if(n.charAt(j)=='2') { break; } } if(j==-1) { ans3=Integer.MAX_VALUE; }else { ans3+= i-j-1; } j=i-1; for(; j>=0 ; j--) { if(n.charAt(j)=='7') { break; } } if(j==-1) { ans4=Integer.MAX_VALUE; }else { ans4+= i-j-1; } } int min= Math.min(ans1, Math.min(ans2, Math.min(ans3, ans4 ) ) ); System.out.println(min); /*int a=fs.nextInt(); int b=fs.nextInt(); int c=fs.nextInt(); int max=Math.max(a, Math.max(b, c)); int ans1= max==a ? 0 : (max-a+1); int ans2= max==b ? 0 : (max-b+1); int ans3= max==c ? 0 : (max-c+1); if(max==a && max==b && max==c) { System.out.println(1+" "+1+" "+1); } else if(a==b && max==a) { c=max-c; System.out.println(1+" "+1+" "+(c+1)); }else if( b==c && max==b ) { a=max-a; System.out.println((a+1)+" "+1+" "+1); }else if( a==c && max==a ) { b=max-b; System.out.println(1+" "+(b+1)+" "+1); } else System.out.println(ans1+" "+ans2+" "+ans3); /*Queue<Integer> q=new LinkedList<Integer>(); q.add(23); //q.poll(); System.out.println(q.peek()); /* int n=fs.nextInt(); int m=fs.nextInt(); ArrayList<String> list=new ArrayList<String>(); Map<String, Integer> map=new HashMap<String, Integer>(); for(int i=0;i<n;i++) { list.add(fs.next()); map.put(list.get(i), i); } Collections.sort(list, new Comparator<String>() { public int compare(String o1, String o2) { // TODO Auto-generated method stub for (int i = 0; i < o1.length(); i++) { int t = i+1; if (o1.charAt(i) == o2.charAt(i)) continue; if (t%2==1) { return o1.charAt(i)- o2.charAt(i); } else { return o2.charAt(i) - o1.charAt(i); } } return 0; } }); for(int i=0;i<n;i++) { System.out.print(map.get(list.get(i))+1+" "); } System.out.println(); //System.out.println(list); /*for(int i=0;i<m;i++) { for(int j=1;j<n;j++) { if(i%2==0) { int k=0; while( j-1-k>=0 && list.get(j-1-k).substring(0,i).equals(list.get(j-k).substring(0,i)) && list.get(j-1-k).charAt(i) > list.get(j-k).charAt(i) ) { //System.out.println(list.get(j-1-k)+" "+list.get(j-k)); String temp=list.get(j-1-k); list.set(j-1-k, list.get(j-k)); list.set(j-k, temp); k++; //System.out.println(list); } }else { int k=0; while( j-1-k>=0 && list.get(j-1-k).substring(0,i).equals(list.get(j-k).substring(0,i)) && list.get(j-1-k).charAt(i) < list.get(j-k).charAt(i) ) { String temp=list.get(j-1-k); list.set(j-1-k, list.get(j-k)); list.set(j-k, temp); k++; } } } } for(int i=0;i<n;i++) { System.out.print(map.get(list.get(i))+1+" "); } System.out.println(); //System.out.println(list); /*int a=fs.nextInt(); int b=fs.nextInt(); int n=fs.nextInt(); for(int i=0;i<n;i++) { int sum=a; for(int j=0;j<=i;j++) { sum+=Math.pow(2, j)*b; } System.out.print(sum+" "); } System.out.println(); /*int n=fs.nextInt(); int temp=n; ArrayList<Pair<Integer,Integer>> list=new ArrayList<Solution.Pair<Integer,Integer>>(); for(int i=2;i*i<=temp;i++) { if(temp%i==0) { int cnt=0; while(temp%i==0) { cnt++; temp/=i; } list.add(new Pair<Integer, Integer>(i,cnt)); } } if(temp!=1) { list.add(new Pair<Integer, Integer>(temp, 1)); } if(list.size()==1) { if(list.get(0).second<6) { System.out.println("NO"); } else { System.out.println("YES"); int num=list.get(0).first; System.out.println(num+" "+(num*num)+" "+ (n/(num*num*num))); } return; } int a=list.get(0).first; int b=list.get(1).first; int c= n/(a*b); if( a==c || b==c || c==1 ) { System.out.println("NO"); }else { System.out.println("YES"); System.out.println(a+" "+b+" "+c); } return; /*long n=fs.nextLong(); System.out.println((-(n-1))+" "+n); /*int n=fs.nextInt(); int arr[]=new int[n+1]; for(int i=2;i<=n;i++) { //System.out.println("#1"); if( arr[i]==0 ) { for(int j=2*i;j<=n;j+=i) { arr[j]++; //System.out.println("#2"); } } } int count=0; for(int i=2;i<=n;i++) { //System.out.println("#3"); if(arr[i]==2) { count++; } } System.out.println(count); /*int n = fs.nextInt(), x = fs.nextInt(); int[] a =new int[n]; for(int i=0;i<n;i++) { a[i]=fs.nextInt(); } int[] b = a.clone(); Arrays.sort(b); for (int i = 0; i < n; i++) { if (i < x && n - 1 - i < x && a[i] != b[i]) { System.out.println("NO"); return; } } System.out.println("YES"); /*int n=fs.nextInt(); int x=fs.nextInt(); ArrayList<Long> list=new ArrayList<Long>(); for(int i=0;i<n;i++) { list.add(fs.nextLong()); } ArrayList<Long> copy=(ArrayList<Long>)list.clone(); Collections.sort(copy); for(int i=0;i<n;i++) { if( copy.get(i)!=list.get(i) ) { if( i < x && n - 1 - i < x ) { System.out.println("NO"); return; } } } System.out.println("YES"); /*int n=fs.nextInt(); int h=fs.nextInt(); ArrayList<Integer> list=new ArrayList<Integer>(); for(int i=0;i<n;i++) { list.add(fs.nextInt()); } Collections.sort(list, Collections.reverseOrder()); int sum=list.get(0)+list.get(1); int count= (h/sum)*2 ; int left=h%sum; if( left<=list.get(0) && left!=0 ) { count++; }else if(left!=0){ count+=2; } System.out.println(count); /*int n=fs.nextInt(); PriorityQueue<Pair<Integer,Integer>> pq=new PriorityQueue<Solution.Pair<Integer,Integer>>( (o1,o2)-> o2.first.compareTo(o1.first) ); for(int i=1;i<=n;i++) { int num=fs.nextInt(); if(num==0) { continue; } pq.add(new Pair<Integer,Integer>(num, i)); } ArrayList<Pair<Integer,Integer>> ans=new ArrayList<Solution.Pair<Integer,Integer>>(); while(pq.size()>1) { Pair p1=pq.poll(); Pair p2=pq.poll(); ans.add(new Pair(p1.second, p2.second)); p1.first=(int)p1.first-1; p2.first=(int)p2.first-1; if(!p1.first.equals(0)) pq.add(p1); if(!p2.first.equals(0)) pq.add(p2); } System.out.println(ans.size()); for(Pair p:ans) { System.out.println(p.first+" "+p.second); } /*int r=fs.nextInt(); int col=fs.nextInt(); int k=fs.nextInt(); char arr[][]=new char[r][col]; for(int i=0;i<r;i++) { char ch[]=fs.next().toCharArray(); arr[i]=ch; } boolean visited[][]=new boolean[r][col]; for(boolean b[]:visited) { Arrays.fill(b, false); } for(int i=r-1;i>=1;i--) { for(int j=1;j<col-1;j++) { if( arr[i][j]=='*' ) { int len = 0; int a1 = i - 1, l1 = j - 1, l2 = j + 1; ArrayList<Pair<Integer, Integer>> v=new ArrayList<Solution.Pair<Integer,Integer>>(); while (a1 >= 0 && l1 >= 0 && l2 < col) { if (arr[a1][l1] == '*' && arr[a1][l2] == '*') { len++; v.add(new Pair(a1,l1)); v.add(new Pair(a1,l2)); l1--; l2++; a1--; continue; } break; } if (len < k && visited[i][j] == false) { System.out.println("NO"); return; } if (len >= k) { for (Pair p:v) { visited[(int)p.first][(int)p.second] = true; } } visited[i][j] = true; } } } for (int i = 0; i < r; i++) { for (int j = 0; j < col; j++) { if (arr[i][j] == '*' && !visited[i][j]) { System.out.println("NO"); return; } } } System.out.println("YES"); /*int n=fs.nextInt(); int arr[]=new int[n+1]; for(int i=1;i<=n;i++) { arr[i]=fs.nextInt(); } ArrayList<int[]> list=new ArrayList<int[]>(); int smallAns[]=new int[3]; for(int i=1;i<=n ;i++) { int minI=i; for(int j=i+1;j<=n;j++) { if(arr[minI]>arr[j]) { minI=j; } } if(minI==i) { continue; } //System.out.println(minI); int temp=arr[minI]; for(int j=minI;j>i;j--) { arr[j]=arr[j-1]; } arr[i]=temp; smallAns[0]=i; smallAns[1]=minI; smallAns[2]=minI-i; list.add(Arrays.copyOf(smallAns,smallAns.length)); } System.out.println(list.size()); for(int i=0;i<list.size();i++) { System.out.println(list.get(i)[0]+" "+list.get(i)[1]+" "+list.get(i)[2]); } /*System.out.println("sort"); for(int i=1;i<=n;i++) { System.out.print(arr[i]+" "); } System.out.println(); /*String s=fs.next(); int a=0; int b=0; int c=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='A') { a++; }else if( s.charAt(i)=='B' ) { b++; }else { c++; } } if( a+c==b ) { System.out.println("YES"); }else { System.out.println("NO"); } /*int w=fs.nextInt(); int h=fs.nextInt(); int x1=fs.nextInt(); int y1=fs.nextInt(); int x2=fs.nextInt(); int y2=fs.nextInt(); int tw=fs.nextInt(); int th=fs.nextInt(); if( !( ( w>= (Math.abs(x1-x2)+tw) || h>= (Math.abs(y1-y2)+th) ) || ( w>= ( Math.abs(x1-x2)+th ) || h>= ( Math.abs(y1-y2)+tw ) ) ) ) { System.out.println(-1); return ; } int ans=Integer.MAX_VALUE; if( y1>= th || h-y2>=th ) { ans=0; }else if( th+y2-y1 <= h ) { ans= th-y1; ans = Math.min(ans, th-( h-y2 ) ); } if( x1>=tw || w-x2 >= tw) { ans=0; }else if( tw+ x2-x1 <= w ) { ans=Math.min(ans, tw-x1 ); ans= Math.min(ans, tw-(w-x2) ); } if(ans== Integer.MAX_VALUE ) { System.out.println(-1); }else if( ans<0 ) { System.out.println(0); }else System.out.println(ans); /*int col=fs.nextInt(); int in[][]=new int[2][col]; for(int i=0;i<col;i++) { in[0][i]=fs.nextInt(); } for(int i=0;i<col;i++) { in[1][i]=fs.nextInt(); } int leftSum[][]=new int[2][col]; leftSum[0][0]=in[0][0]; leftSum[1][0]=in[1][0]; for(int i=1;i<col;i++) { leftSum[0][i]=in[0][i]+leftSum[0][i-1]; leftSum[1][i]=in[1][i]+leftSum[1][i-1]; } int rightSum[][]=new int[2][col]; rightSum[0][col-1]=in[0][col-1]; rightSum[1][col-1]=in[1][col-1]; for(int i=col-2;i>=0;i--) { rightSum[0][i]=rightSum[0][i+1] + in[0][i]; rightSum[1][i]=rightSum[1][i+1] + in[1][i]; } int minScore=Integer.MAX_VALUE; for(int i=0;i<col;i++) { int score1= ( i+1<col ) ? rightSum[0][i+1] : 0; int score2= (i-1>=0) ? leftSum[1][i-1] : 0; minScore= Math.min(minScore, Math.max(score1, score2)); } System.out.println(minScore); /*int n=fs.nextInt(); long input[]=new long[n]; for(int i=0;i<n;i++) { input[i]=fs.nextLong(); } int even=0; for(int i=0;i<n;i++) { if( (input[i]&1) ==0 ) { even++; } } int odd=n-even; if( Math.abs(odd-even) > 1 ) { System.out.println(-1); return ; } for(int i=0;i<n;i++) { input[i]= ( (input[i]&1)==1 )?1 :0; } int ans=Integer.MAX_VALUE; if( (n&1)==0 ) { int output[]=new int[n]; for(int i=0;i<n;i++) { output[i] = ( i&1 )==1 ? 1:0; } ArrayList<Integer> oddpos=new ArrayList<Integer>(); ArrayList<Integer> evenpos=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if( input[i] != output[i] ) { if( (i&1)==1 ) oddpos.add(i); else evenpos.add(i); } } int smallAns=0; for(int i=0;i<oddpos.size();i++) { smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i)); } ans=Math.min(ans, smallAns); output=new int[n]; for(int i=0;i<n;i++) { output[i] = ( i&1 )==0 ? 1:0; } oddpos=new ArrayList<Integer>(); evenpos=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if( input[i] != output[i] ) { if( (i&1)==1 ) oddpos.add(i); else evenpos.add(i); } } smallAns=0; for(int i=0;i<oddpos.size();i++) { smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i)); } ans=Math.min(ans, smallAns); }else if( odd> even ) { int output[]=new int[n]; for(int i=0;i<n;i++) { output[i] = ( i&1 )==0 ? 1:0; } ArrayList<Integer> oddpos=new ArrayList<Integer>(); ArrayList<Integer> evenpos=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if( input[i] != output[i] ) { if( (i&1)==1 ) oddpos.add(i); else evenpos.add(i); } } int smallAns=0; for(int i=0;i<oddpos.size();i++) { smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i)); } ans=Math.min(ans, smallAns); }else { int output[]=new int[n]; for(int i=0;i<n;i++) { output[i] = ( i&1 )==1 ? 1:0; } ArrayList<Integer> oddpos=new ArrayList<Integer>(); ArrayList<Integer> evenpos=new ArrayList<Integer>(); for(int i=0;i<n;i++) { if( input[i] != output[i] ) { if( (i&1)==1 ) oddpos.add(i); else evenpos.add(i); } } int smallAns=0; for(int i=0;i<oddpos.size();i++) { smallAns+= Math.abs(oddpos.get(i)-evenpos.get(i)); } ans=Math.min(ans, smallAns); } System.out.println(ans); /* int len=fs.nextInt(); String row1=fs.next(); String row2=fs.next(); int prev=-1; int count=0; for(int i=0;i<len; i++) { if( row1.charAt(i) != row2.charAt(i) ) { count+=2; prev=-1; }else if ( row1.charAt(i)=='1') { if(prev==0) { count++; prev=-1; }else { prev=1; } }else { if(prev==1) { count+=2; prev=-1; }else { count++; prev=0; } } } System.out.println(count); /*int a=fs.nextInt(); int b=fs.nextInt(); int c=fs.nextInt(); int m=fs.nextInt(); int max=a+b+c-3; int arr[]= {a,b,c}; Arrays.parallelSort(arr); int min=arr[2]-arr[1]-arr[0]-1; if(m>=min && m<=max) { System.out.println("YES"); }else { System.out.println("No"); } */ /* int n=fs.nextInt(); long hero[]=new long[n]; long sum=0; for(int i=0;i<n;i++) { hero[i]=Long.parseLong(fs.next()); sum+=hero[i]; } //System.out.println(sum); Arrays.sort(hero); //for(long x: hero) //System.out.print(x+" "); //System.out.println(); int m=fs.nextInt(); while(m-->0) { long df=Long.parseLong(fs.next()); long at=Long.parseLong(fs.next()); long nextGrt=(long)Math.pow(10, 18); long nextSmall=-1; int index=uperBound(hero, df); //System.out.println(hero[index]); //System.out.println(index); if(index>=n) { nextSmall=hero[n-1]; }else if(index<=0 ) { nextGrt=hero[0]; }else { nextGrt=hero[index]; nextSmall=hero[index-1]; } /*for(int i=0;i<n;i++) { if(hero[i]>=df && hero[i]<nextGrt ) { nextGrt=hero[i]; } if(hero[i]<=df && hero[i]>nextSmall ) { nextSmall=hero[i]; } } //System.out.println(nextGrt +" : "+nextSmall); if( nextGrt!= (long) Math.pow(10, 18) && sum-nextGrt >=at ) { System.out.println(0); }else { if(nextGrt==(long)Math.pow(10, 18)) { long ans= df- nextSmall; ans+= ( at<= ( sum-nextSmall ) ) ? 0 : (at- sum+nextSmall); System.out.println(ans); } else if(nextSmall==-1) { long ans= ( at <= sum- nextGrt ) ? 0 : ( at- sum+nextGrt); System.out.println(ans); }else { long ans1=df- nextSmall; ans1+= ( at<= ( sum-nextSmall ) ) ? 0 : (at- sum+nextSmall); long ans2= ( at <= sum- nextGrt ) ? 0 : ( at- sum+nextGrt); System.out.println(Math.min(ans1, ans2)); } } } /*int n=fs.nextInt(); for(int i=1;i<=n;i++) { String open=""; String close=""; for(int j=1;j<=i;j++) { open+="("; close+=")"; } int j=0; while( j+2*i <= 2* n) { System.out.print(open); System.out.print(close); j=j+2*i; } //System.out.println(j); if(j<2*n) { while(j<2*n) { System.out.print("("); System.out.print(")"); j+=2; } } System.out.println(); } */ } static int computeXOR(int n) { // If n is a multiple of 4 if (n % 4 == 0) return n; // If n%4 gives remainder 1 if (n % 4 == 1) return 1; // If n%4 gives remainder 2 if (n % 4 == 2) return n + 1; // If n%4 gives remainder 3 return 0; } static boolean isSorted (int[] nums) { for (int i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) { return false; } } return true; } static void firstOperation (int[] nums) { for (int i = 1; i < nums.length; i += 2) { int temp = nums[i]; nums[i] = nums[i - 1]; nums[i - 1] = temp; } } static void secondOperation (int[] nums) { int n = nums.length / 2; for (int i = 0; i < n; i++) { int temp = nums[i]; nums[i] = nums[i + n]; nums[i + n] = temp; } } private static long numOfDigits(long a) { long ans=0; while(a!=0) { ans++; a/=10; } return ans; } private static String reverse(String s) { String ans=""; for(int i=s.length()-1;i>=0;i--) { ans+=s.charAt(i); } return ans; } private static boolean isPalindrome(String s) { int i=0; int j=s.length()-1; while(i<j) { if(s.charAt(i)!=s.charAt(j)) { return false; } i++; j--; } return true; } static class FastScanner { BufferedReader br; StringTokenizer st ; FastScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } FastScanner(String file) { try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); st = new StringTokenizer(""); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("file not found"); e.printStackTrace(); } } String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } String readLine() throws IOException{ return br.readLine(); } } public static long[] sort(long arr[]){ List<Long> list = new ArrayList<>(); for(long n : arr){list.add(n);} Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i] = list.get(i); } return arr; } public static int[] sort(int arr[]){ List<Integer> list = new ArrayList<>(); for(int n : arr){list.add(n);} Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i] = list.get(i); } return arr; } // return the (index + 1) // where index is the pos of just smaller element // i.e count of elemets strictly less than num public static int justSmaller(long arr[],long num){ // System.out.println(num+"@"); int st = 0; int e = arr.length - 1; int ans = -1; while(st <= e){ int mid = (st + e)/2; if(arr[mid] >= num){ e = mid - 1; }else{ ans = mid; st = mid + 1; } } return ans + 1; } //return (index of just greater element) //count of elements smaller than or equal to num public static int justGreater(long arr[],long num){ int st = 0; int e = arr.length - 1; int ans = arr.length; while(st <= e){ int mid = (st + e)/2; if(arr[mid] <= num){ st = mid + 1; }else{ ans = mid; e = mid - 1; } } return ans; } public static boolean isPrime(int n) { for(int i=2;i<n;i++) { if(n%i==0) { return false; } } return true; } public static void println(Object obj){ System.out.println(obj.toString()); } public static void print(Object obj){ System.out.println(obj.toString()); } public static long gcd(long a,long b){ if(b == 0l){ return a; } return gcd(b,a%b); } public static int find(int parent[],int v){ if(parent[v] == v){ return v; } return parent[v] = find(parent, parent[v]); } public static List<Integer> sieve(){ List<Integer> prime = new ArrayList<>(); int arr[] = new int[100001]; Arrays.fill(arr,1); arr[1] = 0; arr[2] = 1; for(int i=2;i<=100000;i++){ if(arr[i] == 1){ prime.add(i); for(long j = (i*1l*i);j<100001;j+=i){ arr[(int)j] = 0; } } } return prime; } static boolean isPower(long n,long a){ long log = (long)(Math.log(n)/Math.log(a)); long power = (long)Math.pow(a,log); if(power == n){return true;} return false; } private static int mergeAndCount(int[] arr, int l,int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(int[] arr, int l,int r) { // Keeps track of the inversion count at a // particular node of the recursion tree int count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left subarray count // + right subarray count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } static class Debug { //change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) throws Exception { if(LOCAL) { PrintStream ps = new PrintStream("src/Debug.txt"); System.setErr(ps); System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
3c7aab13ae3876864448e27abc36de5d
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; public class Codeforces { static Scanner sc=new Scanner(System.in); public static void main(String[] args) { int t=1; t=sc.nextInt(); while(t-->0) { solve(); } } private static void fill(int[][] arr) { /*int n=arr.length; int count=1; for(int i=0;i<n;i++) { arr[i][i]=count++; } for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { arr[i][j]=count++; arr[j][i]=count++; } } /* if(i>=n) return true; for(int k=1;k<=n*n;k++) { if(!set.contains(k)) { int count=0; if(i-1>=0 && Math.abs(k-arr[i-1][j])==1) { count++; } if(i+1<n && Math.abs(k-arr[i+1][j])==1) { count++; } if(j-1>=0 && Math.abs(k-arr[i][j-1])==1) { count++; } if(j+1<n && Math.abs(k-arr[i][j+1])==1) { count++; } if(count==0) { arr[i][j]=k; //System.out.println(k); set.add(k); if(j==n-1) { if(!fill(arr,i+1,0,set)) { arr[i][j]=-5; set.remove(k); }else { return true; } }else { if(!fill(arr,i,j+1,set)) { arr[i][j]=-5; set.remove(k); }else { return true; } } } } } return false; */ } private static void solve() { int n=sc.nextInt(); long arr[]=new long[n+1]; for(int i=1;i<=n;i++) { arr[i]=sc.nextInt(); } int count=0; /*for(int i=1;i<=n;i++) { for( int j = arr[i]-i ; j <= n ; j = j+arr[i] ) { if( j >=0) if( arr[i] * arr[j] == i + j && i < j ) count++; } }*/ for (int i = 1; i <= n; i++) { for (int j =(int) arr[i] - i; j <= n; j += arr[i]) { if (j >= 0) if (arr[i] * arr[j] == i + j && i < j) count++; } } System.out.println(count); /*int n=sc.nextInt(); int m=sc.nextInt(); String input[]=new String[n]; String out[]=new String[n-1]; for(int i=0;i<n;i++) { input[i]=sc.next(); } if(n==1) { System.out.println(input[0]); return ; } for(int i=0;i<n-1;i++) { out[i]=sc.next(); } String s=""; for(int i=0;i<m;i++) { int sum=0; for(int j=0;j<n;j++) { sum+=input[j].charAt(i); if(j<n-1) { sum-=out[j].charAt(i); } } s=s+ (char)sum; //System.out.println(s); } System.out.println(s); /*long k=sc.nextLong(); long squarRoot=(long)Math.floor(Math.sqrt(k-1)); squarRoot++; long fillF=(squarRoot-1)*(squarRoot-1)+1; //System.out.println(fillF); if(k-fillF<squarRoot) { System.out.println((k-fillF+1)+" "+squarRoot); }else { System.out.println(squarRoot+" "+((squarRoot*squarRoot)-k+1)); } /*int a=sc.nextInt(); int b=sc.nextInt(); int c=sc.nextInt(); int total=2*Math.abs(a-b); if(Math.min(a, b)-1> Math.abs(a-b)-1 || c>total ) { System.out.println(-1); return; } int d= ((total+ 2*c )/2)%total; if(d==0) { System.out.println(total); }else { System.out.println(d); } /*int k=sc.nextInt(); int n=1; int i=1; while(i<k) { n++; if(!(n%3==0 || n%10==3)) { i++; } } System.out.println(n); */ /*int k=sc.nextInt(); int n=sc.nextInt(); int m=sc.nextInt(); int arr1[]=new int[n]; int arr2[]=new int[m]; for(int i=0;i<n;i++) { arr1[i]=sc.nextInt(); } for(int j=0;j<m;j++) { arr2[j]=sc.nextInt(); } int i=0; int j=0; boolean turn=true; int a=0; int ans[]=new int[m+n]; while(i<n && j<m) { if(arr1[i]==0) { ans[a++]=arr1[i++]; k++; continue; } if(arr2[j]==0) { ans[a++]=arr2[j++]; k++; continue; } if(arr1[i]<arr2[j]) { if(arr1[i]>k) { System.out.println(-1); return; }else { ans[a++]=arr1[i++]; } }else { if(arr2[j]>k) { System.out.println(-1); return; }else { ans[a++]=arr2[j++]; } } } while(i<n) { if(arr1[i]==0) { ans[a++]=arr1[i++]; k++; continue; } if(arr1[i]>k) { System.out.println(-1); return; }else { ans[a++]=arr1[i++]; } } while(j<m) { if(arr2[j]==0) { ans[a++]=arr2[j++]; k++; continue; } if(arr2[j]>k) { System.out.println(-1); return; }else { ans[a++]=arr2[j++]; } } for(i=0;i<m+n;i++) { System.out.print(ans[i]+" "); } System.out.println(); /*int r=sc.nextInt(); int b=sc.nextInt(); int d=sc.nextInt(); int min=Math.min(r,b); int red=(r+min-1)/min; int blue=(b+min-1)/min; if(Math.abs(red-blue)<=d) { System.out.println("YES"); }else { System.out.println("NO"); } /*int n=sc.nextInt(); int m=sc.nextInt(); int k=sc.nextInt(); int tCost=(m-1)+(n-1)*m; if(k==tCost) { System.out.println("YES"); }else { System.out.println("NO"); } /*int n=sc.nextInt(); String s=sc.next().substring(0,n); Set<Character> set=new HashSet<Character>(); set.add(s.charAt(0)); for(int i=1;i<s.length();i++) { if(s.charAt(i)==s.charAt(i-1)) { continue; } if(set.contains(s.charAt(i))) { System.out.println("NO"); return; } set.add(s.charAt(i)); } System.out.println("YES"); /*long n=sc.nextLong(); if(n<10) { System.out.println(n); return; } Queue<Long> q=new LinkedList<Long>(); for(long i=1;i<10;i++) { q.add(i); } int count=0; while(q.peek()<=n) { count++; long front=q.poll(); q.add(front*10+(front%10)); } System.out.println(count); /*int n=sc.nextInt(); if(n==1) { System.out.println(1); return ; } if(n==2) { System.out.println(-1); return; } int arr[][]=new int[n][n]; fill(arr); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } /* int a=sc.nextInt(); int b=sc.nextInt(); if(b==1) { System.out.println("NO"); return; } long x=a; long y= (1L*a*b); long z=x+y; System.out.println("YES"); System.out.println(x+" "+y+" "+z); /*int n=sc.nextInt(); int t=sc.nextInt(); String s=sc.next().substring(0,n); Stack<Integer> st=new Stack<Integer>(); for(int i=n-1;i>=0;i--) { if(s.charAt(i)=='1') { st.push(i); } } Stack<Integer> left=new Stack<Integer>(); for(int i=0;i<n;i++) { if(s.charAt(i)=='1') { left.push(i); st.pop(); }else { if(st.isEmpty() && left.isEmpty()) { System.out.println(s); return; }else if(left.isEmpty()) { int rightO=st.peek(); if(rightO-i<=t) { s=s.substring(0,i)+'1'+s.substring(i+1,n); } }else if(st.isEmpty()) { int leftIndex=left.peek(); if(i-leftIndex<=t) { s=s.substring(0,i)+'1'+s.substring(i+1,n); } }else { int rightO=st.peek(); int leftIndex=left.peek(); if(i-leftIndex != rightO-i && (i-leftIndex<=t || rightO-i<=t )) { s=s.substring(0,i)+'1'+s.substring(i+1,n); } } } } System.out.println(s); /* int n=sc.nextInt(); int arr[]=new int[2*n]; for(int i=0;i<2*n;i++) { arr[i]=sc.nextInt(); } Arrays.sort(arr); int i=0; int j=n; int arr2[]=new int[2*n]; int k=0; while(k<2*n) { if(k%2==0) { arr2[k++]=arr[i++]; }else { arr2[k++]=arr[j++]; } } for(i=0;i<2*n;i++) { System.out.print(arr2[i]+" "); } System.out.println(); /*long n=sc.nextLong(); long ans=n; int i=1; for(;;i++) { if((Math.pow(2,i)-1)>=n) { break; } } System.out.println((long)Math.pow(2,i-1)-1); /* //Binary Decimal long l=sc.nextLong(); long max=0; while(l>0) { max=Math.max(max, l%10); l/=10; } System.out.println(max); /* //B. Putting Plates int m=sc.nextInt(); int n=sc.nextInt(); int arr[][]=new int[m][n]; for(int i=0;i<n;i++) { if(i%2==0) { arr[0][i]=1; arr[m-1][i]=1; } } for(int i=2;i<m-2;i++) { if(i%2==0) { arr[i][0]=1; arr[i][n-1]=1; } } for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { System.out.print(arr[i][j]); } System.out.println(); } /* //Colour the flag int n=sc.nextInt(); int m=sc.nextInt(); char arr[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=sc.next(); for(int j=0;j<m;j++) { arr[i][j]=s.charAt(j); } } boolean isRed=false; int row=0; int col=0; for(int i=0;i<n;i++) { boolean get=false; for(int j=0;j<m;j++) { if(arr[i][j]=='R') { isRed=true; row=i; col=j; get=true; break; } if(arr[i][j]=='W') { row=i; col=j; get=true; break; } } if(get) break; } char color; char color1; if(isRed) { color='R'; color1='W'; }else { color='W'; color1='R'; } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if((i%2==row%2 && j%2==col%2) || (i%2!=row%2 && j%2!=col%2) ) { if( !(arr[i][j]==color || arr[i][j]=='.') ) { System.out.println("NO"); return ; } }else { if(arr[i][j]==color) { System.out.println("NO"); return ; } } } } System.out.println("YES"); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if((i%2==row%2 && j%2==col%2) || (i%2!=row%2 && j%2!=col%2) ) { arr[i][j]=color; }else { arr[i][j]=color1; } } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { System.out.print(arr[i][j]); } System.out.println(); } */ } private static int __gcd(int i, int j) { if(i%j==0) { return j; } return __gcd(j, i%j ); } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
3125406bfec1754a2279697859c28b9c
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class myCode { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter out) { int n = sc.nextInt(); int[] arr = new int[n]; ArrayList<Pair> al = new ArrayList<>(); for(int i = 0 ; i<n;i++){ arr[i] = sc.nextInt(); Pair p = new Pair(arr[i],i+1); al.add(p); } Collections.sort(al); int val = get(al,n); out.println(val); } static class Pair implements Comparable<Pair>{ long val = 0; int idx = 0; public Pair(long val,int idx){ this.val = val; this.idx = idx; } @Override public int compareTo(Pair other){ return Long.compare(val, other.val); } } static int get(ArrayList<Pair> al,int n){ int count= 0 ; for(int i = 0 ; i<n;i++){ for(int j = i+1;j<n;j++){ Pair p1 = al.get(i); Pair p2 = al.get(j); long val = p1.val; long val2 = p2.val; long val3 = val*val2; if(val3 > p1.idx+n){ break; }else{ int val4 = p1.idx + p2.idx; if(val4 == val3){ count++; } } } } return count; } }// end static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
9f95971d561c653177b04eebc72a6496
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.*; import java.util.*; import java.util.Random; import java.util.StringTokenizer; public class myCode { public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter out) { int n = sc.nextInt(); Pair[] al = new Pair[n]; for(int i = 0 ; i<n;i++){ al[i] = new Pair(sc.nextInt(),i+1); } Arrays.sort(al); int val = get(al,n); out.println(val); } static class Pair implements Comparable<Pair>{ long val = 0; int idx = 0; public Pair(long val,int idx){ this.val = val; this.idx = idx; } @Override public int compareTo(Pair other){ return Long.compare(val, other.val); } } static int get(Pair[] a,int n){ int count= 0 ; for(int i = 0 ; i<n;i++){ for(int j = i+1;j<n;j++){ if(a[i].val * a[j].val > a[i].idx + n) break; if(a[i].val * a[j].val == a[i].idx + a[j].idx) count++; } } return count; } }// end static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
5a288ed1b92ccc3abf2a099a85f7f0e9
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class _practise { 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()); } int[] ia(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=nextInt(); return a; } int[][] ia(int n , int m) { int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<n ;j++) a[i][j]=nextInt(); return a; } char[][] ca(int n , int m) { char a[][]=new char[n][m]; for(int i=0;i<n;i++) { String x =next(); for(int j=0;j<n ;j++) a[i][j]=x.charAt(j); } return a; } long[] la(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(long[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {long oi=r.nextInt(n), temp=a[i];a[i]=a[(int)oi];a[(int)oi]=temp;}Arrays.sort(a);} static void sort(int[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {int oi=r.nextInt(n), temp=a[i];a[i]=a[oi];a[oi]=temp;}Arrays.sort(a);} public static long sum(long a[]) {long sum=0; for(long i : a) sum+=i; return(sum);} public static long count(long a[] , long x) {long c=0; for(long i : a) if(i==x) c++; return(c);} public static int sum(int a[]) { int sum=0; for(int i : a) sum+=i; return(sum);} public static int count(int a[] ,int x) {int c=0; for(int i : a) if(i==x) c++; return(c);} public static int count(String s ,char ch) {int c=0; char x[] = s.toCharArray(); for(char i : x) if(ch==i) c++; return(c);} public static boolean prime(int n) {for(int i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static boolean prime(long n) {for(long i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static int gcd(int n1, int n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static long gcd(long n1, long n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static int[] freq(int a[], int n) { int f[]=new int[n+1]; for(int i:a) f[i]++; return f;} public static int[] pos(int a[], int n) { int f[]=new int[n+1]; for(int i=0; i<n ;i++) f[a[i]]=i; return f;} public static long mindig(long n) { long ans=9; while(n>0) { if(n%10<ans) ans=n%10; n/=10; } return ans; } public static long maxdig(long n) { long ans=0; while(n>0) { if(n%10>ans) ans=n%10; n/=10; } return ans; } public static boolean palin(String s) { StringBuilder sb = new StringBuilder(); sb.append(s); String str=String.valueOf(sb.reverse()); if(s.equals(str)) return true; else return false; } public static void main(String args[]) { FastReader in=new FastReader(); PrintWriter so = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); _practise ob = new _practise(); int t = in.nextInt(); //int t = 1; while(t-->0) { int n = in.nextInt(); int a[] = new int[n+1];for(int i=1 ; i<=n ; i++) a[i]=in.nextInt(); long ans=0; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); for(int i=1 ; i<=n ; i++) { hm.put(a[i],i); } // so.println(hm); for(int i=1 ; i<=2*n ; i++) { for(int j=1 ; j<=Math.sqrt(i) ; j++) { if(i%j==0 && j!=i/j ) { int x1=hm.getOrDefault(j, Integer.MIN_VALUE); int x2=hm.getOrDefault(i/j, Integer.MIN_VALUE); if(x1!=x2 && x1+x2==i) ans++; } } } so.println(ans); } so.flush(); /*String s = in.next(); * Arrays.stream(f).min().getAsInt() * BigInteger f = new BigInteger("1"); 1 ke jagah koi bhi value ho skta jo aap * initial value banan chahte int a[] = new int[n]; Stack<Integer> stack = new Stack<Integer>(); Deque<Integer> q = new LinkedList<>(); or Deque<Integer> q = new ArrayDeque<Integer>(); PriorityQueue<Long> pq = new PriorityQueue<Long>(); ArrayList<Integer> al = new ArrayList<Integer>(); StringBuilder sb = new StringBuilder(); HashSet<Integer> st = new LinkedHashSet<Integer>(); Set<Integer> s = new HashSet<Integer>(); Map<Long,Integer> hm = new HashMap<Long, Integer>(); //<key,value> for(Map.Entry<Integer, Integer> i :hm.entrySet()) HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); so.println("HELLO"); Arrays.sort(a,Comparator.comparingDouble(o->o[0])) Arrays.sort(a, (aa, bb) -> Integer.compare(aa[1], bb[1]));*/ } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
63edc61d199a4b06e57917b8a1be90ca
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class _practise { 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()); } int[] ia(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=nextInt(); return a; } int[][] ia(int n , int m) { int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<n ;j++) a[i][j]=nextInt(); return a; } char[][] ca(int n , int m) { char a[][]=new char[n][m]; for(int i=0;i<n;i++) { String x =next(); for(int j=0;j<n ;j++) a[i][j]=x.charAt(j); } return a; } long[] la(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(long[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {long oi=r.nextInt(n), temp=a[i];a[i]=a[(int)oi];a[(int)oi]=temp;}Arrays.sort(a);} static void sort(int[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {int oi=r.nextInt(n), temp=a[i];a[i]=a[oi];a[oi]=temp;}Arrays.sort(a);} public static long sum(long a[]) {long sum=0; for(long i : a) sum+=i; return(sum);} public static long count(long a[] , long x) {long c=0; for(long i : a) if(i==x) c++; return(c);} public static int sum(int a[]) { int sum=0; for(int i : a) sum+=i; return(sum);} public static int count(int a[] ,int x) {int c=0; for(int i : a) if(i==x) c++; return(c);} public static int count(String s ,char ch) {int c=0; char x[] = s.toCharArray(); for(char i : x) if(ch==i) c++; return(c);} public static boolean prime(int n) {for(int i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static boolean prime(long n) {for(long i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static int gcd(int n1, int n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static long gcd(long n1, long n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static int[] freq(int a[], int n) { int f[]=new int[n+1]; for(int i:a) f[i]++; return f;} public static int[] pos(int a[], int n) { int f[]=new int[n+1]; for(int i=0; i<n ;i++) f[a[i]]=i; return f;} public static long mindig(long n) { long ans=9; while(n>0) { if(n%10<ans) ans=n%10; n/=10; } return ans; } public static long maxdig(long n) { long ans=0; while(n>0) { if(n%10>ans) ans=n%10; n/=10; } return ans; } public static boolean palin(String s) { StringBuilder sb = new StringBuilder(); sb.append(s); String str=String.valueOf(sb.reverse()); if(s.equals(str)) return true; else return false; } public static void main(String args[]) { FastReader in=new FastReader(); PrintWriter so = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); _practise ob = new _practise(); int t = in.nextInt(); //int t = 1; while(t-->0) { int n=in.nextInt(); int a[]=new int[n]; HashMap<Integer,Integer> hm=new HashMap<>(); for(int i=0;i<n;i++) { a[i]=in.nextInt(); hm.put(a[i], i+1); } long ans=0; for(int i=3;i<=2*n;i++) { for(int j=1;j*j<=i;j++) { if(i%j==0) { int val1=hm.getOrDefault(j,Integer.MIN_VALUE); int val2=hm.getOrDefault(i/j,Integer.MIN_VALUE); if(val1!=val2) { if(i==val1+val2) { ans++; } } } } } System.out.println(ans); /*int n = in.nextInt(); long a[] = in.la(n); long ans=0; HashMap<Long, Integer> hm = new HashMap<Long, Integer>(); Set<Double> s = new HashSet<Double>(); for(int i=0 ; i<n ; i++) { hm.put(a[i],i); } for(int i=1 ; i<2*n ; i++) { for(int j=1 ; j<=Math.sqrt(i) ; j++) { if(i%j==0 && j!=i/j && j<=n && i/j<=n) { if(a[j-1]*a[i/j-1]==i) ans++; } } } so.println(ans);*/ } so.flush(); /*String s = in.next(); * Arrays.stream(f).min().getAsInt() * BigInteger f = new BigInteger("1"); 1 ke jagah koi bhi value ho skta jo aap * initial value banan chahte int a[] = new int[n]; Stack<Integer> stack = new Stack<Integer>(); Deque<Integer> q = new LinkedList<>(); or Deque<Integer> q = new ArrayDeque<Integer>(); PriorityQueue<Long> pq = new PriorityQueue<Long>(); ArrayList<Integer> al = new ArrayList<Integer>(); StringBuilder sb = new StringBuilder(); HashSet<Integer> st = new LinkedHashSet<Integer>(); Set<Integer> s = new HashSet<Integer>(); Map<Long,Integer> hm = new HashMap<Long, Integer>(); //<key,value> for(Map.Entry<Integer, Integer> i :hm.entrySet()) HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); so.println("HELLO"); Arrays.sort(a,Comparator.comparingDouble(o->o[0])) Arrays.sort(a, (aa, bb) -> Integer.compare(aa[1], bb[1]));*/ } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
91a4f6c530f8d874e56bfb9f62eb5655
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
//--------I--------- import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; //--------O--------- import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.OutputStreamWriter; //--------Arrays--------- import java.util.Arrays; //--------Lists--------- import java.util.List; import java.util.ArrayList; import java.util.LinkedList; import java.util.Collections; import java.util.Comparator; //--------Sets--------- import java.util.Set; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.TreeSet; //--------Stack/Queue--------- import java.util.Stack; import java.util.Queue; import java.util.Random; import java.util.ArrayDeque; import java.util.PriorityQueue; //--------Maps--------- import java.util.Map; import java.util.TreeMap; import java.util.HashMap; import java.util.LinkedHashMap; @SuppressWarnings("unused") public class TEMPLATE { final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; public static char sc() throws IOException { byte c = read();while (Character.isWhitespace(c)) c = read();return (char) c; } public static String ss() throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int cnt = 0, c; while ((c = read()) != -1) {if (c == '\n') {if (cnt != 0) break;continue;} buf[cnt++] = (byte) c;} return new String(buf, 0, cnt); } public static int si() 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 static int[] sia(int length) throws IOException { int[] ret = new int[length]; for (int i = 0; i < length; ++i) ret[i] = si(); return ret; } public static long sl() 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 static long[] sla(int length) throws IOException { long[] ret = new long[length]; for (int i = 0; i < length; ++i) ret[i] = sl(); return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public static void main(final String[] args) throws IOException { int tc = si(); while (tc-->0) { int n = si(); long cnt = 0; long[] arr = sla(n); for (int i = 1; i <= n; ++i) { long first = arr[i-1]; long start = 2*i % first; start = i + first - start; for (long j = start; j <= n; j += first) { long second = arr[(int) (j-1)]; if (first * second == i + j) { cnt++; } } } System.out.println(cnt); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
7864ff957bb93baf4ee09847d19e96e3
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
//--------I--------- import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; //--------O--------- import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.OutputStreamWriter; //--------Arrays--------- import java.util.Arrays; //--------Lists--------- import java.util.List; import java.util.ArrayList; import java.util.LinkedList; import java.util.Collections; import java.util.Comparator; //--------Sets--------- import java.util.Set; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.TreeSet; //--------Stack/Queue--------- import java.util.Stack; import java.util.Queue; import java.util.Random; import java.util.ArrayDeque; import java.util.PriorityQueue; //--------Maps--------- import java.util.Map; import java.util.TreeMap; import java.util.HashMap; import java.util.LinkedHashMap; @SuppressWarnings("unused") public class TEMPLATE { final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; public static char sc() throws IOException { byte c = read();while (Character.isWhitespace(c)) c = read();return (char) c; } public static String ss() throws IOException { byte[] buf = new byte[BUFFER_SIZE]; int cnt = 0, c; while ((c = read()) != -1) {if (c == '\n') {if (cnt != 0) break;continue;} buf[cnt++] = (byte) c;} return new String(buf, 0, cnt); } public static int si() 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 static int[] sia(int length) throws IOException { int[] ret = new int[length]; for (int i = 0; i < length; ++i) ret[i] = si(); return ret; } public static long sl() 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 static long[] sla(int length) throws IOException { long[] ret = new long[length]; for (int i = 0; i < length; ++i) ret[i] = sl(); return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public static void main(final String[] args) throws IOException { int tc = si(); while (tc-->0) { int n = si(); long cnt = 0; long[] arr = sla(n); for (int i = 1; i <= n; ++i) { long first = arr[i-1]; long start = 2*i / first*first - i; if (start <= i) { start += first; } for (long j = start; j <= n; j += first) { assert(j > 0); long second = arr[(int) (j-1)]; if (first * second == i + j) { cnt++; } } } System.out.println(cnt); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
5722757f4d291dfdd151275c29e1dd09
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.util.*; public class main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int[] arr = new int[n+1]; for(int i=1;i<=n;i++) { arr[i] = sc.nextInt(); } long count=0; for(int i=1;i<n;i++) { for(int j=arr[i]-i;j<=n;j+=arr[i]) { if(j>i) { if( arr[i]*1l*arr[j] == i+j) { count++; } } } } System.out.println(count); } } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
131f2d4567a26cae4cdc6fd5546ba477
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } //check only for sqrt of the number as the divisors //keep repeating so only half of them are required. So,sqrt. for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Long> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Long> l = new ArrayList<>(); for (long p = 2; p*p<=n; p++) { if (prime[(int)(p)] == true) { for(long i = p*p; i<=n; i += p) { prime[(int)(i)] = false; } } } for (long p = 2; p<=n; p++) { if (prime[(int)(p)] == true) { l.add(p); } } return l; } public static int countDivisors(int x) { int c = 0; for(int i = 1;i*i<=x;i++) { if(x%i == 0) { if(x/i != i) { c+=2; } else { c++; } } } return c; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(long a[], long x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(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; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); Pair[] pp = new Pair[n]; for(int i = 0;i<n;i++) { pp[i] = new Pair(sc.nextInt(),i+1); } long ans = 0; Arrays.sort(pp,(o1,o2) -> o1.first - o2.first); for(int i = 0;i<n;i++) { for(int j = i+1;j<n;j++) { if(1L * pp[i].first * pp[j].first > 2 * n) break; ans += (1L * pp[i].first * pp[j].first == pp[i].second + pp[j].second) ? 1 : 0; } } fout.println(ans); } fout.close(); } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
5dd9531f15898cf65828766f5cc874b1
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } //check only for sqrt of the number as the divisors //keep repeating so only half of them are required. So,sqrt. for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Long> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Long> l = new ArrayList<>(); for (long p = 2; p*p<=n; p++) { if (prime[(int)(p)] == true) { for(long i = p*p; i<=n; i += p) { prime[(int)(i)] = false; } } } for (long p = 2; p<=n; p++) { if (prime[(int)(p)] == true) { l.add(p); } } return l; } public static int countDivisors(int x) { int c = 0; for(int i = 1;i*i<=x;i++) { if(x%i == 0) { if(x/i != i) { c+=2; } else { c++; } } } return c; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(long a[], long x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(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; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); Pair[] pp = new Pair[n]; for(int i = 0;i<n;i++) { pp[i] = new Pair(sc.nextInt(),i+1); } long ans = 0; Arrays.sort(pp); for(int i = 0;i<n;i++) { for(int j = i+1;j<n;j++) { if(1L * pp[i].first * pp[j].first > 2 * n) break; ans += (1L * pp[i].first * pp[j].first == pp[i].second + pp[j].second) ? 1 : 0; } } fout.println(ans); } fout.close(); } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output
PASSED
5cf4deef51216f9b66675d042fbcd7ee
train_107.jsonl
1624635300
You are given an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. Count the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { long first, second; public Pair(long first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return Long.compare(first, ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { 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) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Long> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Long> l = new ArrayList<>(); for (long p=2; p*p<=n; p++) { if (prime[(int)(p)] == true) { for(long i=p*p; i<=n; i += p) { prime[(int)(p)] = false; } } } for (long p=2; p<=n; p++) { if (prime[(int)(p)] == true) { l.add(p); } } return l; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(long a[], long x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(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; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); Pair[] p = new Pair[n]; for(int i = 0;i<n;i++) { p[i] = new Pair(sc.nextInt(),i+1); } Arrays.sort(p); long c = 0; for(int i = 0;i<n;i++) { for(int j = i+1;j<n;j++) { if(p[i].first * p[j].first > p[i].second + n) break; if(p[i].first * p[j].first == p[i].second + p[j].second) c++; } } fout.println(c); } fout.close(); } }
Java
["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2"]
2 seconds
["1\n1\n3"]
NoteFor the first test case, the only pair that satisfies the constraints is $$$(1, 2)$$$, as $$$a_1 \cdot a_2 = 1 + 2 = 3$$$For the second test case, the only pair that satisfies the constraints is $$$(2, 3)$$$.For the third test case, the pairs that satisfy the constraints are $$$(1, 2)$$$, $$$(1, 5)$$$, and $$$(2, 3)$$$.
Java 8
standard input
[ "brute force", "implementation", "math", "number theory" ]
0ce05499cd28f0825580ff48dae9e7a9
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — the array $$$a$$$. It is guaranteed that all elements are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.
1,200
For each test case, output the number of pairs of indices $$$(i, j)$$$ such that $$$i &lt; j$$$ and $$$a_i \cdot a_j = i + j$$$.
standard output