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
0e2a453562d14d409afcd1cb89d66724
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) ///common mistakes // didn't read the question properly public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); //pretty important for sure - out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure //code here int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt(); char[][] inp = new char[n][m]; for(int i= 0; i < n; i++){ inp[i] = sc.nextLine().toCharArray(); } //input is done //now do some pre work for queries int total = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(inp[i][j] == '*') total++; } } //now think brother, what to do next huh? //mark the ending and beginning, and count diversion int inside = 0; int outside = 0; int counter = 0; for(int j = 0; j < m; j++){ for(int i = 0; i < n; i++){ if(inp[i][j] == '*') inside++; counter++; if(counter == total) break; } if(counter == total) break; } outside = total - inside; //or maybe total would work in some way or other, we will see // out.println(inside + " " + outside + " " + total); for(int i = 0; i < q; i++){ int cx = sc.nextInt(); int cy = sc.nextInt(); //now checking if present or not at that pos cx--; cy--; // out.println(cx + n * cy + " hello " + total + " " + inside + " " + outside); // out.println(inp[cy][cy]); if(inp[cx][cy] == '*'){ //just check if inside se hta ya outside se, simple //basically two cases are there simple, solve them bruh int val = cx + n * cy; //converting it to value if(val + 1 <= total) inside--;else outside--; inp[cx][cy] = '.'; //otherwise one final point check should be there for sure int x = (total-1)%n; int y = (total-1)/n; if(inp[x][y] == '*'){ inside--; outside++; } total--; }else{ //just check if inside aaya ya outside simple int val = cx + n * cy; //inside incre or decre if(val + 1 <= total ) inside++; else outside++; inp[cx][cy] = '*'; //one more at that point check guys int x = (total)%n; int y = (total)/n; if(inp[x][y] == '*'){ inside++; outside--; } total++; } //final answer baby out.println(outside); } out.close(); } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; 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/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Long.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; return; //behnchoda return tera baap krvayege? } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } public static class segmentTreeLazy{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; public long[] lazy; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query-range -> O(logn) //lazy update-range -> O(logn) (imp) //simple iteration and stuff for sure public segmentTreeLazy(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO! } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long queryLazy(int s, int e, int qs, int qe, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > qe || e < qs){ return Long.MAX_VALUE; } //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //partial overlap int mid = (s + e)/2; long left = queryLazy(s, mid, qs, qe, 2 * index); long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1); return Math.min(left, right); } //update range in O(logn) -- using lazy array public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > r || l > e){ return; } //another case if(l <= s && e <= r){ tree[index] += inc; //create a new lazy value for children node if(s != e){ lazy[2*index] += inc; lazy[2*index + 1] += inc; } return; } //recursive case int mid = (s + e)/2; updateRangeLazy(s, mid, l, r, inc, 2*index); updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1); //update the tree index tree[index] = Math.min(tree[2*index], tree[2*index + 1]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public 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); } //sort long public static void sort(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); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------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 nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
27b85033f59de80dc3ad25aae5225333
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.util.*; public class a{ public static FastScanner fs; public static BIT tree; public static char[][]grid; public static void main(String args[]) { fs=new FastScanner(); int n=fs.nextInt(); int m=fs.nextInt(); int q=fs.nextInt(); tree=new BIT(n*m); grid=new char[n][m]; int tot=0; for(int i=0;i<n;i++) { grid[i]=fs.next().toCharArray(); for(int j=0;j<m;j++) { if(grid[i][j]=='.') { tree.update((j*n)+(i+1),1); } else { tot++; } } } StringBuilder ans=new StringBuilder(""); while(q-- > 0) { int x,y; x=fs.nextInt(); y=fs.nextInt(); if(grid[--x][--y]=='*') { tot--; grid[x][y]='.'; tree.update((y*n)+(x+1),1); } else { tot++; grid[x][y]='*'; tree.update((y*n)+(x+1),-1); } ans.append(tree.query(tot)); ans.append("\n"); } System.out.println(ans); } static class BIT { public int n,fenwick[]; BIT(int N) { n=N; fenwick=new int[n+1]; } void update(int pos,int val) { while(pos<=n) { fenwick[pos] += val; pos += (pos&(-pos)); } } int query(int pos) { int sum=0; while(pos > 0) { sum += fenwick[pos]; pos -= (pos&(-pos)); } return sum; } } 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(Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
e6ac36d9775b2617a06e8e9f5b6e8ef1
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.lang.Math; import java.lang.reflect.Array; import java.util.*; import javax.swing.text.DefaultStyledDocument.ElementSpec; public final class Solution { static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(System.out) ); static StringTokenizer st; /*write your constructor and global variables here*/ static class sortCond implements Comparator<Pair<Integer, Integer>> { @Override public int compare(Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) { if (p1.a <= p2.a) { return -1; } else { return 1; } } } static class Rec { int a; int b; long c; Rec(int a, int b, long c) { this.a = a; this.b = b; this.c = c; } } static class Pair<f, s> { f a; s b; Pair(f a, s b) { this.a = a; this.b = b; } } interface modOperations { int mod(int a, int b, int mod); } static int findBinaryExponentian(int a, int pow, int mod) { if (pow == 1) { return a; } else if (pow == 0) { return 1; } else { int retVal = findBinaryExponentian(a, (int) pow / 2, mod); int val = (pow % 2 == 0) ? 1 : a; return modMul.mod(modMul.mod(retVal, retVal, mod), val, mod); } } static int findPow(int a, int b, int mod) { if (b == 1) { return a % mod; } else if (b == 0) { return 1; } else { int res = findPow(a, (int) b / 2, mod); return modMul.mod(res, modMul.mod(res, (b % 2 == 1 ? a : 1), mod), mod); } } static int bleft(int ele, int[] sortedArr) { int l = 0; int h = sortedArr.length - 1; int ans = -1; while (l <= h) { int mid = l + (int) (h - l) / 2; if (sortedArr[mid] < ele) { ans = mid; l = mid + 1; } else if (sortedArr[mid] >= ele) { h = mid - 1; } } return ans; } static int gcd(int a, int b) { int div = b; int rem = a % b; while (rem != 0) { int temp = rem; rem = div % rem; div = temp; } return div; } static long[] log(long no, long n) { long i = 1; int cnt = 0; long sum = 0l; long arr[] = new long[2]; while (i < no) { sum += i; cnt++; if (sum == n) { arr[0] = 1l * cnt; arr[1] = sum; break; } i *= 2l; } if (arr[0] == 0) { arr[0] = cnt; arr[1] = sum; } return arr; } static modOperations modAdd = (int a, int b, int mod) -> { return (a % mod + b % mod) % mod; }; static modOperations modSub = (int a, int b, int mod) -> { return (int) ((1l * a % mod - 1l * b % mod + 1l * mod) % mod); }; static modOperations modMul = (int a, int b, int mod) -> { return (int) ((1l * (a % mod) * 1l * (b % mod)) % (1l * mod)); }; static modOperations modDiv = (int a, int b, int mod) -> { return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod); }; static HashSet<Integer> primeList(int MAXI) { int[] prime = new int[MAXI + 1]; HashSet<Integer> obj = new HashSet<>(); for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) { if (prime[i] == 0) { obj.add(i); for (int j = i * i; j <= MAXI; j += i) { prime[j] = 1; } } } for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) { if (prime[i] == 0) { obj.add(i); } } return obj; } static int[] factorialList(int MAXI, int mod) { int[] factorial = new int[MAXI + 1]; factorial[2] = 1; for (int i = 3; i < MAXI + 1; i++) { factorial[i] = modMul.mod(factorial[i - 1], i, mod); } return factorial; } static void put(HashMap<Integer, Integer> cnt, int key) { if (cnt.containsKey(key)) { cnt.replace(key, cnt.get(key) + 1); } else { cnt.put(key, 1); } } static long arrSum(ArrayList<Long> arr) { long tot = 0; for (int i = 0; i < arr.size(); i++) { tot += arr.get(i); } return tot; } static int ord(char b) { return (int) b - (int) 'a'; } static int optimSearch(int[] cnt, int lower_bound, int pow, int n) { int l = lower_bound + 1; int h = n; int ans = 0; while (l <= h) { int mid = l + (h - l) / 2; if (cnt[mid] - cnt[lower_bound] == pow) { return mid; } else if (cnt[mid] - cnt[lower_bound] < pow) { ans = mid; l = mid + 1; } else { h = mid - 1; } } return ans; } static Pair<Long, Integer> ret_ans(ArrayList<Integer> ans) { int size = ans.size(); int mini = 1000000000 + 1; long tit = 0l; for (int i = 0; i < size; i++) { tit += 1l * ans.get(i); mini = Math.min(mini, ans.get(i)); } return new Pair<>(tit - mini, mini); } static int factorList( HashMap<Integer, Integer> maps, int no, int maxK, int req ) { int i = 1; while (i * i <= no) { if (no % i == 0) { if (i != no / i) { put(maps, no / i); } put(maps, i); if (maps.get(i) == req) { maxK = Math.max(maxK, i); } if (maps.get(no / i) == req) { maxK = Math.max(maxK, no / i); } } i++; } return maxK; } static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) { ArrayList<Integer> vals = new ArrayList<>(); for (Map.Entry<Integer, Integer> map : maps.entrySet()) { vals.add(map.getKey()); } return vals; } static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) { ArrayList<Integer> vals = new ArrayList<>(); for (Map.Entry<Integer, Integer> map : maps.entrySet()) { vals.add(map.getValue()); } return vals; } static int getMax(ArrayList<Integer> arr) { int max = arr.get(0); for (int i = 1; i < arr.size(); i++) { if (arr.get(i) > max) { max = arr.get(i); } } return max; } static int getMin(ArrayList<Integer> arr) { int max = arr.get(0); for (int i = 1; i < arr.size(); i++) { if (arr.get(i) < max) { max = arr.get(i); } } return max; } static int list[][] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } }; /*write your methods and classes here*/ static class FT { int[][] fen; int n, m; FT(int n, int m) { this.fen = new int[n + 1][m + 1]; this.n = n; this.m = m; } void uS(int x, int y, int val) { while (x < this.n + 1) { int dy = y; while (dy < this.m + 1) { this.fen[x][dy] += val; dy += (dy & -dy); } x += (x & -x); } } int gS(int x, int y) { int tot = 0; while (x > 0) { int dy = y; while (dy > 0) { tot += this.fen[x][dy]; dy -= (dy & -dy); } x -= (x & -x); } return tot; } } public static void main(String[] args) throws IOException { int cases = 1, n, m, q, i, j; while (cases-- != 0) { st = new StringTokenizer(br.readLine()); n = Integer.parseInt(st.nextToken()); m = Integer.parseInt(st.nextToken()); q = Integer.parseInt(st.nextToken()); char arr[][] = new char[n][m]; FT ft = new FT(n, m); int cnt = 0; for (i = 0; i < n; i++) { arr[i] = br.readLine().toCharArray(); for (j = 0; j < m; j++) { if (arr[i][j] == '.') { ft.uS(i + 1, j + 1, 1); } else { cnt++; } } } for (i = 0; i < q; i++) { st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int val = 0; if (arr[x - 1][y - 1] == '.') { val = 1; arr[x - 1][y - 1] = '*'; } else { val = -1; arr[x - 1][y - 1] = '.'; } cnt += val; ft.uS(x, y, -val); int finalCol = cnt / n; int finalRow = cnt % n; int gs = ft.gS(n, finalCol) + ft.gS(finalRow, finalCol + 1) - ft.gS(finalRow, finalCol); //System.out.println(cnt + " " + finalCol + " " + finalRow + " " + gs); bw.write(Integer.toString(gs) + "\n"); } } bw.flush(); } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
167208027ac9eb75f7440499330e043b
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.util.*; import java.io.*; public class F { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(int arr[],int l1,int r1,int l2,int r2) { int tmp[]=new int[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1); if(l==r) { return; } int mid=(l+r)/2; sort(arr,l,mid); sort(arr,mid+1,r); merge(arr,l,mid,mid+1,r); } public static void merge(long arr[],int l1,int r1,int l2,int r2) { long tmp[]=new long[r2-l1+1]; int indx1=l1,indx2=l2; //sorting the two halves using a tmp array for(int i=0;i<tmp.length;i++) { if(indx1>r1) { tmp[i]=arr[indx2]; indx2++; continue; } if(indx2>r2) { tmp[i]=arr[indx1]; indx1++; continue; } if(arr[indx1]<arr[indx2]) { tmp[i]=arr[indx1]; indx1++; continue; } tmp[i]=arr[indx2]; indx2++; } //Copying the elements of tmp into the main array for(int i=0,j=l1;i<tmp.length;i++,j++) { arr[j]=tmp[i]; } } static class seg_tree { int seg_tree[]; public seg_tree(int n,int arr[]) { seg_tree=new int[4*n]; create_seg_tree(arr,0,0,n-1); } //0 index-Left child-(2*i+1) Right Child-(2*i+2) public void create_seg_tree(int arr[],int vertex,int l,int r) { if(l==r) { seg_tree[vertex]=arr[r]; return; } int mid=(l+r)/2; //Left Child create_seg_tree(arr,(2*vertex)+1,l,mid); //Right Child create_seg_tree(arr,(2*vertex)+2,mid+1,r); //Filling this node seg_tree[vertex]=seg_tree[(2*vertex)+1]+seg_tree[(2*vertex)+2]; } public int sum(int vertex,int l,int r,int ql,int qr) { //ql->query left , qr-> query right l->curr Segmrnt left r->curr segment right if(ql>qr) { return 0; } if(ql==l && qr==r) { return seg_tree[vertex]; } int mid=(l+r)/2; int total=0; //Left Child total+=sum((2*vertex)+1,l,mid,ql,Math.min(qr, mid)); //Right Child total+=sum((2*vertex)+2,mid+1,r,Math.max(mid+1,ql),qr); return total; } public void update(int vertex,int l,int r,int pos,int value) { //pos->Position of the update value->updates value if(l==r) { seg_tree[vertex]=value; return; } int mid=(l+r)/2; //Left Child if(pos<=mid) { update((2*vertex)+1,l,mid,pos,value); } //Right Child else { update((2*vertex)+2,mid+1,r,pos,value); } seg_tree[vertex]=seg_tree[(2*vertex)+1]+seg_tree[(2*vertex)+2]; } } public static void main(String args[]) throws IOException { Scan input=new Scan(); StringBuilder ans=new StringBuilder(""); int n=input.scanInt(); int m=input.scanInt(); int qq=input.scanInt(); int arr[][]=new int[n][m]; int cnt=0; for(int i=0;i<n;i++) { String str=input.scanString(); for(int j=0;j<m;j++) { if(str.charAt(j)=='*') { arr[i][j]=1; cnt++; } } } arr=tp(n,m,arr); int tmp=n; n=m; m=tmp; seg_tree st[]=new seg_tree[n]; int total[]=new int[n]; // for(int i=0;i<n;i++) { // for(int j=0;j<m;j++) { // System.out.print(arr[i][j]+" "); // } // System.out.println(); // } for(int i=0;i<n;i++) { st[i]=new seg_tree(m,arr[i]); total[i]=st[i].sum(0, 0, m-1, 0, m-1); // System.out.println(total[i]); } seg_tree st_total=new seg_tree(n,total); for(int q=1;q<=qq;q++) { int v=input.scanInt()-1; int u=input.scanInt()-1; if(arr[u][v]==0) { arr[u][v]=1; cnt++; st[u].update(0, 0, m-1, v, 1); } else { arr[u][v]=0; cnt--; st[u].update(0, 0, m-1, v, 0); } st_total.update(0, 0, n-1, u, st[u].sum(0, 0, m-1, 0, m-1)); int rows=cnt/m; int nxt=cnt%m; // System.out.println(rows+" "+nxt); if(cnt==(n*m)) { ans.append(0+"\n"); continue; } int fin=0; fin+=st_total.sum(0, 0, n-1, rows+1, n-1); fin+=st[rows].sum(0, 0, m-1, nxt, m-1); ans.append(fin+"\n"); } System.out.print(ans); } public static int[][] tp(int n,int m,int arr[][]) { int brr[][]=new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { brr[i][j] = arr[j][i]; } } return brr; } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
6350cd8bf62429424c35b553cc7dc0f4
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
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.StringTokenizer; public class F1674 { 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 m = in.nextInt(); int q = in.nextInt(); int[] col = new int[m]; char[][] map = new char[n][m]; for (int i = 0; i < n; i++) { String temp = in.next(); map[i] = temp.toCharArray(); } int countStar = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (map[i][j] == '*') { countStar++; col[j]++; } } } // q: 2 * 1e5 // m: 1e3 // n: 1e3 while (q-- > 0) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; if (map[x][y] == '*') { map[x][y] = '.'; countStar--; col[y]--; } else { map[x][y] = '*'; countStar++; col[y]++; } int needCol = countStar / n; int needRow = countStar % n; int temp = 0; for (int i = 0; i < needCol; i++) { temp += col[i]; } for (int i = 0; i < needRow; i++) { temp += map[i][needCol] == '*' ? 1 : 0; } out.println(countStar - temp); } } } 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
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
9988e15d0faea7b5a0b50ccd217d81e7
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static Scanner sc = new Scanner(System.in); public static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { solve(); pw.flush(); } static void solve() { int H = sc.nextInt(); int W = sc.nextInt(); int Q = sc.nextInt(); int cnt = 0; int ans = 0; char[][] s = new char[H][W]; boolean[][] todo = new boolean[H][W]; for( int i = 0; i < H; i++ ) { s[i] = sc.next().toCharArray(); for( int j = 0; j < W; j++ ) { if( s[i][j] == '*' ) cnt++; } } for( int j = 0; j < W; j++ ) { for( int i = 0; i < H; i++ ) { if( j*H+(i+1) <= cnt ) { todo[i][j] = true; if( s[i][j] == '.' ) ans++; } } } for( int q = 0; q < Q; q++ ) { int x = sc.nextInt()-1; int y = sc.nextInt()-1; if( s[x][y] == '*' ) { int r = (cnt-1)%H; int c = (cnt-1)/H; cnt--; ans--; todo[r][c] = false; if( todo[x][y] ) ans++; if( s[r][c] == '*' ) ans++; s[x][y] = '.'; }else { int r = cnt%H; int c = cnt/H; cnt++; ans++; todo[r][c] = true; if( todo[x][y] ) ans--; if( s[r][c] == '*' ) ans--; s[x][y] = '*'; } pw.println(ans); } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
861fd41ecfb3588371361d5ed058634b
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class CodeForces { static private final String INPUT = "input.txt"; static private final String OUTPUT = "output.txt"; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.00000"); final static int mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; final static long INF = Long.MAX_VALUE; final static long NEG_INF = Long.MIN_VALUE; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== input(); preprocess(); int t = 1; // t = readInt(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(), m = readInt(), q = readInt(); char[][] mat2 = readMatrix(n, m); char[][] mat = new char[m][n]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) mat[j][i] = mat2[i][j]; int tmp = n; n = m; m = tmp; int total = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (mat[i][j] == '*') total++; int empty = 0, k = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (++k > total) break; if (mat[i][j] == '.') empty++; } if (k > total) break; } // out.println(total); // out.println(empty); while (q-- > 0) { int y = readInt() - 1, x = readInt() - 1, t = x * m + y + 1; int i = (total - 1) / m, j = (total - 1 + m) % m; if (mat[x][y] == '.') { mat[x][y] = '*'; if (++j == m) { i++; j = 0; } if (t <= total && mat[i][j] == '*') empty--; if (t > total && mat[i][j] == '.') empty++; total++; } else { mat[x][y] = '.'; if (t <= total && mat[i][j] == '*') empty++; if (t > total && mat[i][j] == '.') empty--; total--; } out.println(empty); } } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java // java CodeForces // javac CodeForces.java && java CodeForces // ==================== CUSTOM CLASSES ================================ static class Pair { int first, second; Pair(int f, int s) { first = f; second = s; } public int compareTo(Pair o) { if (this.first == o.first) return this.second - o.second; return this.first - o.first; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Pair other = (Pair) (obj); if (this.first != other.first) return false; if (this.second != other.second) return false; return true; } @Override public int hashCode() { return this.first ^ this.second; } @Override public String toString() { return this.first + " " + this.second; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== private static void input() { FileInputStream instream = null; PrintStream outstream = null; try { instream = new FileInputStream(INPUT); outstream = new PrintStream(new FileOutputStream(OUTPUT)); System.setIn(instream); System.setOut(outstream); } catch (Exception e) { System.err.println("Error Occurred."); } br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray(int n) throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(m); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, int mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static int divide(int a, int b) { return multiply(a, mod_pow(b, mod - 2, mod)); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int i = 2; 1L * i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; 1L * i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) if (primes[j] == j) primes[j] = i; } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } // check if a is subsequence of b private static boolean isSubsequence(String a, String b) { int idx = 0; for (int i = 0; i < b.length() && idx < a.length(); i++) if (a.charAt(idx) == b.charAt(i)) idx++; return idx == a.length(); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ================== public static class SegmentTree { int n; long[] arr, tree, lazy; SegmentTree(long arr[]) { this.arr = arr; this.n = arr.length; this.tree = new long[(n << 2)]; this.lazy = new long[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, long val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, long val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } long query(int l, int r) { return query(1, 0, n - 1, l, r); } long query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0L; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ==================== FENWICK TREE ================================ static class FT { long[] tree; int n; FT(int[] arr, int n) { this.n = n; this.tree = new long[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
c4d3e7fb84c819c047f36ab26c3b3d4b
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class CodeForces { static private final String INPUT = "input.txt"; static private final String OUTPUT = "output.txt"; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.00000"); final static int mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; final static long INF = Long.MAX_VALUE; final static long NEG_INF = Long.MIN_VALUE; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== input(); preprocess(); int t = 1; // t = readInt(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(), m = readInt(), q = readInt(); char[][] mat2 = readMatrix(n, m); char[][] mat = new char[m][n]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) mat[j][i] = mat2[i][j]; int tmp = n; n = m; m = tmp; int total = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (mat[i][j] == '*') total++; int empty = 0, k = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (++k > total) break; if (mat[i][j] == '.') empty++; } if (k > total) break; } // out.println(total); // out.println(empty); while (q-- > 0) { int y = readInt() - 1, x = readInt() - 1, t = x * m + y + 1; int i = (total - 1) / m, j = (total - 1 + m) % m; if (mat[x][y] == '.') { mat[x][y] = '*'; if (++j == m) { i++; j = 0; } if (t <= total && mat[i][j] == '*') empty--; if (t > total && mat[i][j] == '.') empty++; total++; } else { mat[x][y] = '.'; if (t <= total && mat[i][j] == '*') empty++; if (t > total && mat[i][j] == '.') empty--; total--; } out.println(empty); } } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java // java CodeForces // javac CodeForces.java && java CodeForces // ==================== CUSTOM CLASSES ================================ static class Pair { int first, second; Pair(int f, int s) { first = f; second = s; } public int compareTo(Pair o) { if (this.first == o.first) return this.second - o.second; return this.first - o.first; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Pair other = (Pair) (obj); if (this.first != other.first) return false; if (this.second != other.second) return false; return true; } @Override public int hashCode() { return this.first ^ this.second; } @Override public String toString() { return this.first + " " + this.second; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== private static void input() { FileInputStream instream = null; PrintStream outstream = null; try { instream = new FileInputStream(INPUT); outstream = new PrintStream(new FileOutputStream(OUTPUT)); System.setIn(instream); System.setOut(outstream); } catch (Exception e) { System.err.println("Error Occurred."); } br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray(int n) throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(m); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, int mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static int divide(int a, int b) { return multiply(a, mod_pow(b, mod - 2, mod)); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int i = 2; 1L * i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; 1L * i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) if (primes[j] == j) primes[j] = i; } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } // check if a is subsequence of b private static boolean isSubsequence(String a, String b) { int idx = 0; for (int i = 0; i < b.length() && idx < a.length(); i++) if (a.charAt(idx) == b.charAt(i)) idx++; return idx == a.length(); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ================== public static class SegmentTree { int n; long[] arr, tree, lazy; SegmentTree(long arr[]) { this.arr = arr; this.n = arr.length; this.tree = new long[(n << 2)]; this.lazy = new long[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, long val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, long val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } long query(int l, int r) { return query(1, 0, n - 1, l, r); } long query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0L; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ==================== FENWICK TREE ================================ static class FT { long[] tree; int n; FT(int[] arr, int n) { this.n = n; this.tree = new long[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
9fdd278dd56f455f0fe4d7b6d17df69c
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int[] nmq = Arrays.stream(in.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); int n = nmq[0]; int m = nmq[1]; int q = nmq[2]; boolean[] icons = new boolean[n*m]; int count = 0; for (int i = 0; i < n; i++){ String row = in.readLine(); for (int j = 0; j < m; j++){ icons[n*j+i] = row.charAt(j) == '*'; if (icons[n*j+i]) count++; } } int res = count; for (int i = 0; i < count; i++){ if (icons[i]) res--; } for (int i = 0; i < q; i++){ int[] coord = Arrays.stream(in.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray(); int row = coord[0]-1; int col = coord[1]-1; int index = col*n + row; boolean addorsub = !icons[index]; if (addorsub) { if (icons[count]) res--; if (index > count) res++; count++; } else{ if (icons[count-1]) res++; if (index >= count-1) res--; count--; } icons[index] = !icons[index]; System.out.println(res); } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
e97c803afff1849914121299b63864b9
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
// package c1674; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.StringTokenizer; // // Codeforces Round #786 (Div. 3) 2022-05-02 07:35 // F. Desktop Rearrangement // https://codeforces.com/contest/1674/problem/F // time limit per test 3 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a // rectangle matrix of size n x m consisting of characters '.' (empty cell of the desktop) and '*' // (an icon). // // The desktop is called if all its icons are occupying some prefix of full columns and, possibly, // the prefix of the next column (and there are no icons outside this figure). In other words, some // amount of first columns will be filled with icons and, possibly, some amount of first cells of // the next (after the last full column) column will be also filled with icons (and all the icons on // the desktop belong to this figure). This is pretty much the same as the real life icons // arrangement. // // In one move, you can take one icon and move it to any empty cell in the desktop. // // Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to // answer q queries: what is the number of moves required to make the desktop after adding/removing // one icon? // // Note that and change the state of the desktop. // // Input // // The first line of the input contains three integers n, m and q (1 <= n, m <= 1000; 1 <= q <= 2 * // 10^5) -- the number of rows in the desktop, the number of columns in the desktop and the number // of queries, respectively. // // The next n lines contain the description of the desktop. The i-th of them contains m characters // '.' and '*' -- the description of the i-th row of the desktop. // // The next q lines describe queries. The i-th of them contains two integers x_i and y_i (1 <= x_i // <= n; 1 <= y_i <= m) -- the position of the cell which changes its state (if this cell contained // the icon before, then this icon is removed, otherwise an icon appears in this cell). // // Output // // Print q integers. The i-th of them should be the number of moves required to make the desktop // after applying the first i queries. // // Example /* input: 4 4 8 ..** .*.. *... ...* 1 3 2 3 3 1 2 3 3 4 4 3 2 3 2 2 output: 3 4 4 3 4 5 5 5 input: 2 5 5 *...* ***** 1 3 2 2 1 3 1 5 2 3 output: 2 3 3 3 2 */ // public class C1674F { static final int MOD = 998244353; static final Random RAND = new Random(); static int[] solve(char[][] desk, int[][] queries) { int n = desk.length; int m = desk[0].length; int q = queries.length; int[] ans = new int[q]; int total = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (desk[i][j] == '*') { total++; } } } int inner = 0; for (int k = 0; k < total; k++) { int i = k % n; int j = k / n; if (desk[i][j] == '*') { inner++; } } for (int k = 0; k < q; k++) { int i = queries[k][0]; int j = queries[k][1]; if (desk[i][j] == '*') { int ri = (total-1) % n; int rj = (total-1) / n; total--; if (j * n + i < total) { inner--; } if (desk[ri][rj] == '*') { // the shrink excluded another '*' cell as the last inner cell inner--; } desk[i][j] = '.'; } else { total++; int ii = (total-1) % n; int ij = (total-1) / n; if (ii == i && ij == j) { // the insert of * is at the last inner cell inner++; } else { if (j * n + i < total) { inner++; } if (desk[ii][ij] == '*') { // the expansion included another '*' cell as the last inner cell inner++; } } desk[i][j] = '*'; } // System.out.format(" k:%d %d %d total:%d inner:%d\n", k, i, j, total, inner); ans[k] = total - inner; } return ans; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); char[][] desk = new char[n][m]; for (int i = 0; i < n; i++) { String s = in.next(); for (int j = 0; j < m; j++) { desk[i][j] = s.charAt(j); } } int[][] queries = new int[q][2]; for (int i = 0; i < q; i++) { queries[i][0] = in.nextInt() - 1; queries[i][1] = in.nextInt() - 1; } int[] ans = solve(desk, queries); output(ans); } static void output(int[] a) { StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append('\n'); if (sb.length() > 500) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.print(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
2c803799036876c2e36b03eba6aeb901
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class codeforces_786_F { private static void solve(FastIOAdapter in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[] freq = new int[m]; char[][] s = new char[n][]; for (int i = 0; i < n; i++) { char[] charArray = in.next().toCharArray(); s[i] = charArray; } int[][] c = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (s[j][i] == '*') { freq[i]++; c[i][j] = 1; } } } BinaryIndexedTree[] trees = new BinaryIndexedTree[m]; for (int i = 0; i < m; i++) { trees[i] = new BinaryIndexedTree(); trees[i].constructBITree(c[i], n); } BinaryIndexedTree tree = new BinaryIndexedTree(); tree.constructBITree(freq, m); for (int i = 0; i < q; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; if (c[y][x] == 1) { c[y][x] = 0; freq[y]--; tree.updateBIT(m, y, -1); trees[y].updateBIT(n, x, -1); } else { c[y][x] = 1; freq[y]++; tree.updateBIT(m, y, 1); trees[y].updateBIT(n, x, 1); } int all = tree.getSum(m - 1); int full = all / n; int rest = all % n; int good = 0; if (full > 0) good += tree.getSum(full - 1); if (rest > 0) good += trees[full].getSum(rest - 1); out.println(all - good); } } static class BinaryIndexedTree { // Max tree size final static int MAX = 2000; public int BITree[] = new int[MAX]; int getSum(int index) { int sum = 0; index = index + 1; while (index > 0) { sum += BITree[index]; index -= index & (-index); } return sum; } public void updateBIT(int n, int index, int val) { index = index + 1; while (index <= n) { BITree[index] += val; index += index & (-index); } } void constructBITree(int arr[], int n) { for (int i = 1; i <= n; i++) BITree[i] = 0; for (int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } } 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
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
e26ea4fddcc3ecaed4cacc63c0005174
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.util.*; public class F { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub solve(0); } private static void solve(int t) { int m = sc.nextInt(); int n = sc.nextInt(); int q = sc.nextInt(); sc.nextLine(); char [][] arr = new char [m][]; for (int i = 0; i < m; ++i) { arr[i] = sc.nextLine().toCharArray(); } int [] numArr = new int [m*n + 1]; int [] bit = new int [m*n + 1]; int idx = 1; int total = 0; //System.out.println(Arrays.deepToString(arr)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { numArr[idx++] = arr[j][i] == '*' ? 1 : 0; total += arr[j][i] == '*' ? 1 : 0; } } for (int i = 1; i < numArr.length; ++i) { if (numArr[i] == 1) { addToBit(bit , i, 1); } } int r, c; int diff; StringBuilder sb = new StringBuilder(); for (int i = 0; i < q; ++i) { r = sc.nextInt(); c = sc.nextInt(); idx = r + (c-1)*m; diff = numArr[idx] == 1 ? -1 : 1; total += diff; numArr[idx] = 1 - numArr[idx]; addToBit(bit, idx, diff); sb.append(total - getBitVal(bit , total)); sb.append("\n"); //sb.append(idx + " " + total + " " + Arrays.toString(numArr)); //sb.append("\n"); } System.out.print(sb); } private static void addToBit(int [] bit, int idx, int val) { for (int i = idx ; i < bit.length; i += (i & -i) ) { bit[i] += val; } } private static int getBitVal(int [] bit, int idx) { int result = 0; for (int i = idx; i > 0; i -= (i & -i)) { result += bit[i]; } return result; } public static void print(int test, long result) { System.out.println("Case #" + test + ": " + result); } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
b5dd5338c1279ac9d0fc62216b368d80
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.util.*; public class q6 { public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // public static long mod = 1000000007; static int[] farr; public static void update(int idx,int val){ while(idx < farr.length){ farr[idx] += val; idx += (idx & (-idx)); } } public static int query(int idx){ int ans = 0; while(idx > 0){ ans += farr[idx]; idx -= (idx & (-idx)); } return ans; } public static void solve() throws Exception { String[] parts = br.readLine().split(" "); int n = Integer.parseInt(parts[0]); int m = Integer.parseInt(parts[1]); int q = Integer.parseInt(parts[2]); char[][] arr = new char[n][m]; for(int i = 0;i < n;i++){ String str = br.readLine(); for(int j = 0;j < m;j++){ arr[i][j] = str.charAt(j); } } int count = 0; int[] psum = new int[m]; for(int j = 0;j < m;j++){ int c = 0; for(int i = 0;i < n;i++){ if(arr[i][j] == '*') c++; } psum[j] = c; count += c; } farr = new int[m + 1]; for(int i = 0;i < m;i++){ update(i + 1,psum[i]); } for(int i = 0;i < q;i++){ parts = br.readLine().split(" "); int x = Integer.parseInt(parts[0]) - 1; int y = Integer.parseInt(parts[1]) - 1; if(arr[x][y] == '.'){ arr[x][y] = '*'; count++; psum[y]++; update(y + 1,1); }else{ arr[x][y] = '.'; count--; psum[y]--; update(y + 1,-1); } int val = count / n; int extra = count % n; // System.out.println(val); int ans = 0; if(val > 0) ans += query(val); for(int j = 0;j < extra;j++) if(arr[j][val] == '*') ans++; System.out.println(count - 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
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
aee5d1bc901b2e1746bb9bf69e5b68be
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { static int sum(int idx , int bit[]) { int ans = 0; while(idx > 0) { ans += bit[idx]; idx -= idx&(-idx); } return ans; } static void update(int n , int idx , int val , int bit[]) { while(idx <= n) { bit[idx] += val;; idx += idx&(-idx); } } public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken()); int a[][] = new int[n+1][m+1]; // sc.nextLine(); int b1[][] = new int[m+1][n+1]; int b2[] = new int[m+1]; int cnt = 0; for(int i = 1 ; i <= n ; i++) { String s = br.readLine(); for(int j = 1 ; j <= m ; j++) { if(s.charAt(j-1) == '*') { a[i][j] = 1; update(n,i,1,b1[j]); cnt++; } } } for(int i = 1 ; i <= m ; i++) { update(m,i,sum(n,b1[i]),b2); } StringBuffer str = new StringBuffer(""); while(q-- > 0) { st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()); int j = Integer.parseInt(st.nextToken()); int up = 1; if(a[i][j] == 1) up = -1; a[i][j] += up; if(up == 1) cnt++; else cnt--; update(n,i,up,b1[j]); update(m,j,up,b2); int x = 0; if(cnt%n == 0) { x = sum(cnt/n,b2); } else { x = sum(cnt/n,b2)+sum(cnt%n,b1[cnt/n+1]); } str.append(cnt-x); str.append(System.lineSeparator()); } System.out.println(str); } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
f81877f1dc410681aa36b60945d64990
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]),q=Integer.parseInt(s[2]); boolean icon[][]=new boolean[n][m]; int i,j,tot=0; bit=new int[n*m+1]; for(i=0;i<n;i++) { String st=bu.readLine(); for(j=0;j<m;j++) { icon[i][j]=st.charAt(j)=='*'; if(icon[i][j]) { tot++; update(j*n+i,1,n*m); } } } while(q-->0) { s=bu.readLine().split(" "); int x=Integer.parseInt(s[0])-1,y=Integer.parseInt(s[1])-1; if(icon[x][y]) {update(y*n+x,-1,n*m); tot--;} else {update(y*n+x,1,n*m); tot++;} icon[x][y]=!icon[x][y]; int place=query(tot); sb.append((tot-place)+"\n"); } System.out.print(sb); } static int bit[]; static void update(int i,int v,int n) { i++; while(i<=n) { bit[i]+=v; i+=i&-i; } } static int query(int i) { int s=0; while(i>0) { s+=bit[i]; i-=i&-i; } return s; } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
769301f209dcacac018605fedf52ebfd
train_107.jsonl
1651502100
Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.
256 megabytes
import java.io.*; import java.util.*; public class CF1674F extends PrintWriter { CF1674F() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1674F o = new CF1674F(); o.main(); o.flush(); } int[] ft; void update(int i, int n, int x) { while (i < n) { ft[i] += x; i |= i + 1; } } int query(int i) { int x = 0; while (i >= 0) { x += ft[i]; i &= i + 1; i--; } return x; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt(); byte[][] cc = new byte[n][]; for (int i = 0; i < n; i++) { cc[i] = sc.next().getBytes(); for (int j = 0; j < m; j++) cc[i][j] = (byte) (cc[i][j] == '.' ? 0 : 1); } ft = new int[n * m]; int k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (cc[i][j] == 1) { update(j * n + i, n * m, 1); k++; } while (q-- > 0) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; int x = cc[i][j] == 0 ? 1 : -1; cc[i][j] ^= 1; update(j * n + i, n * m, x); k += x; println(k - query(k - 1)); } } }
Java
["4 4 8\n..**\n.*..\n*...\n...*\n1 3\n2 3\n3 1\n2 3\n3 4\n4 3\n2 3\n2 2", "2 5 5\n*...*\n*****\n1 3\n2 2\n1 3\n1 5\n2 3"]
3 seconds
["3\n4\n4\n3\n4\n5\n5\n5", "2\n3\n3\n3\n2"]
null
Java 11
standard input
[ "data structures", "greedy", "implementation" ]
9afb205f542c0d8ba4f7fa03faa617ae
The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively. The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop. The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).
1,800
Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.
standard output
PASSED
34b2b386e2c669ba49d4520239e5c97d
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; import java.util.concurrent.TimeUnit; import java.io.*; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class G_Remove_Directed_Edges{ public static void solve(){ } public static void main(String args[])throws IOException, ParseException{ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); Graph g =new Graph(n); for(int i=0;i<m;i++){ int u=sc.nextInt(); int v=sc.nextInt(); g.addDirectedEdge(u,v,-1); } g.solve(); } public static <K,V> Map<K,V> getLimitedSizedCache(int size){ /*Returns an unlimited sized map*/ if(size==0){ return (LinkedHashMap<K, V>) Collections.synchronizedMap(new LinkedHashMap<K, V>()); } /*Returns the map with the limited size*/ Map<K, V> linkedHashMap = Collections.synchronizedMap(new LinkedHashMap<K, V>() { protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > size; } }); return linkedHashMap; } } class BinarySearch<T extends Comparable<T>> { T ele[]; int n; public BinarySearch(T ele[],int n){ this.ele=(T[]) ele; Arrays.sort(this.ele); this.n=n; } public int lower_bound(T x){ //Return next smallest element greater than ewqual to the current element int left=0; int right=n-1; while(left<=right){ int mid=left+(right-left)/2; if(x.compareTo(ele[mid])==0)return mid; if(x.compareTo(ele[mid])>0)left=mid+1; else right=mid-1; } if(left ==n)return -1; return left; } public int upper_bound(T x){ //Returns the highest element lss than equal to the current element int left=0; int right=n-1; while(left<=right){ int mid=left+(right-left)/2; if(x.compareTo(ele[mid])==0)return mid; if(x.compareTo(ele[mid])>0)left=mid+1; else right=mid-1; } return right; } } class Data implements Comparable<Data>{ int num; public Data(int num){ this.num=num; } public int compareTo(Data o){ return -o.num+num; } public String toString(){ return num+" "; } } class Binary{ public String convertToBinaryString(long ele){ StringBuffer res=new StringBuffer(); while(ele>0){ if(ele%2==0)res.append(0+""); else res.append(1+""); ele=ele/2; } return res.reverse().toString(); } } class FenwickTree{ int bit[]; int size; FenwickTree(int n){ this.size=n; bit=new int[size]; } public void modify(int index,int value){ while(index<size){ bit[index]+=value; index=(index|(index+1)); } } public int get(int index){ int ans=0; while(index>=0){ ans+=bit[index]; index=(index&(index+1))-1; } return ans; } } class PAndC{ long c[][]; long mod; public PAndC(int n,long mod){ c=new long[n+1][n+1]; this.mod=mod; build(n); } public void build(int n){ for(int i=0;i<=n;i++){ c[i][0]=1; c[i][i]=1; for(int j=1;j<i;j++){ c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod; } } } } class Trie{ int trie[][]; int revind[]; int root[]; int tind,n; int sz[]; int drev[]; public Trie(){ trie=new int[1000000][2]; root=new int[600000]; sz=new int[1000000]; tind=0; n=0; revind=new int[1000000]; drev=new int[20]; } public void add(int ele){ // System.out.println(root[n]+" "); n++; tind++; revind[tind]=n; root[n]=tind; addimpl(root[n-1],root[n],ele); } public void addimpl(int prev_root,int cur_root,int ele){ for(int i=18;i>=0;i--){ int edge=(ele&(1<<i))>0?1:0; trie[cur_root][1-edge]=trie[prev_root][1-edge]; sz[cur_root]=sz[trie[cur_root][1-edge]]; tind++; drev[i]=cur_root; revind[tind]=n; trie[cur_root][edge]=tind; cur_root=tind; prev_root=trie[prev_root][edge]; } sz[cur_root]+=sz[prev_root]+1; for(int i=0;i<=18;i++){ sz[drev[i]]=sz[trie[drev[i]][0]]+sz[trie[drev[i]][1]]; } } public void findmaxxor(int l,int r,int x){ int ans=0; int cur_root=root[r]; for(int i=18;i>=0;i--){ int edge=(x&(1<<i))>0?1:0; if(revind[trie[cur_root][1-edge]]>=l){ cur_root=trie[cur_root][1-edge]; ans+=(1-edge)*(1<<i); }else{ cur_root=trie[cur_root][edge]; ans+=(edge)*(1<<i); } } System.out.println(ans); } public void findKthStatistic(int l,int r,int k){ //System.out.println("In 3"); int curr=root[r]; int curl=root[l-1]; int ans=0; for(int i=18;i>=0;i--){ for(int j=0;j<2;j++){ if(sz[trie[curr][j]]-sz[trie[curl][j]]<k) k-=sz[trie[curr][j]]-sz[trie[curl][j]]; else{ curr=trie[curr][j]; curl=trie[curl][j]; ans+=(j)*(1<<i); break; } } } System.out.println(ans); } public void findSmallest(int l,int r,int x){ //System.out.println("In 4"); int curr=root[r]; int curl=root[l-1]; int countl=0,countr=0; // System.out.println(curl+" "+curr); for(int i=18;i>=0;i--){ int edge=(x&(1<<i))>0?1:0; // System.out.println(trie[curl][edge]+" "+trie[curr][edge]+" "+sz[curl]+" "+sz[curr]); if(edge==1){ countr+=sz[trie[curr][0]]; countl+=sz[trie[curl][0]]; } curr=trie[curr][edge]; curl=trie[curl][edge]; } countl+=sz[curl]; countr+=sz[curr]; System.out.println(countr-countl); } } class Printer{ public <T> T printArray(T obj[] ,String details){ System.out.println(details); for(int i=0;i<obj.length;i++) System.out.print(obj[i]+" "); System.out.println(); return obj[0]; } public <T> void print(T obj,String details){ System.out.println(details+" "+obj); } } class Node{ long weight; int vertex; public Node(int vertex,long weight){ this.vertex=vertex; this.weight=weight; } public String toString(){ return vertex+" "+weight; } } class Graph{ int nv; //0 indexing i.e vertices starts from 0 input as 1 indexed for add Edge List<List<Node>> adj; boolean visited[]; // Section for input required data storages int dp[]; int in[]; int out[]; public Graph(int n){ adj=new ArrayList<>(); this.nv=n; this.dp=new int[n]; this.in=new int[n]; this.out=new int[n]; // visited=new boolean[nv]; for(int i=0;i<n;i++){ adj.add(new ArrayList<Node>()); dp[i]=-1; } } public void addEdge(int u,int v,long weight){ u--;v--; Node first=new Node(v,weight); Node second=new Node(u,weight); adj.get(v).add(second); adj.get(u).add(first); } public void addDirectedEdge(int u,int v,long weight){ u--;v--; Node first=new Node(v,weight); in[v]++; out[u]++; adj.get(u).add(first); } public void dfscheck(int u,long curweight){ visited[u]=true; for(Node i:adj.get(u)){ if(visited[i.vertex]==false&&(i.weight|curweight)==curweight) dfscheck(i.vertex,curweight); } } long maxweight; public void clear(){ this.adj=null; this.nv=0; } public void solve(){ int ans=1; for(int i=0;i<nv;i++){ if(out[i]>=2){ for(Node v:adj.get(i)) ans=Math.max(ans,1+caldfs(v.vertex)); // System.out.println(i+" "+ans); } } // System.out.println(" The dp array "); // for(int i=0;i<nv;i++){ // System.out.print(dp[i]+" "); // } System.out.println("\n"+ans); } private int caldfs(int u){ if(dp[u]!=-1)return dp[u]; if(in[u]>=2&&out[u]>=2){ dp[u]=1; for(Node v:adj.get(u)){ dp[u]=Math.max(dp[u],1+caldfs(v.vertex)); } } else if(in[u]>=2){ dp[u]=1; } else { dp[u]=Integer.MIN_VALUE; } return dp[u]; } // public void solve() { // maxweight=(1l<<32)-1; // dfsutil(31); // System.out.println(maxweight); // } // public void dfsutil(int msb){ // if(msb<0)return; // maxweight-=(1l<<msb); // visited=new boolean[nv]; // dfscheck(0,maxweight); // for(int i=0;i<nv;i++) // { // if(visited[i]==false) // {maxweight+=(1<<msb); // break;} // } // dfsutil(msb-1); // } // public boolean TopologicalSort() { // top=new int[nv]; // int cnt=0; // int indegree[]=new int[nv]; // for(int i=0;i<nv;i++){ // for(int j:adj.get(i)){ // indegree[j]++; // } // } // Deque<Integer> q=new LinkedList<Integer>(); // for(int i=0;i<nv;i++){ // if(indegree[i]==0){ // q.addLast(i); // } // } // while(q.size()>0){ // int tele=q.pop(); // top[tele]=cnt++; // for(int j:adj.get(tele)){ // indegree[j]--; // if(indegree[j]==0) // q.addLast(j); // } // } // return cnt==nv; // } // public boolean isBipartiteGraph(){ // col=new Integer[nv]; // visited=new boolean[nv]; // for(int i=0;i<nv;i++){ // if(visited[i]==false){ // col[i]=0; // dfs(i); // } // } } class DSU{ int []parent; int rank[]; int n; public DSU(int n){ this.n=n; parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++) { parent[i]=i; rank[i]=1; } } public int find(int i){ if(parent[i]==i)return i; return parent[i]=find(parent[i]); } public boolean union(int a,int b){ int pa=find(a); int pb=find(b); if(pa==pb)return false; if(rank[pa]>rank[pb]){ parent[pb]=pa; rank[pa]+=rank[pb]; } else{ parent[pa]=pb; rank[pb]+=rank[pa]; } return true; } } class SegmentTree{ long tree[]; long data[]; int tsize; int dsize; public SegmentTree(long data[],int n){ this.tsize=4*n+1; this.dsize=n; this.data=data; this.tree=new long[tsize]; build(0,n-1,0); } public SegmentTree(int n,long def){ this.tsize=4*n+1; this.dsize=n; this.data=new long[n]; for(int i=0;i<n;i++){ data[i]=def; } this.tree=new long[tsize]; build(0,n-1,0); } public void build(int l,int r,int treeindex){ if(l==r){ tree[treeindex]=data[l]; return ; } int mid=(l+r)/2; build(l,mid,2*treeindex+1); build(mid+1,r,2*treeindex+2); tree[treeindex]=Math.max(tree[2*treeindex+1],tree[2*treeindex+2]); } public void updateOneImpl(int l,int r,int tind,int dind){ if(l==r&&l==dind){ tree[tind]=data[dind]; return ; } if(dind>=l&&dind<=r){ int mid=(l+r)/2; updateOneImpl(l,mid,2*tind+1,dind); updateOneImpl(mid+1,r,2*tind+2,dind); tree[tind]=Math.max(tree[2*tind+1],tree[2*tind+2]); } // System.out.println("In range "+l+" "+r+" "+tree[tind]); } public void updateOne(int index,long value){ data[index]=value; updateOneImpl(0,dsize-1,0,index); } public long getRangeValueImpl(int ql,int qr,int tl,int tr,int tind){ if(tr<ql||qr<tl){ return Long.MIN_VALUE; } if(qr>=tr&&ql<=tl)return tree[tind]; int mid=(tl+tr)/2; long l=getRangeValueImpl(ql, qr, tl, mid, 2*tind+1); long r=getRangeValueImpl(ql, qr, mid+1, tr, 2*tind+2); //System.out.println("In range "+tl+" "+tr+" "+Math.max(l,r)); return Math.max(l,r); } public long getRangeValue(int l,int r){ long temp= getRangeValueImpl(l,r, 0, dsize-1, 0); // System.out.println(" Max Value in between "+l+" "+r+" = "+temp); return temp; } public void printData(){ System.out.println("The Data After updation"); for(int i=0;i<dsize;i++){ System.out.print(data[i]+" "); } System.out.println(); // System.out.println(" The Tree After Updation"); // for(int i=0;i<tsize;i++){ // System.out.print(tree[i]+" "); // } // System.out.println(); } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
3e53ae52dc378e1c3f2d96e3f8bf3cec
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
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= 10000_0000_7; static int dp[]; static int fake[]; static int in[]; static List<Integer> adj[]; 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=1; outer:for(int time=1;time<=t;time++) { int n=fs.nextInt(), m=fs.nextInt(); adj=new ArrayList[n+1]; in=new int[n+1]; dp=new int[n+1]; fake=new int[n+1]; for(int i=0;i<=n;i++) adj[i]=new ArrayList<>(); for(int i=0;i<m;i++) { int u=fs.nextInt(), v=fs.nextInt(); adj[u].add(v); in[v]++; } Arrays.fill(dp, -1); int ans=1; for(int i=1;i<=n;i++) { if(dp[i]==-1) find(i); } for(int i=1;i<=n;i++) ans=Math.max(dp[i], ans); out.println(ans); } out.close(); } static int find(int cur) { if(dp[cur]!=-1) { if(in[cur]==1) return 0; return dp[cur]; } dp[cur]=1; if(adj[cur].size()<2) { if(in[cur]==1) { return 0; } return 1; } List<Integer> list=new ArrayList<>(adj[cur].size()); for(int c:adj[cur]) { list.add(find(c)); } Collections.sort(list); dp[cur]=Math.max(dp[cur], 1+list.get(list.size()-1)); if(in[cur]==1) { return 0; } return dp[cur]; } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
6d2e2e460d2c369609c2e3ef14d6d451
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
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 G { static ArrayList<Integer>[]adj; static int[]dp,in,ot; public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(); adj=new ArrayList[n]; for(int i=0;i<n;i++)adj[i]=new ArrayList<Integer>(); in=new int[n]; ot=new int[n]; dp=new int[n]; Arrays.fill(dp, -1); for(int i=0;i<m;i++) { int u=sc.nextInt()-1,v=sc.nextInt()-1; adj[u].add(v); in[v]++;ot[u]++; } int mx=0; for(int i=0;i<n;i++) { mx=Math.max(mx, dp(i)); } out.println(mx); out.close(); } private static int dp(int i) { if(dp[i]!=-1)return dp[i]; int ans=1; if(ot[i]==1) { return dp[i]=in[i]>1?1:0; } for(int v:adj[i]) { if(in[v]>1) ans=Math.max(ans,1+dp(v)); } return dp[i]=ans; } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
8c4410758425904894f0629f551940f1
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
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 G { static ArrayList<Integer>[]adj; static int[]dp,in,ot; public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(); adj=new ArrayList[n]; for(int i=0;i<n;i++)adj[i]=new ArrayList<Integer>(); in=new int[n]; ot=new int[n]; dp=new int[n]; Arrays.fill(dp, -1); for(int i=0;i<m;i++) { int u=sc.nextInt()-1,v=sc.nextInt()-1; adj[u].add(v); in[v]++;ot[u]++; } int mx=0; for(int i=0;i<n;i++) { mx=Math.max(mx, dp(i)); } out.println(mx); out.close(); } private static int dp(int i) { if(dp[i]!=-1)return dp[i]; int mn=Math.min(in[i], ot[i]); int mx=Math.max(in[i], ot[i]); //if(mn==1||(mn==0&&mx==1))return dp[i]=0 // if(ot[i]+in[i]==0)return dp[i]=0; int ans=1; if(ot[i]==1) { return dp[i]=in[i]>1?1:0; } for(int v:adj[i]) { if(in[v]>1) ans=Math.max(ans,1+dp(v)); } return dp[i]=ans; } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
4e0a3369e2371884222c5dc9c6b64dc6
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class RemoveDirectedEdges { public static void solve(FastIO io) { final int N = io.nextInt(); final int M = io.nextInt(); Node[] nodes = new Node[N + 1]; for (int i = 1; i <= N; ++i) { nodes[i] = new Node(i); } for (int i = 0; i < M; ++i) { final int U = io.nextInt(); final int V = io.nextInt(); nodes[U].next.add(nodes[V]); ++nodes[V].inDegree; } int[] memo = new int[N + 1]; Arrays.fill(memo, -1); int best = 1; for (int i = 1; i <= N; ++i) { if (nodes[i].next.size() <= 1) { continue; } for (Node v : nodes[i].next) { best = Math.max(best, 1 + asConnector(v, memo)); } } io.println(best); } private static int asConnector(Node u, int[] memo) { if (memo[u.id] < 0) { if (u.inDegree <= 1) { memo[u.id] = 0; } else if (u.next.size() == 1) { memo[u.id] = 1; } else { int bestNext = 0; for (Node v : u.next) { bestNext = Math.max(bestNext, asConnector(v, memo)); } memo[u.id] = 1 + bestNext; } } return memo[u.id]; } private static class Node { public int id; public ArrayList<Node> next = new ArrayList<>(); public int inDegree = 0; public Node(int id) { this.id = id; } } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
e566121574e5dfc07d40aaf6346d67c9
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class RemoveDirectedEdges { public static void solve(FastIO io) { final int N = io.nextInt(); final int M = io.nextInt(); Node[] nodes = new Node[N + 1]; for (int i = 1; i <= N; ++i) { nodes[i] = new Node(i); } for (int i = 0; i < M; ++i) { final int U = io.nextInt(); final int V = io.nextInt(); nodes[U].next.add(nodes[V]); nodes[V].prev.add(nodes[U]); } int[] memo = new int[N + 1]; Arrays.fill(memo, -1); int best = 1; for (int i = 1; i <= N; ++i) { if (nodes[i].next.size() <= 1) { continue; } for (Node v : nodes[i].next) { best = Math.max(best, 1 + asConnector(v, memo)); } } io.println(best); } // private static int asSource(Node u, int[] memo) { // if (memo[u.id] < 0) { // // } // return memo[u.id]; // } private static int asConnector(Node u, int[] memo) { if (memo[u.id] < 0) { if (u.prev.size() <= 1) { memo[u.id] = 0; } else if (u.next.size() == 1) { memo[u.id] = 1; } else { int bestNext = 0; for (Node v : u.next) { bestNext = Math.max(bestNext, asConnector(v, memo)); } memo[u.id] = 1 + bestNext; } } return memo[u.id]; } private static class Node { public int id; public ArrayList<Node> next = new ArrayList<>(); public ArrayList<Node> prev = new ArrayList<>(); public Node(int id) { this.id = id; } } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
ee80384bcf8eb5e8336a764a43ab7d9d
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; import java.io.*; public class Main { static long startTime = System.currentTimeMillis(); // for global initializations and methods starts here static List<List<Integer>> graph; static List<Integer> ordered; static boolean[] visitedBy; static void initializeGraph(int size) { graph = new ArrayList<>(); for (int i = 0; i < size; i++) graph.add(new ArrayList<>()); } static void dfs(int src) { visitedBy[src] = true; for (int node : graph.get(src)) { if (!visitedBy[node]) { dfs(node); } } ordered.add(src); } // global initialisations and methods end here static void run() { boolean tc = false; AdityaFastIO r = new AdityaFastIO(); //FastReader r = new FastReader(); try (OutputStream out = new BufferedOutputStream(System.out)) { //long startTime = System.currentTimeMillis(); int testcases = tc ? r.ni() : 1; int tcCounter = 1; // Hold Here Sparky------------------->>> // Solution Starts Here start: while (testcases-- > 0) { int n = r.ni(); int m = r.ni(); initializeGraph(n + 5); int[] inner = new int[n + 5]; int[] outer = new int[n + 5]; visitedBy = new boolean[n + 5]; ordered = new ArrayList<>(); for (int i = 0; i < m; i++) { int u = r.ni() - 1; int v = r.ni() - 1; graph.get(u).add(v); outer[u]++; inner[v]++; } for (int i = 0; i < n; i++) { if (!visitedBy[i]) { dfs(i); } } int[] dp = new int[n + 5]; for (int ele : ordered) { dp[ele] = 1; for (int node : graph.get(ele)) { if (outer[ele] > 1 && inner[node] > 1) { dp[ele] = Math.max(dp[ele], dp[node] + 1); } } } int ans = Arrays.stream(dp).max().getAsInt(); out.write((ans + " ").getBytes()); out.write(("\n").getBytes()); } // Solution Ends Here } catch (IOException e) { e.printStackTrace(); } } static class AdityaFastIO { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public BufferedReader br; public StringTokenizer st; public AdityaFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public AdityaFastIO(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String readLine() throws IOException { byte[] buf = new byte[100000001]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int ni() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nl() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nd() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws Exception { run(); } static int[] readIntArr(int n, AdityaFastIO r) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = r.ni(); return arr; } static long[] readLongArr(int n, AdityaFastIO r) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = r.nl(); return arr; } static List<Integer> readIntList(int n, AdityaFastIO r) throws IOException { List<Integer> al = new ArrayList<>(); for (int i = 0; i < n; i++) al.add(r.ni()); return al; } static List<Long> readLongList(int n, AdityaFastIO r) throws IOException { List<Long> al = new ArrayList<>(); for (int i = 0; i < n; i++) al.add(r.nl()); return al; } static long mod = 998244353; static long modInv(long base, long e) { long result = 1; base %= mod; while (e > 0) { if ((e & 1) > 0) result = result * base % mod; base = base * base % mod; e >>= 1; } return result; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int ni() { return Integer.parseInt(word()); } long nl() { return Long.parseLong(word()); } double nd() { return Double.parseDouble(word()); } } static int MOD = (int) (1e9 + 7); static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = result * x % MOD; n = n / 2; x = x * x % MOD; } return result; } static long powerStrings(int i1, int i2) { String sa = String.valueOf(i1); String sb = String.valueOf(i2); long a = 0, b = 0; for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD; for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1); return powerLL(a, b); } static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static long lower_bound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] >= x) r = m; else l = m; } return r; } static int upper_bound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] <= x) l = m; else r = m; } return l + 1; } static void addEdge(List<List<Integer>> graph, int edge1, int edge2) { graph.get(edge1).add(edge2); graph.get(edge2).add(edge1); } public static class Pair implements Comparable<Pair> { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair o) { // TODO Auto-generated method stub if (this.first != o.first) return (int) (this.first - o.first); else return (int) (this.second - o.second); } } public static class PairC<X, Y> implements Comparable<PairC> { X first; Y second; public PairC(X first, Y second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(PairC o) { // TODO Auto-generated method stub return o.compareTo((PairC) first); } } static boolean isCollectionsSorted(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false; return true; } static boolean isCollectionsSortedReverseOrder(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false; return true; } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
dae8c56d325a5ee708f57c2a4b631b14
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; import java.io.*; public class Main { static long startTime = System.currentTimeMillis(); // for global initializations and methods starts here static List<List<Integer>> graph; static List<Integer> ordered; static boolean[] visitedBy; static void initializeGraph(int size) { graph = new ArrayList<>(); for (int i = 0; i < size; i++) graph.add(new ArrayList<>()); } static void dfs(int src) { visitedBy[src] = true; for (int node : graph.get(src)) { if (!visitedBy[node]) { dfs(node); } } ordered.add(src); } // global initialisations and methods end here static void run() { boolean tc = false; AdityaFastIO r = new AdityaFastIO(); //FastReader r = new FastReader(); try (OutputStream out = new BufferedOutputStream(System.out)) { //long startTime = System.currentTimeMillis(); int testcases = tc ? r.ni() : 1; int tcCounter = 1; // Hold Here Sparky------------------->>> // Solution Starts Here start: while (testcases-- > 0) { int n = r.ni(); int m = r.ni(); initializeGraph(n + 5); int[] inner = new int[n + 5]; int[] outer = new int[n + 5]; visitedBy = new boolean[n + 5]; ordered = new ArrayList<>(); for (int i = 0; i < m; i++) { int u = r.ni() - 1; int v = r.ni() - 1; graph.get(u).add(v); outer[u]++; inner[v]++; } for (int i = 0; i < n; i++) { if (!visitedBy[i]) { dfs(i); } } int[] dp = new int[n + 5]; for (int ele : ordered) { dp[ele] = 1; for (int node : graph.get(ele)) { if (outer[ele] > 1 && inner[node] > 1) { dp[ele] = Math.max(dp[ele], dp[node] + 1); } } } int ans = Arrays.stream(dp).max().getAsInt(); out.write((ans + " ").getBytes()); out.write(("\n").getBytes()); } // Solution Ends Here } catch (IOException e) { e.printStackTrace(); } } static class AdityaFastIO { final private int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public BufferedReader br; public StringTokenizer st; public AdityaFastIO() { br = new BufferedReader(new InputStreamReader(System.in)); din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public AdityaFastIO(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String readLine() throws IOException { byte[] buf = new byte[100000001]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int ni() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nl() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nd() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws Exception { run(); } static int[] readIntArr(int n, AdityaFastIO r) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = r.ni(); return arr; } static long[] readLongArr(int n, AdityaFastIO r) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = r.nl(); return arr; } static List<Integer> readIntList(int n, AdityaFastIO r) throws IOException { List<Integer> al = new ArrayList<>(); for (int i = 0; i < n; i++) al.add(r.ni()); return al; } static List<Long> readLongList(int n, AdityaFastIO r) throws IOException { List<Long> al = new ArrayList<>(); for (int i = 0; i < n; i++) al.add(r.nl()); return al; } static long mod = 998244353; static long modInv(long base, long e) { long result = 1; base %= mod; while (e > 0) { if ((e & 1) > 0) result = result * base % mod; base = base * base % mod; e >>= 1; } return result; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String word() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String line() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int ni() { return Integer.parseInt(word()); } long nl() { return Long.parseLong(word()); } double nd() { return Double.parseDouble(word()); } } static int MOD = (int) (1e9 + 7); static long powerLL(long x, long n) { long result = 1; while (n > 0) { if (n % 2 == 1) result = result * x % MOD; n = n / 2; x = x * x % MOD; } return result; } static long powerStrings(int i1, int i2) { String sa = String.valueOf(i1); String sb = String.valueOf(i2); long a = 0, b = 0; for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD; for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1); return powerLL(a, b); } static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, a); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static long lower_bound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] >= x) r = m; else l = m; } return r; } static int upper_bound(int[] arr, int x) { int l = -1, r = arr.length; while (l + 1 < r) { int m = (l + r) >>> 1; if (arr[m] <= x) l = m; else r = m; } return l + 1; } static void addEdge(List<List<Integer>> graph, int edge1, int edge2) { graph.get(edge1).add(edge2); graph.get(edge2).add(edge1); } public static class Pair implements Comparable<Pair> { int first; int second; public Pair(int first, int second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(Pair o) { // TODO Auto-generated method stub if (this.first != o.first) return (int) (this.first - o.first); else return (int) (this.second - o.second); } } public static class PairC<X, Y> implements Comparable<PairC> { X first; Y second; public PairC(X first, Y second) { this.first = first; this.second = second; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(PairC o) { // TODO Auto-generated method stub return o.compareTo((PairC) first); } } static boolean isCollectionsSorted(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false; return true; } static boolean isCollectionsSortedReverseOrder(List<Long> list) { if (list.size() == 0 || list.size() == 1) return true; for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false; return true; } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
903814b76eec364b75dc64cb0fa0e28a
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
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 int n, m; 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); n = sc.nextInt(); m = sc.nextInt(); int[] in = new int[n], outt = new int[n], deg = new int[n]; ad = new ArrayList[n]; for (int i = 0; i < n; i++) ad[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; in[b]++; deg[b]++; outt[a]++; ad[a].add(b); } Queue<Integer> q = new LinkedList<Integer>(); int[] ans = new int[n]; for (int i = 0; i < n; i++) if (in[i] == 0) { q.add(i); ans[i] = 1; } int pr = 1; // System.out.println(Arrays.toString(deg)); // System.out.println(Arrays.toString(outt)); while (!q.isEmpty()) { // System.out.println(q); int u = q.poll(); pr = Math.max(pr, ans[u]); if (outt[u] < 2) { if (ad[u].size() == 1) { int v = ad[u].get(0); deg[v]--; if (deg[v] == 0) { ans[v] = Math.max(ans[v], 1); q.add(v); } } continue; } for (int v : ad[u]) { deg[v]--; if (in[v] > 1) { ans[v] = Math.max(ans[v], 1 + ans[u]); } if (deg[v] == 0) { ans[v] = Math.max(ans[v], 1); q.add(v); } // System.out.println(v + " " + Arrays.toString(deg)); } } out.print(pr); out.flush(); } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
4b2f7f4b5d19e3f8b08d770f3eb86d0c
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; public class G { public static void main(String[] args) { new G().solve(); } public void solve() { Scanner scanner = new Scanner(System.in); int t = 1; while (t-- > 0) { int n = scanner.nextInt(); int m = scanner.nextInt(); Node[] node = new Node[n + 1]; for (int i = 1; i <= n; i++) { node[i] = new Node(); } for (int i = 0; i < m; i++) { int v = scanner.nextInt(); int u = scanner.nextInt(); node[v].getAdj().add(u); node[u].setIn(node[u].getIn() + 1); } for (int i = 1; i <= n; i++) { node[i].setStaticin(node[i].getIn());; } Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 1; i <= n; i++) { if (node[i].getIn() == 0) { queue.add(i); } } while (!queue.isEmpty()) { Node temp = node[queue.poll()]; List<Integer> adj = temp.getAdj(); int maxS = temp.getMaxS(); if (adj.size() > 1) { for (Integer u : adj) { if (node[u].getStaticin() > 1) { node[u].setMaxS(maxS + 1); } } } for (Integer u : adj) { node[u].setIn(node[u].getIn() - 1); if (node[u].getIn() == 0) { queue.add(u); } } } int maxS = 1; for (int i = 1; i <= n; i++) { int maxSi = node[i].getMaxS(); if (maxSi > maxS) maxS = maxSi; } System.out.println(maxS); } } } class Node { private int maxS = 1; private List<Integer> adj = new ArrayList<Integer>(); private int staticin = 0; private int in = 0; public Node() { super(); } public int getMaxS() { return maxS; } public void setMaxS(int maxS) { if (maxS > this.maxS) { this.maxS = maxS; } } public List<Integer> getAdj() { return adj; } public void setAdj(List<Integer> adj) { this.adj = adj; } public int getIn() { return in; } public void setIn(int in) { this.in = in; } public int getStaticin() { return staticin; } public void setStaticin(int staticin) { this.staticin = staticin; } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
3e7d4160f8709c24a4f8c38e431c2cd0
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class div3_1674_g { public static void main(String[] args) { FastScanner scan=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n=scan.nextInt(), m=scan.nextInt(); ArrayList<Integer>[] a=new ArrayList[n], rev=new ArrayList[n]; for(int i=0;i<n;i++) { a[i]=new ArrayList<>(); rev[i]=new ArrayList<>(); } int[] drev=new int[n], da=new int[n]; for(int i=0;i<m;i++) { int u=scan.nextInt()-1, v=scan.nextInt()-1; a[u].add(v); rev[v].add(u); drev[u]++; da[v]++; } int[] res=new int[n]; Arrays.fill(res,1); ArrayDeque<Integer> q=new ArrayDeque<>(); for(int i=0;i<n;i++) { if(drev[i]==0) q.offer(i); } int ans=1; int[] ct=new int[n]; while(!q.isEmpty()) { int cur=q.poll(); for(int nxt:rev[cur]) { drev[nxt]--; ct[nxt]++; if(da[cur]>1) { res[nxt]=Math.max(res[nxt],1+res[cur]); } if(drev[nxt]==0) { if(ct[nxt]==1) res[nxt]=1; ans=Math.max(ans,res[nxt]); q.offer(nxt); } } } out.println(ans); out.close(); } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
358fcbdb3ad0f688b92cdea1e0902c50
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Main { static int n, m, res; static int ans[], in[]; static ArrayList<Integer> g[]; static void dfs(int u) { int s = 0; for (int v : g[u]) { if (ans[v] == 0) { dfs(v); } if (in[v] != 1 && g[u].size() != 1) { s = Math.max(s, ans[v]); } } ans[u] = s + 1; res = Math.max(res, ans[u]); } public static void main(String[] args) throws IOException { fs = new FastReader(); out = new PrintWriter(System.out); n = fs.nextInt(); m = fs.nextInt(); g = new ArrayList[n]; ans = new int[n]; in = new int[n]; res = 1; for (int i = 0; i < n; ++i) g[i] = new ArrayList<Integer>(); for (int i = 0, u, v; i < m; ++i) { u = fs.nextInt() - 1; v = fs.nextInt() - 1; g[u].add(v); ++in[v]; } for (int i = 0; i < n; ++i) { if (ans[i] == 0) { dfs(i); } } out.println(res); 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
0e272f92a64bfc4da7a46f0a9e67cb85
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); try {if(new File(System.getProperty("user.dir")).getName().equals("LOCAL")) { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} } catch (Exception ignore) { } } //----------------------START---------------------// void start() { // int t = ni(); while(t-- > 0) solve(); w.close(); } List<Integer>[] graph; void solve() { int n = ni(), m = ni(); graph = new List[n]; int[] indegree = new int[n], outdegree = new int[n]; for(int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for(int i = 0; i < m; i++) { int a = ni()-1, b = ni()-1; indegree[b]++; outdegree[a]++; graph[a].add(b); } int[] topo = new int[n]; int at = 0; int[] degree = indegree.clone(); Queue<Integer> q = new ArrayDeque<>(); for(int i = 0; i < n; i++) { if(degree[i] == 0) q.offer(i); } while(!q.isEmpty()) { int poll = q.poll(); topo[at++] = poll; for(int i: graph[poll]) { degree[i]--; if(degree[i] == 0) q.offer(i); } } int ans = 1; int[] dp = new int[n]; Arrays.fill(dp, -1); vis = new boolean[n]; for(int i = 0; i < n; i++) { int curr = topo[i]; if(outdegree[curr] > 1) { ans = Math.max(ans, dfs(curr, indegree, outdegree, dp)); } } p(ans); } boolean[] vis; int dfs(int at, int[] indegree, int[] outdegree, int[] dp) { vis[at] = true; int max = 0; for(int i: graph[at]) { if(outdegree[at] > 1 && indegree[i] > 1) { if(vis[i]) max = Math.max(dp[i], max); else { max = Math.max(max, dfs(i, indegree, outdegree, dp)); } } } return dp[at] = (max+1); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
2da49863ecfea849a06d8b9c9fddaa1a
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class G_Remove_Directed_Edges { public static int[] dp, outd, ind; 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 e = in.nextInt(); List<List<Integer>> g = new ArrayList<>(); ind = new int[n]; outd = new int[n]; dp = new int[n]; Arrays.fill(dp, -1); for (int i = 0; i < n; i++) g.add(new ArrayList<>()); while (e-- > 0) { int u = in.nextInt()-1; int v = in.nextInt()-1; g.get(u).add(v); ind[v]++; outd[u]++; } int ans = 1; for (int i = 0; i < n; i++) { if (outd[i] >= 2) { for (int child : g.get(i)) ans = Math.max(ans, solve(g, child)+1); } } out.println(ans); out.flush(); out.close(); } public static int solve(List<List<Integer>> g, int u) { if (dp[u] != -1) return dp[u]; if (outd[u] >= 2 && ind[u] >= 2) { dp[u] = 1; for (int child : g.get(u)) { dp[u] = Math.max(dp[u], solve(g, child)+1); } } else if (ind[u] >= 2) { dp[u] = 1; } else { dp[u] = Integer.MIN_VALUE; } return dp[u]; } } // 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
ea9fc6a4e1bbb19f5797a1bd5b6ebadb
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class Main { static Main2 admin = new Main2(); public static void main(String[] args) { admin.start(); } } class Main2 { //---------------------------------INPUT READER-----------------------------------------// public BufferedReader br; StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine());} catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long n) {int[]ret=new int[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} long[] nal(long n) {long[]ret=new long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} Integer[] nA(long n) {Integer[]ret=new Integer[(int)n]; for(int i=0;i<n;i++) ret[i]=ni(); return ret;} Long[] nAl(long n) {Long[]ret=new Long[(int)n]; for(int i=0;i<n;i++) ret[i]=nl(); return ret;} //--------------------------------------PRINTER------------------------------------------// PrintWriter w; void p(int i) {w.println(i);} void p(long l) {w.println(l);} void p(double d) {w.println(d);} void p(String s) { w.println(s);} void pr(int i) {w.print(i);} void pr(long l) {w.print(l);} void pr(double d) {w.print(d);} void pr(String s) { w.print(s);} void pl() {w.println();} //--------------------------------------VARIABLES-----------------------------------------// long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; long mod = 1000000007; { w = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); try {if(new File(System.getProperty("user.dir")).getName().equals("LOCAL")) { w = new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));} } catch (Exception ignore) { } } //----------------------START---------------------// void start() { // int t = ni(); while(t-- > 0) solve(); w.close(); } List<Integer>[] graph; void solve() { int n = ni(), m = ni(); graph = new List[n]; int[] indegree = new int[n], outdegree = new int[n]; for(int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for(int i = 0; i < m; i++) { int a = ni()-1, b = ni()-1; indegree[b]++; outdegree[a]++; graph[a].add(b); } int[] topo = new int[n]; int at = 0; int[] degree = indegree.clone(); Queue<Integer> q = new ArrayDeque<>(); for(int i = 0; i < n; i++) { if(degree[i] == 0) q.offer(i); } while(!q.isEmpty()) { int poll = q.poll(); topo[at++] = poll; for(int i: graph[poll]) { degree[i]--; if(degree[i] == 0) q.offer(i); } } int ans = 1; int[] dp = new int[n]; Arrays.fill(dp, -1); vis = new boolean[n]; for(int i = 0; i < n; i++) { int curr = topo[i]; if(outdegree[curr] > 1) { ans = Math.max(ans, dfs(curr, indegree, outdegree, dp)); } } p(ans); } boolean[] vis; int dfs(int at, int[] indegree, int[] outdegree, int[] dp) { vis[at] = true; int max = 0; for(int i: graph[at]) { if(outdegree[at] > 1 && indegree[i] > 1) { if(vis[i]) max = Math.max(dp[i], max); else { max = Math.max(max, dfs(i, indegree, outdegree, dp)); } } } return dp[at] = (max+1); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
cf1f2e794fe2d3161c481dbd473c4885
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; public class ACM { private static int INF = (int) 1e9; private static int n; private static int[] in, out; private static ArrayList<Integer>[] graph; private static int[] dp; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); in = new int[n]; out = new int[n]; graph = new ArrayList[n]; for (int i = n - 1; i >= 0; i--) graph[i] = new ArrayList<Integer>(); for (int m = sc.nextInt(); m > 0; m--) { int v = sc.nextInt() - 1; int u = sc.nextInt() - 1; out[v]++; in[u]++; graph[v].add(u); } maxSize(); } private static void maxSize() { int res = 1; dp = new int[n]; for (int v = n - 1; v >= 0; v--) { if (out[v] < 2) continue; for (int u: graph[v]) { res = Math.max(res, cal(u) + 1); } } System.out.println(res); } private static int cal(int v) { if (dp[v] != 0) return dp[v]; if (in[v] >= 2 && out[v] >= 2) { dp[v] = 1; for (int u: graph[v]) { dp[v] = Math.max(dp[v], cal(u) + 1); } } else if (in[v] >= 2) { dp[v] = 1; } else { dp[v] = -INF; } return dp[v]; } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
aa532575fbe9950b21940beb799d9968
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; public class RemoveDirectedEdge { static ArrayList<Integer> in = new ArrayList<Integer>(); static ArrayList<Integer> out = new ArrayList<Integer>(); static ArrayList<Integer> dp = new ArrayList<Integer>(); static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(); public static void main(String[] args) { Scanner inp = new Scanner(System.in); int n = inp.nextInt(); int m = inp.nextInt(); for(int i=0; i<n; i++){ graph.add(new ArrayList<Integer>()); in.add(0); out.add(0); dp.add(-1); } for(int i=0; i<m; i++){ int v = inp.nextInt(); int u = inp.nextInt(); u--; v--; graph.get(v).add(u); in.set(u, in.get(u)+1); out.set(v, out.get(v)+1); } int ans = 1; for(int v=0; v<n; v++){ if (out.get(v)>=2){ for(int u:graph.get(v)){ ans = Math.max(ans, calc(u)+1); } } } System.out.println(ans); inp.close(); } static int calc(int u){ if (dp.get(u)!=-1){ return dp.get(u); } if (in.get(u)>=2 && out.get(u)>=2){ dp.set(u, 1); for (int v:graph.get(u)){ dp.set(u, Math.max(dp.get(u), calc(v)+1)); } } else if (in.get(u) >= 2){ dp.set(u, 1); } else{ dp.set(u, Integer.MIN_VALUE); } return dp.get(u); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
91d1f6fde6ada70c4cbbd20666a6176d
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; import java.io.*; // res.append("Case #"+(p+1)+": "+hh+" \n"); ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class G_Remove_Directed_Edges{ 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(); int m=s.nextInt(); ArrayList<ArrayList<Integer>> list1 = new ArrayList<ArrayList<Integer>>(n+3); ArrayList<ArrayList<Integer>> list2 = new ArrayList<ArrayList<Integer>>(n+3); for(int i=0;i<=n;i++){ ArrayList<Integer> obj1 = new ArrayList<Integer>(); ArrayList<Integer> obj2 = new ArrayList<Integer>(); list1.add(obj1); list2.add(obj2); } ArrayList<ArrayList<Integer>> list3 = new ArrayList<ArrayList<Integer>>(n+3); ArrayList<ArrayList<Integer>> list4 = new ArrayList<ArrayList<Integer>>(n+3); for(int i=0;i<=n;i++){ ArrayList<Integer> obj1 = new ArrayList<Integer>(); ArrayList<Integer> obj2 = new ArrayList<Integer>(); list3.add(obj1); list4.add(obj2); } Queue<Integer> nice = new LinkedList<Integer>(); int visited[]= new int[n+1]; int out[]= new int[n+1]; for(int i=0;i<m;i++){ int a=s.nextInt(); int b=s.nextInt(); list1.get(a).add(b); list2.get(b).add(a); //out[a]++; } HashMap<String,Integer> map = new HashMap<String,Integer>(); for(int i=1;i<=n;i++){ if(list1.get(i).size()==1){ String a1=""; a1=a1+list1.get(i).get(0); a1=a1+"*"+i; map.put(a1,1); String a2=""; a2=a2+i+"*"+list1.get(i).get(0);; map.put(a2,1); } if(list2.get(i).size()==1){ String a1=""; a1=a1+list2.get(i).get(0); a1=a1+"*"+i; map.put(a1,1); String a2=""; a2=a2+i+"*"+list2.get(i).get(0);; map.put(a2,1); } } for(int i=1;i<=n;i++){ ArrayList<Integer> obj1 = list1.get(i); ArrayList<Integer> obj2 =list3.get(i); for(int j=0;j<obj1.size();j++){ int num=obj1.get(j); String a3=""; a3=a3+i+"*"+num; if(!map.containsKey(a3)){ obj2.add(num); out[i]++; } } } for(int i=1;i<=n;i++){ ArrayList<Integer> obj1 = list2.get(i); ArrayList<Integer> obj2 =list4.get(i); for(int j=0;j<obj1.size();j++){ int num=obj1.get(j); String a3=""; a3=a3+i+"*"+num; if(!map.containsKey(a3)){ obj2.add(num); } } } list1=list3; list2=list4; long well[]= new long[n+1]; //stores the longest simple path starting from node i for(int i=1;i<=n;i++){ if(out[i]==0){ nice.add(i); visited[i]=1; } } while(nice.size()>0){ Queue<Integer> nice2 = new LinkedList<Integer>(); while(nice.size()>0){ int node=nice.poll(); long hh=0; for(int j=0;j<list1.get(node).size();j++){ int num=list1.get(node).get(j); hh=Math.max(hh,well[num]); } hh++; well[node]=hh; for(int j=0;j<list2.get(node).size();j++){ int num=list2.get(node).get(j); out[num]--; } nice2.add(node); } Queue<Integer> nice3 = new LinkedList<Integer>(); while(nice2.size()>0){ int node=nice2.poll(); for(int j=0;j<list2.get(node).size();j++){ int num=list2.get(node).get(j); if(visited[num]==0 && out[num]==0){ visited[num]=1; nice3.add(num); } } } nice=nice3; } long ans=0; for(int i=1;i<=n;i++){ ans=Math.max(ans,well[i]); } 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
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
49d149bb3763c24430e09c6033408b85
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
/* I am dead inside Do you like NCT, sKz, BTS? 5 4 3 2 1 Moonwalk Imma knock it down like domino Is this what you want? Is this what you want? Let's ttalkbocky about that */ import static java.lang.Math.*; import java.util.*; import java.io.*; public class x1674G { static final int INF = Integer.MIN_VALUE/5; static ArrayDeque<Integer>[] edges; public static void main(String args[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.nextInt(); int M = infile.nextInt(); edges = new ArrayDeque[N]; for(int v=0; v < N; v++) edges[v] = new ArrayDeque<Integer>(); int[] in = new int[N]; int[] out = new int[N]; while(M-->0) { int a = infile.nextInt()-1; int b = infile.nextInt()-1; edges[a].add(b); out[a]++; in[b]++; } topsort = new ArrayList<Integer>(); boolean[] seents = new boolean[N]; for(int i=0; i < N; i++) if(!seents[i]) dfs(i, seents); Collections.reverse(topsort); int[] dp = new int[N]; for(int i=N-1; i >= 0; i--) { int curr = topsort.get(i); dp[curr] = 1; if(out[curr] == 1) continue; int best = 0; for(int next: edges[curr]) if(in[next] > 1) best = max(best, dp[next]); dp[curr] += best; } int res = 1; for(int i=0; i < N; i++) res = max(res, dp[i]); System.out.println(res); } static ArrayList<Integer> topsort; public static void dfs(int curr, boolean[] seen) { seen[curr] = true; for(int next: edges[curr]) if(!seen[next]) dfs(next, seen); topsort.add(curr); } } class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
f3cf4b2fc9b094b9d1c046d5315ac28e
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class Main{ static LinkedList<Integer>[]adj; static int[]memo; static int[]in,out; static int dp(int i){ if(memo[i]!=-1)return memo[i]; int ans=1; if(out[i]>=2) { for (int j : adj[i]) { if(in[j]>=2){ ans=Math.max(ans,1+dp(j)); } } } return memo[i]=ans; } static void main() throws Exception{ int n=sc.nextInt(),m=sc.nextInt(); adj=new LinkedList[n]; memo=new int[n]; for(int i=0;i<n;i++){ adj[i]=new LinkedList<>(); memo[i]=-1; } in=new int[n]; out=new int[n]; for(int i=0;i<m;i++){ int x=sc.nextInt()-1,y=sc.nextInt()-1; adj[x].add(y); out[x]++; in[y]++; } int ans=0; for(int i=0;i<n;i++){ ans= Math.max(ans,dp(i)); } pw.println(ans); } public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; // tc=sc.nextInt(); for(int test=1;test<=tc;test++) { main(); } pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(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 int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } 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 void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 8
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
53bc669b6bacc8cbd899ff11a5ed6380
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; /* getOrDefault valueOf char[] arr=st.nextToken().toCharArray(); System.out.println(); List<Integer> l=new ArrayList<>(); List<int[]> l=new ArrayList<>(); Set<Integer> set=new HashSet<>(); Map<Integer,Integer> map=new HashMap<>(); Map<Integer,List<Integer>> map=new HashMap<>(); for(int i=1;i<=n;i++) map.put(i,new ArrayList<>()); Map<Integer,List<int[]>> map=new HashMap<>(); Deque<Integer> d=new ArrayDeque<>(); PriorityQueue<Integer> pq=new PriorityQueue<>(); st = new StringTokenizer(infile.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); int z=Integer.parseInt(st.nextToken()); */ public class Solution{ static Map<Integer,List<Integer>> map=new HashMap<>(); static int[] in; static int[] out; static int[] tempout; static int[] res; public static void main(String []args) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); //int T=Integer.parseInt(st.nextToken()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); in=new int[n+1]; out=new int[n+1]; tempout=new int[n+1]; res=new int[n+1]; for(int i=1;i<=n;i++){ res[i]=1; map.put(i,new ArrayList<>()); } for(int i=1;i<=m;i++){ st = new StringTokenizer(infile.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); map.get(y).add(x); out[x]++; in[y]++; tempout[x]=out[x]; } Deque<Integer> d=new ArrayDeque<>(); for(int i=1;i<=n;i++){ if(out[i]==0) d.add(i); } while(!d.isEmpty()){ int cur=d.removeFirst(); for(int next:map.get(cur)){ if(out[next]>1 && in[cur]>1) res[next]=Math.max(res[next],res[cur]+1); tempout[next]--; if(tempout[next]==0) d.add(next); } } int ans=1; for(int i=1;i<=n;i++) ans=Math.max(ans,res[i]); System.out.println(ans); } public static void build(long[] arr, StringTokenizer st, int lo){ for(int i=lo;i<arr.length;i++) arr[i]=Long.parseLong(st.nextToken()); } public static void build(int[] arr, StringTokenizer st, int lo){ for(int i=lo;i<arr.length;i++) arr[i]=Integer.parseInt(st.nextToken()); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 17
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
69a1ce0870d9bd972ee90c8fb94a0a93
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; /* getOrDefault valueOf char[] arr=st.nextToken().toCharArray(); System.out.println(); List<Integer> l=new ArrayList<>(); List<int[]> l=new ArrayList<>(); Set<Integer> set=new HashSet<>(); Map<Integer,Integer> map=new HashMap<>(); Map<Integer,List<Integer>> map=new HashMap<>(); for(int i=1;i<=n;i++) map.put(i,new ArrayList<>()); Map<Integer,List<int[]>> map=new HashMap<>(); Deque<Integer> d=new ArrayDeque<>(); PriorityQueue<Integer> pq=new PriorityQueue<>(); st = new StringTokenizer(infile.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); int z=Integer.parseInt(st.nextToken()); */ public class Solution{ static Map<Integer,List<Integer>> map=new HashMap<>(); static int[] in; static int[] out; static int[] tempin; static int[] tempout; static int[] res; public static void main(String []args) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); //int T=Integer.parseInt(st.nextToken()); int n=Integer.parseInt(st.nextToken()); int m=Integer.parseInt(st.nextToken()); in=new int[n+1]; tempin=new int[n+1]; out=new int[n+1]; tempout=new int[n+1]; res=new int[n+1]; for(int i=1;i<=n;i++){ res[i]=1; map.put(i,new ArrayList<>()); } for(int i=1;i<=m;i++){ st = new StringTokenizer(infile.readLine()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); map.get(y).add(x); out[x]++; in[y]++; tempin[y]=in[y]; tempout[x]=out[x]; } Deque<Integer> d=new ArrayDeque<>(); for(int i=1;i<=n;i++){ if(out[i]==0) d.add(i); } while(!d.isEmpty()){ int cur=d.removeFirst(); for(int next:map.get(cur)){ if(out[next]>1 && in[cur]>1) res[next]=Math.max(res[next],res[cur]+1); tempout[next]--; if(tempout[next]==0) d.add(next); } } int ans=1; for(int i=1;i<=n;i++) ans=Math.max(ans,res[i]); System.out.println(ans); } public static void build(long[] arr, StringTokenizer st, int lo){ for(int i=lo;i<arr.length;i++) arr[i]=Long.parseLong(st.nextToken()); } public static void build(int[] arr, StringTokenizer st, int lo){ for(int i=lo;i<arr.length;i++) arr[i]=Integer.parseInt(st.nextToken()); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 17
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
e9b7cd11e6f03c981990a930fb6339e1
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static AReader scan = new AReader(); static int N = 200010; static int[] h = new int[N]; static int[] e = new int[N]; static int[] ne = new int[N]; static int idx; static int n; static int[] din = new int[N]; static int[] dout = new int[N]; static int[] dp = new int[N]; static boolean[] st = new boolean[N]; static void add(int a,int b){ e[idx] = b;ne[idx] = h[a];h[a] = idx++;din[b]++;dout[a]++; } static void dfs(int u){ if(dp[u] != -1) return; dp[u] = 1; if(dout[u] <= 1) return; for(int i = h[u];i!=-1;i=ne[i]){ int j = e[i]; if(din[j] > 1) { dfs(j); dp[u] = Math.max(dp[u], dp[j] + 1); } } } static void solve() { Arrays.fill(h,-1); n = scan.nextInt(); int m = scan.nextInt(); while(m-->0){ int a = scan.nextInt(); int b = scan.nextInt(); add(a,b); } int res = 1; Arrays.fill(dp,-1); for(int i = 1;i<=n;i++){ dfs(i); res = Math.max(res,dp[i]); } System.out.println(res); } public static void main(String[] args) { //int T = scan.nextInt(); //while (T-- > 0) { solve(); //} } } class AReader { private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer tokenizer = new StringTokenizer(""); private String innerNextLine() { try { return reader.readLine(); } catch (IOException ex) { return null; } } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String nextLine = innerNextLine(); if (nextLine == null) { return false; } tokenizer = new StringTokenizer(nextLine); } return true; } public String nextLine() { tokenizer = new StringTokenizer(""); return innerNextLine(); } public String next() { hasNext(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } class Pair { int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
040b5c6b95131f9620166cadc633ea30
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.security.cert.X509CRL; import java.util.*; import java.lang.*; import java.util.stream.Collector; import java.util.stream.Collectors; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; static String OUTPUT = ""; //global //private final static long BASE = 998244353L; private final static int ALPHABET = (int)('z') - (int)('a') + 1; private final static int BASE = 1000000007; private final static int INF_I = (1<<31)-1; private final static long INF_L = (1l<<63)-1; private final static int MAXN = 100100; private final static int MAXK = 31; private static List<List<Integer>> G = new ArrayList<>(); private static boolean[] free; private static List<Integer> topo = new ArrayList<>(); private static void dfs(int u, int pa) { free[u] = true; for (int v:G.get(u)) { if (v==pa || free[v]) continue; dfs(v,u); } topo.add(u); } static void solve() { int ntest = 1; for (int test=0;test<ntest;test++) { int N = readInt(), M = readInt(); int[] din = new int[N]; int[] dout = new int[N]; int[] F = new int[N]; free = new boolean[N]; Arrays.fill(F, -INF_I); for (int i=0;i<N;i++) G.add(new ArrayList<>()); for (int i=0;i<M;i++) { int u = readInt() - 1; int v = readInt() - 1; G.get(u).add(v); din[v]++; dout[u]++; } for (int i=0;i<N;i++) { if (free[i]) continue; dfs(i,-1); } Collections.reverse(topo); //for (int x:topo) out.println(x); for (int i=0;i<N;i++) if (din[i] >= 2 || din[i]==0) F[i] = 1; for (int i=topo.size()-1; i>=0; i--) { int u = topo.get(i); if (dout[u] >= 2) { for (int v: G.get(u)) if (din[v]>=2) F[u] = Math.max(F[u], F[v] + 1); } } int ans = 0; for (int i=0;i<N;i++) ans = Math.max(ans, F[i]); out.println(ans); } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } if (OUTPUT == "") out = new PrintWriter(System.out); else out = new PrintWriter(OUTPUT); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> { private T x; private T y; public Point(T x, T y) { this.x = x; this.y = y; } public T getX() {return x;} public T getY() {return y;} @Override public int compareTo(Point<T> o) { int cmp = x.compareTo(o.getX()); if (cmp==0) return y.compareTo(o.getY()); return cmp; } } private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> { public ClassComparator() {} @Override public int compare(T a, T b) { return a.compareTo(b); } } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
5eb0606e80453ef36f2b0f9a419bf81e
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
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.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class G1674 { 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(); } private static class Solver { private Map<Integer, List<Integer>> mp; private int[] degreeIn; private int[] degreeOut; private int[] dp; private void addEdge(int u, int v) { List<Integer> nexts = mp.getOrDefault(u, new ArrayList<>()); nexts.add(v); mp.put(u, nexts); this.degreeIn[v]++; this.degreeOut[u]++; } private void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); // 已i为头的最长链的长度 dp = new int[n + 1]; degreeIn = new int[n + 1]; degreeOut = new int[n + 1]; mp = new HashMap<>(); for (int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); this.addEdge(u, v); } for (int i = 1; i <= n; i++) { this.dfs(i); } Arrays.stream(dp).max().ifPresent(out::println); } private void dfs(int father) { if (dp[father] > 0) { return; } dp[father] = 1; // 出度为0的时候,没有下一个点可以走;出度为1的时候,要删一条出边,也没下一个点可以走 if (degreeOut[father] < 2) { return; } List<Integer> sons = mp.getOrDefault(father, Collections.emptyList()); for (int son : sons) { dfs(son); if (degreeIn[son] > 1) { dp[father] = Math.max(dp[father], dp[son] + 1); } } } } private 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()); } } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
610e7684e93cc8b856b8ac896c373c44
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
// package c1674; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; // // Codeforces Round #786 (Div. 3) 2022-05-02 07:35 // G. Remove Directed Edges // https://codeforces.com/contest/1674/problem/G // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given a directed acyclic graph, consisting of n vertices and m edges. The vertices are // numbered from 1 to n. There are no multiple edges and self-loops. // // Let \mathit{in}_v be the number of incoming edges (indegree) and \mathit{out}_v be the number of // outgoing edges (outdegree) of vertex v. // // You are asked to remove some edges from the graph. Let the new degrees be \mathit{in'}_v and // \mathit{out'}_v. // // You are only allowed to remove the edges if the following conditions hold for every vertex v: // * \mathit{in'}_v < \mathit{in}_v or \mathit{in'}_v = \mathit{in}_v = 0; // * \mathit{out'}_v < \mathit{out}_v or \mathit{out'}_v = \mathit{out}_v = 0. // // Let's call a set of vertices S if for each pair of vertices v and u (v != u) such that v \in S // and u \in S, there exists a path either from v to u or from u to v over the non-removed edges. // // What is the maximum possible size of a set S after you remove some edges from the graph and both // indegrees and outdegrees of all vertices either decrease or remain equal to 0? // // Input // // The first line contains two integers n and m (1 <= n <= 2 * 10^5; 0 <= m <= 2 * 10^5)-- the // number of vertices and the number of edges of the graph. // // Each of the next m lines contains two integers v and u (1 <= v, u <= n; v != u)-- the description // of an edge. // // The given edges form a valid directed acyclic graph. There are no multiple edges. // // Output // // Print a single integer-- the maximum possible size of a set S after you remove some edges from // the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to 0. // // Example /* input: 3 3 1 2 2 3 1 3 output: 2 input: 5 0 output: 1 input: 7 8 7 1 1 3 6 2 2 3 7 2 2 4 7 3 6 3 output: 3 */ // Note // // In the first example, you can remove edges (1, 2) and (2, 3). \mathit{in} = [0, 1, 2], // \mathit{out} = [2, 1, 0]. \mathit{in'} = [0, 0, 1], \mathit{out'} = [1, 0, 0]. You can see that // for all v the conditions hold. The maximum set S is formed by vertices 1 and 3. They are still // connected directly by an edge, so there is a path between them. // // In the second example, there are no edges. Since all \mathit{in}_v and \mathit{out}_v are equal // to 0, leaving a graph with zero edges is allowed. There are 5 sets, each contains a single // vertex. Thus, the maximum size is 1. // // In the third example, you can remove edges (7, 1), (2, 4), (1, 3) and (6, 2). The maximum set // will be S = {7, 3, 2}. You can remove edge (7, 3) as well, and the answer won't change. // // Here is the picture of the graph from the third example: // https://espresso.codeforces.com/7c002cfb3555fb57111c5bab3e66f41e485f3a8a.png // public class C1674G { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int n, int[][] edges) { edges = reduce(n, edges); int[] indegs = new int[n]; int[] outdegs = new int[n]; List<List<Integer>> upa = getUpEdgeArray(n, edges); List<List<Integer>> dna = getDownEdgeArray(n, edges); if (test) { System.out.format(trace(dna)); } int[] lens = new int[n]; Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < n; i++) { indegs[i] = upa.get(i).size(); outdegs[i] = dna.get(i).size(); if (outdegs[i] == 0) { q.add(i); } } myAssert(!q.isEmpty()); int ans = 1; while (!q.isEmpty()) { int v = q.poll(); lens[v] = 1; // single down or up edge has already been removed // here no more restriction. if (!dna.get(v).isEmpty()) { int i0 = dna.get(v).get(0); int maxc = lens[i0]; for (int w : dna.get(v)) { maxc = Math.max(maxc, lens[w]); } lens[v] = 1 + maxc; } ans = Math.max(ans, lens[v]); // up degrees must also reduce by 1 for (int u : upa.get(v)) { myAssert(outdegs[u] > 0); outdegs[u]--; if (outdegs[u] == 0) { q.add(u); } } } // System.out.format("lens: %s\n", Arrays.toString(lens)); return ans; } // Eliminate single in and out edges static int[][] reduce(int n, int[][] edges) { int m = edges.length; List<List<int[]>> dna = new ArrayList<>(); List<List<int[]>> upa = new ArrayList<>(); for (int i = 0; i < n; i++) { dna.add(new ArrayList<>()); upa.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = edges[i][0]; int v = edges[i][1]; // u --> v dna.get(u).add(new int[] {v, i}); upa.get(v).add(new int[] {u, i}); } boolean[] deleted = new boolean[m]; for (int i = 0; i < n; i++) { if (dna.get(i).size() == 1) { int[] e = dna.get(i).get(0); deleted[e[1]] = true; if (test) { System.out.format(" deleted edge %d %d\n", i, e[0]); } } if (upa.get(i).size() == 1) { int[] e = upa.get(i).get(0); deleted[e[1]] = true; if (test) { System.out.format(" deleted edge %d %d\n", e[0], i); } } } int r = 0; for (int i = 0; i < m; i++) { if (!deleted[i]) { r++; } } int[][] ans = new int[r][2]; int idx = 0; for (int i = 0; i < m; i++) { if (!deleted[i]) { ans[idx][0] = edges[i][0]; ans[idx][1] = edges[i][1]; idx++; } } return ans; } static List<List<Integer>> getDownEdgeArray(int n, int[][] edges) { int m = edges.length; List<List<Integer>> dna = new ArrayList<>(); for (int i = 0; i < n; i++) { dna.add(new ArrayList<>()); } for (int[] edge : edges) { int u = edge[0]; int v = edge[1]; // u --> v dna.get(u).add(v); } for (int i = 0; i < n; i++) { Collections.sort(dna.get(i)); } return dna; } static List<List<Integer>> getUpEdgeArray(int n, int[][] edges) { int m = edges.length; List<List<Integer>> upa = new ArrayList<>(); for (int i = 0; i < n; i++) { upa.add(new ArrayList<>()); } for (int[] edge : edges) { int u = edge[0]; int v = edge[1]; // u --> v upa.get(v).add(u); } for (int i = 0; i < n; i++) { Collections.sort(upa.get(i)); } return upa; } static String trace(List<List<Integer>> dna) { int n = dna.size(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (dna.get(i).isEmpty()) { continue; } sb.append(String.format("%3d: ", i)); boolean first = true; for (int v : dna.get(i)) { if (!first) { sb.append(','); } sb.append(v); first = false; } sb.append('\n'); } return sb.toString(); } static void test(int exp, int n, int[][] edges) { List<List<Integer>> dna = getDownEdgeArray(n, edges); int ans = solve(n, edges); System.out.format("%d %s => %d%s\n", n, trace(edges), ans, ans == exp ? "" : " Expected " + exp); myAssert(ans == exp); } static String trace(int[][] edges) { StringBuilder sb = new StringBuilder(); sb.append('{'); for (int[] e : edges) { if (sb.length() > 1) { sb.append(','); } sb.append('{'); sb.append(e[0]); sb.append(','); sb.append(e[1]); sb.append('}'); } sb.append('}'); return sb.toString(); } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); test(2, 3, new int[][] {{0,1},{1,2},{0,2}}); test(3, 7, new int[][] {{6,0},{0,2},{5,1},{1,2},{6,1},{1,3},{6,2},{5,2}}); test(8, 10, new int[][] {{2,7},{2,6},{2,4},{2,1},{2,0},{2,3},{2,9},{2,5},{2,8},{7,6},{7,4}, {7,1},{7,0},{7,3},{7,9},{7,5},{7,8},{6,4},{6,1},{6,0},{6,3},{6,9},{6,5},{6,8},{4,1},{4,0}, {4,3},{4,9},{4,5},{4,8},{1,0},{1,3},{1,9},{1,5},{1,8},{0,3},{0,9},{0,5},{0,8},{3,9},{3,5}, {3,8},{9,5},{9,8},{5,8}}); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int n = in.nextInt(); int m = in.nextInt(); int[][] edges = new int[m][2]; for (int i = 0; i < m; i++) { edges[i][0] = in.nextInt() - 1; edges[i][1] = in.nextInt() - 1; } // System.out.println(trace(edges)); int ans = solve(n, edges); System.out.println(ans); } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 500) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
bb87461ef237c7a681f3dcb2f8b7bd6f
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
//Utilities import java.io.*; import java.util.*; public class a { static int n, m; static int[] ord; static int idxOrd; static boolean[] vis; static ArrayList<Integer>[] adj, revAdj; static int u, v; static int[] dp; static int res = 0; public static void main(String[] args) throws IOException { n = in.iscan(); m = in.iscan(); adj = new ArrayList[n+1]; revAdj = new ArrayList[n+1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList(); revAdj[i] = new ArrayList(); } for (int i = 0; i < m; i++) { u = in.iscan(); v = in.iscan(); adj[u].add(v); revAdj[v].add(u); } vis = new boolean[n+1]; idxOrd = n-1; ord = new int[n]; // topological sort for (int i = 1; i <= n; i++) { if (!vis[i]) { dfs(i); } } // for (int i = 0; i < n; i++) { // out.print(ord[i] + " "); // } // out.println(); dp = new int[n+1]; for (int i = 0; i < n; i++) { boolean found = false; int max = 0; for (int u : revAdj[ord[i]]) { if (adj[u].size() == 1) { found = true; } else { max = Math.max(max, dp[u]); } } if (found) { dp[ord[i]] = max + 1; } else { if (revAdj[ord[i]].size() <= 1) { dp[ord[i]] = 1; } else { dp[ord[i]] = max + 1; } } res = Math.max(res, dp[ord[i]]); } out.println(res); out.close(); } static void dfs(int cur) { vis[cur] = true; for (int u : adj[cur]) { if (!vis[u]) { dfs(u); } } ord[idxOrd--] = cur; } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } 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 * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
ff778db9b306e7834f08c8bc1ccb6d29
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class G { void go() { int ans = 0; int n = Reader.nextInt(); int m = Reader.nextInt(); List<Integer>[] g = new List[n + 1]; List<Integer>[] rg = new List[n + 1]; int[] ind = new int[n + 1]; List<Integer> top = new ArrayList<>(); Queue<Integer> q = new ArrayDeque<>(); int[] dp = new int[n + 1]; // longest path ending at vertex i for(int i = 0; i <= n; i++) { g[i] = new ArrayList<>(); rg[i] = new ArrayList<>(); } for(int i = 0; i < m; i++) { int u = Reader.nextInt(); int v = Reader.nextInt(); g[u].add(v); rg[v].add(u); ind[v]++; } for(int i = 1; i <= n; i++) { if(ind[i] == 0) { q.offer(i); } } while(!q.isEmpty()) { int v = q.poll(); top.add(v); for(int nei : g[v]) { if(--ind[nei] == 0) { q.offer(nei); } } } for(int v : top) { List<Integer> l = rg[v]; List<Integer> atLeastTwo = new ArrayList<>(); int max = 0; for(int u : l) { if(g[u].size() > 1) { atLeastTwo.add(u); max = Math.max(dp[u], max); } } if(atLeastTwo.size() > 1) { dp[v] = max + 1; } else { if(atLeastTwo.isEmpty() || (atLeastTwo.size() == 1 && l.size() == 1)) { dp[v] = 1; } else { dp[v] = max + 1; } } ans = Math.max(ans, dp[v]); } Writer.println(ans); } void solve() { go(); } void run() throws Exception { Reader.init(System.in); Writer.init(System.out); solve(); Writer.close(); } public static void main(String[] args) throws Exception { new G().run(); } public static class Reader { public static StringTokenizer st; public static BufferedReader br; public static void init(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public static String next() { while(!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new InputMismatchException(); } } return st.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static double nextDouble() { return Double.parseDouble(next()); } } public static class Writer { public static PrintWriter pw; public static void init(OutputStream os) { pw = new PrintWriter(new BufferedOutputStream(os)); } public static void print(String s) { pw.print(s); } public static void print(char c) { pw.print(c); } public static void print(int x) { pw.print(x); } public static void print(long x) { pw.print(x); } public static void println(String s) { pw.println(s); } public static void println(char c) { pw.println(c); } public static void println(int x) { pw.println(x); } public static void println(long x) { pw.println(x); } public static void flush() { pw.flush(); } public static void close() { pw.close(); } } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
0e3591bb12548fa2d525a18a2fa085a3
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); String s[]=bu.readLine().split(" "); int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]); int i,dp[]=new int[n],c[]=new int[n]; ArrayList<Integer> g[]=new ArrayList[n],rg[]=new ArrayList[n]; for(i=0;i<n;i++) { g[i]=new ArrayList<>(); rg[i]=new ArrayList<>(); dp[i]=1; } for(i=0;i<m;i++) { s=bu.readLine().split(" "); int u=Integer.parseInt(s[0])-1,v=Integer.parseInt(s[1])-1; rg[v].add(u); c[u]++; g[u].add(v); } Queue<Integer> q=new LinkedList<>(); for(i=0;i<n;i++) if(c[i]==0) q.add(i); int ans=0; while(!q.isEmpty()) { int p=q.poll(); if(g[p].size()>1) for(int x:g[p]) if(rg[x].size()>1) dp[p]=Math.max(dp[p],dp[x]+1); ans=Math.max(ans,dp[p]); for(int x:rg[p]) { c[x]--; if(c[x]==0) q.add(x); } } System.out.println(ans); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
01d94624829dbad5dd84fb0d7500b947
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; import java.io.*; // you can compare with output.txt and expected out public class Round786G { MyPrintWriter out; MyScanner in; final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void preferFileIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round786G sol = new Round786G(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; preferFileIO(isFileIO); int n = in.nextInt(); int[][] e = in.nextGraphEdges(-1); int ans = solve(n, e); out.println(ans); in.close(); out.close(); } private int solve(int n, int[][] e) { // in a cute set S, // suppose u --> v, i.e., v is reachable from u // if w --> u, then we have w --> u --> v // if u --> w, then we have u --> w --> v // by induction, we can show that there is a linear path in S // now assume we found a maximum linear path // what happens when we remove edges? // priority queues with lazy deletion each on in/out degree // no we don't need dynamic env, since we just delete once // it's harder to delete after creating a graph, so do this when construct the graph // delete all degree 1 vertices // now we are left with degree 2+ vertices. // choose a path with maximum length (how?) // deleting other edges not on the path is fine // define length of path = # of edges // dp[i] : maximum length of path starting in i // = max(dp[j]) for outNeighbors j of i int[] inDegreeTemp = new int[n]; int[] outDegreeTemp = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegreeTemp[u]++; inDegreeTemp[v]++; } int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; if(outDegreeTemp[u] != 1 && inDegreeTemp[v] != 1) { outDegree[u]++; inDegree[v]++; } } inNeighbors = new int[n][]; outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } int[] inIdx = new int[n]; int[] outIdx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; if(outDegreeTemp[u] != 1 && inDegreeTemp[v] != 1) { outNeighbors[u][outIdx[u]++] = v; inNeighbors[v][inIdx[v]++] = u; } } dp = new int[n]; Arrays.fill(dp, -1); int max = 0; for(int i=0; i<n; i++) { max = Math.max(max, rec(i)); } return max+1; } int[] dp; int[][] inNeighbors; int[][] outNeighbors; // dp[i] : maximum length of path starting in i // = max(dp[j]) for outNeighbors j of i int rec(int v) { if(dp[v] != -1) return dp[v]; int max = 0; for(int i=0; i<outNeighbors[v].length; i++) { max = Math.max(max, rec(outNeighbors[v][i])+1); } dp[v] = max; return max; } class Pair implements Comparable<Pair>{ int vertex; int degree; public Pair(int vertex, int degree) { this.vertex = vertex; this.degree = degree; } @Override public int compareTo(Pair o) { return Integer.compare(degree, o.degree); } } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } 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[][] nextGraphEdges(){ return nextGraphEdges(0); } int[][] nextGraphEdges(int offset) { int m = nextInt(); int[][] e = new int[m][2]; for(int i=0; i<m; i++){ e[i][0] = nextInt()+offset; e[i][1] = nextInt()+offset; } return e; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void print(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(long[] arr){ print(arr); println(); } public void print(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(int[] arr){ print(arr); println(); } public <T> void print(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void println(ArrayList<T> arr){ print(arr); println(); } public void println(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void println(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][][] constructDirectedNeighborhood(int n, int[][] e){ int[] inDegree = new int[n]; int[] outDegree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outDegree[u]++; inDegree[v]++; } int[][] inNeighbors = new int[n][]; int[][] outNeighbors = new int[n][]; for(int i=0; i<n; i++) { inNeighbors[i] = new int[inDegree[i]]; outNeighbors[i] = new int[outDegree[i]]; } int[] inIdx = new int[n]; int[] outIdx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][outIdx[u]++] = v; inNeighbors[v][inIdx[v]++] = u; } return new int[][][] {inNeighbors, outNeighbors}; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; int[] idx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][idx[u]++] = v; neighbors[v][idx[v]++] = u; } return neighbors; } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.close(); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
4a969cebb2405c49d65d1f0c9265253b
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class a{ public static FastScanner fs; public static int n,m,indeg[]; public static ArrayList<Integer>g[],rg[]; public static void main(String args[]) { fs=new FastScanner(); n=fs.nextInt(); m=fs.nextInt(); indeg=new int[n+1]; Arrays.fill(indeg,0); g=new ArrayList[n+1]; rg=new ArrayList[n+1]; for(int i=1;i<=n;i++) { g[i]=new ArrayList<Integer>(); rg[i]=new ArrayList<Integer>(); } for(int i=1;i<=m;i++) { int x,y; x=fs.nextInt(); y=fs.nextInt(); g[x].add(y); rg[y].add(x); indeg[y]++; } Queue<Integer>q=new LinkedList<>(); for(int i=1;i<=n;i++) { if(indeg[i]==0) q.add(i); } ArrayList<Integer>topologicalsort=new ArrayList<>(); while(!q.isEmpty()) { Integer fr=q.poll(); topologicalsort.add(fr); for(Integer it:g[fr]) { indeg[it]--; if(indeg[it]==0) q.add(it); } } int[] dp=new int[n+1]; for(int i=1;i<=n;i++) dp[i]=1; for(Integer it:topologicalsort) { if(rg[it].size()>1)//because we need to skip atleast one incoming edge { for(Integer it1:rg[it]) { if(g[it1].size()>1)//because we need to skip alteast one outgoing edge { dp[it]=Math.max(dp[it],1+dp[it1]); } } } } int ans=1; for(int i=1;i<=n;i++) ans=Math.max(ans,dp[i]); System.out.println(ans); } 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(Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
2f60c26857cc5051e25b06fa5d62d54d
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class JavaTest { private static 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 m = sc.nextInt(); ArrayList<Integer>[] graph = new ArrayList[n]; for(int i = 0; i < n; i++) { graph[i] = new ArrayList<Integer>(); } int[] in = new int[n]; int[] out = new int[n]; int[] dp = new int[n]; for(int i = 0; i < m; i++) { int v = sc.nextInt(); int u = sc.nextInt(); --v; --u; graph[v].add(u); ++in[u]; ++out[v]; } int ans = 1; Arrays.fill(dp, -1); for(int v = 0; v < n; v++) { if(out[v] >= 2) { for(int k = 0; k < graph[v].size(); k++) { int u = graph[v].get(k); ans = Math.max(ans, calc(u, dp, in, out, graph) + 1); } } } System.out.println(ans); } private static int calc(int v, int[] dp, int[] in, int[] out, ArrayList<Integer>[] graph) { if(dp[v] != -1) return dp[v]; if(in[v] >= 2 && out[v] >= 2) { dp[v] = 1; for (int u : graph[v]) { dp[v] = Math.max(dp[v], calc(u, dp, in, out, graph) + 1); } } else if(in[v] >= 2) { dp[v] = 1; } else { dp[v] = Integer.MIN_VALUE; } return dp[v]; } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
838c986aa32410fbf78904cecad5524d
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.util.*; public class G { static Scanner sc = new Scanner(System.in); static List<Integer> [] graph; static int [] toCount; static int [][] memo; public static void main(String[] args) { // TODO Auto-generated method stub solve(0); } private static void solve(int t) { int n = sc.nextInt(); int m = sc.nextInt(); graph = new List[n + 1]; boolean [] visited = new boolean [n + 1]; memo = new int [n + 1][]; toCount = new int [n + 1]; int from, to; for (int i = 0; i < m; ++i) { from = sc.nextInt(); to = sc.nextInt(); visited[to] = true; if (graph[from] == null) graph[from] = new ArrayList<>(); graph[from].add(to); toCount[to]++; } int result = 1; for (int i = 1; i <= n; ++i) { if (!visited[i]) { result = Math.max(result, dfs(i)[1]); } } System.out.println(result); } // streak, largest; private static int [] dfs (int node) { if (memo[node] != null) return memo[node]; int [] result = new int [] {1 , 1}; int [] arr; if (graph[node] != null) { for (int child : graph[node]) { arr = dfs(child); result[1] = Math.max(result[1], arr[1]); if (graph[node].size() > 1 && toCount[child] > 1) { result[1] = Math.max(result[1], 1 + arr[0]); result[0] = Math.max(result[0], 1 + arr[0]); } } } if (toCount[node] < 2) result[0] = 0; memo[node] = result; return result; } public static void print(int test, long result) { System.out.println("Case #" + test + ": " + result); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
aaa80b17f185c28a96199c46a984886e
train_107.jsonl
1651502100
You are given a directed acyclic graph, consisting of $$$n$$$ vertices and $$$m$$$ edges. The vertices are numbered from $$$1$$$ to $$$n$$$. There are no multiple edges and self-loops.Let $$$\mathit{in}_v$$$ be the number of incoming edges (indegree) and $$$\mathit{out}_v$$$ be the number of outgoing edges (outdegree) of vertex $$$v$$$.You are asked to remove some edges from the graph. Let the new degrees be $$$\mathit{in'}_v$$$ and $$$\mathit{out'}_v$$$.You are only allowed to remove the edges if the following conditions hold for every vertex $$$v$$$: $$$\mathit{in'}_v &lt; \mathit{in}_v$$$ or $$$\mathit{in'}_v = \mathit{in}_v = 0$$$; $$$\mathit{out'}_v &lt; \mathit{out}_v$$$ or $$$\mathit{out'}_v = \mathit{out}_v = 0$$$. Let's call a set of vertices $$$S$$$ cute if for each pair of vertices $$$v$$$ and $$$u$$$ ($$$v \neq u$$$) such that $$$v \in S$$$ and $$$u \in S$$$, there exists a path either from $$$v$$$ to $$$u$$$ or from $$$u$$$ to $$$v$$$ over the non-removed edges.What is the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$?
256 megabytes
import java.io.*; import java.util.*; public class CF1674G extends PrintWriter { CF1674G() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1674G o = new CF1674G(); o.main(); o.flush(); } int[] dp, eo, fo; int[][] ej; void append(int i, int j) { int o = eo[i]++; fo[j]++; if (o >= 2 && (o & o - 1) == 0) ej[i] = Arrays.copyOf(ej[i], o << 1); ej[i][o] = j; } void dfs(int i) { if (dp[i] != 0) return; int d = 0; for (int o = eo[i]; o-- > 0; ) { int j = ej[i][o]; if (eo[i] > 1 && fo[j] > 1) { dfs(j); d = Math.max(d, dp[j]); } } dp[i] = d + 1; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); dp = new int[n]; eo = new int[n]; ej = new int[n][2]; fo = new int[n]; while (m-- > 0) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; append(i, j); } int ans = 0; for (int i = 0; i < n; i++) { dfs(i); ans = Math.max(ans, dp[i]); } println(ans); } }
Java
["3 3\n1 2\n2 3\n1 3", "5 0", "7 8\n7 1\n1 3\n6 2\n2 3\n7 2\n2 4\n7 3\n6 3"]
2 seconds
["2", "1", "3"]
NoteIn the first example, you can remove edges $$$(1, 2)$$$ and $$$(2, 3)$$$. $$$\mathit{in} = [0, 1, 2]$$$, $$$\mathit{out} = [2, 1, 0]$$$. $$$\mathit{in'} = [0, 0, 1]$$$, $$$\mathit{out'} = [1, 0, 0]$$$. You can see that for all $$$v$$$ the conditions hold. The maximum cute set $$$S$$$ is formed by vertices $$$1$$$ and $$$3$$$. They are still connected directly by an edge, so there is a path between them.In the second example, there are no edges. Since all $$$\mathit{in}_v$$$ and $$$\mathit{out}_v$$$ are equal to $$$0$$$, leaving a graph with zero edges is allowed. There are $$$5$$$ cute sets, each contains a single vertex. Thus, the maximum size is $$$1$$$.In the third example, you can remove edges $$$(7, 1)$$$, $$$(2, 4)$$$, $$$(1, 3)$$$ and $$$(6, 2)$$$. The maximum cute set will be $$$S = \{7, 3, 2\}$$$. You can remove edge $$$(7, 3)$$$ as well, and the answer won't change.Here is the picture of the graph from the third example:
Java 11
standard input
[ "dfs and similar", "dp", "graphs" ]
2d3af7ca9bf074d03408d5ade3ddd14c
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$0 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges of the graph. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \le v, u \le n$$$; $$$v \neq u$$$) — the description of an edge. The given edges form a valid directed acyclic graph. There are no multiple edges.
2,000
Print a single integer — the maximum possible size of a cute set $$$S$$$ after you remove some edges from the graph and both indegrees and outdegrees of all vertices either decrease or remain equal to $$$0$$$.
standard output
PASSED
e9d0e5043c94035d911b9abb922aed46
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 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
9cb9ffb6a2f9327345564cc07e9763d1
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.lang.*; import java.util.*; public class ComdeFormces { public static int cc2; public static pair pr; public static long sum; public static int ind2; public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub // Reader.init(System.in); FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // OutputStream out = new BufferedOutputStream ( System.out ); int t=1; int tc=1; while(tc--!=0) { int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); int b[]=a.clone(); mergesort(b,0,n-1); int mn=(b[0]+1)/2+(b[1]+1)/2; for(int i=1;i<n-1;i++) { mn=Math.min(mn, a[i-1]/2 +a[i+1]/2+((a[i-1]>=1 || a[i+1]>=1)?1:0)); } for(int i=0;i<n-1;i++) { int vl1=Math.max(a[i], a[i+1]); int vl2=Math.min(a[i], a[i+1]); if(vl1>=2*vl2) { mn=Math.min(mn, (vl1+1)/2); } else { mn=Math.min(mn, (vl1+vl2+2)/3); } // mn=Math.min(mn, an+p); } log.write(mn+"\n"); log.flush(); } } static int ff(ArrayList<Integer> ar,int el) { int s=0; int e=ar.size()-1; // p(s,"s"); // p(e,"e"); while(s<=e) { int m=s+(e-s)/2; if(ar.get(m)==el) { s=m+1; e=m-1; break; } else if(ar.get(m)<el)s=m+1; else e=m-1; } int vl1=Integer.MAX_VALUE; int vl2=Integer.MAX_VALUE; if(e>=0)vl1=Math.abs(ar.get(e)-el); if(s<=ar.size()-1)vl2=Math.abs(ar.get(s)-el); return Math.min(vl1, vl2); } static int find(int el,int p[]) { if(p[el]<0)return el; return p[el]=find(p[el],p); } static boolean find(int a,int b,int p[]) { int p1=find(a,p); int p2=find(b,p); if(p1>=0 && p1==p2)return false; else { if(p[p1]<p[p2]) { p[p1]+=p[p2]; p[p2]=p1; } else { p[p2]+=p[p1]; p[p1]=p2; } return true; } } static long eval(ArrayList<ArrayList<Integer>> ar,int src,long f[], boolean vis[]) { long mn=Integer.MAX_VALUE; vis[src]=true; for(int p:ar.get(src)) { if(!vis[p]) { long s=eval(ar,p,f,vis); mn=Math.min(mn,s); sum+=s; } } if(src==0)return 0; if(mn==Integer.MAX_VALUE)return f[src]; sum-=mn; return Math.max(f[src], mn); } public static void radixSort(int a[]) { int n=a.length; int res[]=new int[n]; int p=1; for(int i=0;i<=8;i++) { int cnt[]=new int[10]; for(int j=0;j<n;j++) { a[j]=res[j]; cnt[(a[j]/p)%10]++; } for(int j=1;j<=9;j++) { cnt[j]+=cnt[j-1]; } for(int j=n-1;j>=0;j--) { res[cnt[(a[j]/p)%10]-1]=a[j]; cnt[(a[j]/p)%10]--; } p*=10; } } static int bits(long n) { int ans=0; while(n!=0) { if((n&1)==1)ans++; n>>=1; } return ans; } static long flor(ArrayList<Long> ar,long el) { int s=0; int e=ar.size()-1; while(s<=e) { int m=s+(e-s)/2; if(ar.get(m)==el)return ar.get(m); else if(ar.get(m)<el)s=m+1; else e=m-1; } return e>=0?e:-1; } public static int kadane(int a[]) { int sum=0,mx=Integer.MIN_VALUE; for(int i=0;i<a.length;i++) { sum+=a[i]; mx=Math.max(mx, sum); if(sum<0) sum=0; } return mx; } public static int m=1000000007; public static int mul(int a, int b) { return ((a%m)*(b%m))%m; } public static long mul(long a, long b) { return ((a%m)*(b%m))%m; } public static int add(int a, int b) { return ((a%m)+(b%m))%m; } public static long add(long a, long b) { return ((a%m)+(b%m))%m; } //debug public static <E> void p(E[][] a,String s) { System.out.println(s); for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } public static void p(int[] a,String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static void p(long[] a,String s) { System.out.print(s+"="); for(int i=0;i<a.length;i++)System.out.print(a[i]+" "); System.out.println(); } public static <E> void p(E a,String s){ System.out.println(s+"="+a); } public static <E> void p(ArrayList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(LinkedList<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(HashSet<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Stack<E> a,String s){ System.out.println(s+"="+a); } public static <E> void p(Queue<E> a,String s){ System.out.println(s+"="+a); } //utils static ArrayList<Integer> divisors(int n){ ArrayList<Integer> ar=new ArrayList<>(); for (int i=2; i<=Math.sqrt(n); i++){ if (n%i == 0){ if (n/i == i) { ar.add(i); } else { ar.add(i); ar.add(n/i); } } } return ar; } static ArrayList<Integer> prime(int n){ ArrayList<Integer> ar=new ArrayList<>(); int cnt=0; boolean pr=false; while(n%2==0) { ar.add(2); n/=2; } for(int i=3;i*i<=n;i+=2) { pr=false; while(n%i==0) { n/=i; ar.add(i); pr=true; } } if(n>2) ar.add(n); return ar; } 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 factmod(long n,long mod,long img) { if(n==0)return 1; long ans=1; long temp=1; while(n--!=0) { if(temp!=img) { ans=((ans%mod)*((temp)%mod))%mod; } temp++; } return ans%mod; } static int ncr(int n, int r){ if(r>n-r)r=n-r; int ans=1; for(int i=0;i<r;i++){ ans*=(n-i); ans/=(i+1); } return ans; } public static class trip{ int a,b; int c; public trip(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } public int compareTo(trip q) { return this.b-q.b; } } static void mergesort(int[] a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(int[] a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a[ptr1]<=a[ptr2]) { b[i]=a[ptr1]; ptr1++; i++; } else { b[i]=a[ptr2]; ptr2++; i++; } } while(ptr1<=mid) { b[i]=a[ptr1]; ptr1++; i++; } while(ptr2<=end) { b[i]=a[ptr2]; ptr2++; i++; } for(int j=start;j<=end;j++) { a[j]=b[j-start]; } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } public int compareTo(pair b) { return this.a-b.a; } // public int compareToo(pair b) { // return this.b-b.b; // } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } }
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
842780a5821e2c444960837259f85f10
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 Solution { static long[] fac; public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); /* // Do not delete this // Uncomment this before using nCrModPFermat fac = new long[200000 + 1]; fac[0] = 1; for (int i = 1; i <= 200000; i++) fac[i] = (fac[i - 1] * i % 1000000007); */ // int te = Reader.nextInt(); int te = 1; while(te-->0) { int n = Reader.nextInt(); int[] arr = new int[n]; int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE; for(int i = 0;i<n;i++){ arr[i] = Reader.nextInt(); if(arr[i]<min1){ min2 = min1; min1 = arr[i]; } else if(arr[i]<min2){ min2 = arr[i]; } } long ans = Long.MAX_VALUE; for(int i = 0;i<n-1;i++){ if(arr[i]>=arr[i+1]){ long diff = arr[i]-arr[i+1]; diff = Math.min(diff,arr[i+1]); long c = diff; int temp = arr[i]; temp -= 2*diff; if(arr[i+1]==diff){ c += (long)Math.ceil(temp/(double)2); // System.out.println(c+" i: "+i); } else{ c += 2*(temp/3); long rem = (temp)%3; if(rem==2){ c+=2; } else if(rem==1) c++; // System.out.println(c+" i: "+i); } ans = Math.min(ans,c); } else{ long diff = arr[i+1]-arr[i]; diff = Math.min(diff,arr[i]); long c = diff; int temp = arr[i+1]; temp -= 2*diff; if(arr[i]==diff){ c += (long)Math.ceil(temp/(double)2); } else{ c += 2*(temp/3); long rem = (temp)%3; if(rem==2){ c+=2; } else if(rem==1) c++; } ans = Math.min(ans,c); } if(i-1>=0){ long a1 = arr[i-1]; long a3 = arr[i+1]; if(a1>a3){ long t = a3 + (long)Math.ceil((a1-a3)/(double)2); ans = Math.min(ans,t); } else{ long t = a1 + (long)Math.ceil((a3-a1)/(double)2); ans = Math.min(ans,t); } } } // ans = Math.min(ans,(long)Math.ceil(min1/(double)2)+(long)Math.ceil(min2/(double)2)); output.write(ans+"\n"); } output.close(); } public static boolean isP(int n){ StringBuilder s1 = new StringBuilder(n+""); StringBuilder s2 = new StringBuilder(n+""); s2.reverse(); for(int i = 0;i<s1.length();i++){ if(s1.charAt(i)!=s2.charAt(i)) return false; } return true; } public static long[] factorial(int n){ long[] factorials = new long[n+1]; factorials[1] = 1; for(int i = 2;i<=n;i++){ factorials[i] = (factorials[i-1]*i)%((int)1e9+7); } return factorials; } public static long numOfBits(long n){ long ans = 0; while(n>0){ n = n & (n-1); ans++; } return ans; } public static long ceilOfFraction(long x, long y){ // ceil using integer division: ceil(x/y) = (x+y-1)/y // using double may go out of range. return (x+y-1)/y; } public static long power(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; } // Returns n^(-1) mod p public static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. public static long nCrModPFermat(int n, int r, int p) { if (n<r) return 0; if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long ncr(long n, long r) { long p = 1, k = 1; if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; long m = gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } public static boolean isPrime(long n){ if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; (long) i * i <= n; i = i + 6){ if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } public static int powOf2JustSmallerThanN(int n) { n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return n ^ (n >> 1); } public static int mergeSortAndCount(int[] arr, int l, int r) { int count = 0; if (l < r) { int m = (l + r) / 2; count += mergeSortAndCount(arr, l, m); count += mergeSortAndCount(arr, m + 1, r); count += mergeAndCount(arr, l, m, r); } return count; } public static int mergeAndCount(int[] arr, int l, int m, int r) { int[] left = Arrays.copyOfRange(arr, l, m + 1); 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; } public static void reverseArray(int[] arr,int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static long gcd(long a, long b){ if(a==0){ return b; } return gcd(b%a,a); } public static long lcm(long a, long b){ if(a>b) return a/gcd(b,a) * b; return b/gcd(a,b) * a; } public static long largeExponentMod(long x,long y,long mod){ // computing (x^y) % mod x%=mod; long ans = 1; while(y>0){ if((y&1)==1){ ans = (ans*x)%mod; } x = (x*x)%mod; y = y >> 1; } return ans; } public static boolean[] numOfPrimesInRange(long L, long R){ boolean[] isPrime = new boolean[(int) (R-L+1)]; Arrays.fill(isPrime,true); long lim = (long) Math.sqrt(R); for (long i = 2; i <= lim; i++){ for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){ isPrime[(int) (j - L)] = false; } } if (L == 1) isPrime[0] = false; return isPrime; } public static ArrayList<Long> primeFactors(long n){ ArrayList<Long> factorization = new ArrayList<>(); if(n%2==0){ factorization.add(2L); } while(n%2==0){ n/=2; } if(n%3==0){ factorization.add(3L); } while(n%3==0){ n/=3; } if(n%5==0){ factorization.add(5L); } while(n%5==0){ // factorization.add(5L); n/=5; } int[] increments = {4, 2, 4, 2, 4, 6, 2, 6}; int i = 0; for (long d = 7; d * d <= n; d += increments[i++]) { if(n%d==0){ factorization.add(d); } while (n % d == 0) { // factorization.add(d); n /= d; } if (i == 8) i = 0; } if (n > 1) factorization.add(n); return factorization; } } class DSU { int[] size, parent; int n; public DSU(int n){ this.n = n; size = new int[n]; parent = new int[n]; for(int i = 0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int u){ if(parent[u]==u){ return u; } return parent[u] = find(parent[u]); } public void merge(int u, int v){ u = find(u); v = find(v); if(u!=v){ if(size[u]>size[v]){ parent[v] = u; size[u] += size[v]; } else{ parent[u] = v; size[v] += size[u]; } } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
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
5505393b180bc3358a5cce54a3f6a579
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 Solution { public static void main(String[] args) throws IOException { int n = sc.nextInt(); int[] arr = sc.nextIntArray(n); long[] temp = new long[n]; temp[0] = Math.max((long) Math.ceil(arr[0] / 2.0), arr[1]); temp[n - 1] = Math.max((long) Math.ceil(arr[n - 1] / 2.0), arr[n - 2]); for (int i = 1; i < temp.length - 1; i++) { long third = Math.max(arr[i - 1], arr[i + 1]); long first = (long) Math.floor(arr[i - 1]/2.0) + (long) Math.floor(arr[i+1]/2.0)+1; temp[i] =Math.min(first, third); } long[] temp2 = new long[n]; for (int i = 0; i < temp2.length - 1; i++) { long x = Math.max(arr[i + 1], arr[i]); long y = Math.min(arr[i + 1], arr[i]); temp2[i] = 2*y <=x ? (int)Math.ceil(x/2.0):(int) Math.ceil((arr[i] + arr[i + 1]) / 3.0); } temp2[n - 1] = temp2[n - 2]; Arrays.sort(arr); Arrays.sort(temp); Arrays.sort(temp2); long min2 = (long) (Math.ceil(arr[0] / 2.0) + Math.ceil(arr[1] / 2.0)); pw.println(Math.min(Math.min(temp[0], temp2[0]), min2)); pw.close(); } 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; } 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 long getDiff(pair start, pair end) { return Math.abs(start.x - end.x) + Math.abs(start.y - end.y); } static HashMap Hash(int[] arr) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i : arr) { map.put(i, map.getOrDefault(i, 0) + 1); } return map; } static HashMap Hash(char[] arr) { HashMap<Character, Integer> map = new HashMap<>(); for (char i : arr) { map.put(i, map.getOrDefault(i, 0) + 1); } return map; } static boolean isPrime(int n) { if (n <= 1) return false; for (int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } public static long combination(long n, long r) { return factorial(n) / (factorial(n - r) * factorial(r)); } static long factorial(Long n) { if (n == 0) return 1; return n * factorial(n - 1); } static boolean isPalindrome(char[] str, int i, int j) { // While there are characters to compare while (i < j) { // If there is a mismatch if (str[i] != str[j]) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } public static double log2(int N) { double result = (Math.log(N) / Math.log(2)); return result; } public static double log4(int N) { double result = (Math.log(N) / Math.log(4)); return result; } public static int setBit(int mask, int idx) { return mask | (1 << idx); } public static int clearBit(int mask, int idx) { return mask ^ (1 << idx); } public static boolean checkBit(int mask, int idx) { return (mask & (1 << idx)) != 0; } 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(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long 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 Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } public static String toString(int[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } public static String toString(long[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } public static String toString(ArrayList arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.size(); i++) { sb.append(arr.get(i) + " "); } return sb.toString().trim(); } public static String toString(int[][] arr) { StringBuilder sb = new StringBuilder(); for (int[] i : arr) { sb.append(toString(i) + "\n"); } return sb.toString(); } public static String toString(boolean[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } public static String toString(Integer[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } public static String toString(String[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } public static String toString(char[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
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
18e7912af19baa315a86dbca99b9b389
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.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.math.BigInteger; public final class Main{ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(new FileWriter(problemName + ".out")); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } static Kattio sc = new Kattio(); static long mod = 998244353l; static PrintWriter out =new PrintWriter(System.out); //Heapify function to maintain heap property. public static void swap(int i,int j,int arr[]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void swap(int i,int j,long arr[]) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void swap(int i,int j,char arr[]) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static String endl = "\n" , gap = " "; public static void main(String[] args)throws IOException { int t =1; // List<Integer> list = new ArrayList<>(); // int MAX = (int)4e4; // for(int i =1;i<=MAX;i++) { // if(isPalindrome(i + "")) list.add(i); // } // // System.out.println(list); // long dp[] = new long[MAX +1]; // dp[0] = 1; // long mod = (long)(1e9+7); // for(int x : list) { // for(int i =1;i<=MAX;i++) { // if(i >= x) { // dp[i] += dp[i-x]; // dp[i] %= mod; // } // } // } // int MAK = (int)1e6; // boolean seive[] = new boolean[MAK]; // Arrays.fill(seive , true); // seive[1] = false; // seive[0] = false; // for (int i = 1; i < MAK; i++) { // if(seive[i]) { // for (int j = i+i; j < MAK; j+=i) { // seive[j] = false; // } // } // } // for (int i = 1; i <= MAK; i++) { // seive[i] += seive[i - 1]; // } int test_case = 1; while(t-->0) { // out.write("Case #"+(test_case++)+": "); solve(); } out.close(); } static HashMap<Integer , Boolean>dp; public static void solve()throws IOException { int n = ri() + 2; int arr[] = new int[n]; arr[0] = (int)1e9; arr[n-1] = (int)1e9; for(int i =1;i<n-1;i++) { arr[i] = ri(); } int clone[] = arr.clone(); // System.out.println(Arrays.toString(arr)); Arrays.sort(clone); int ans = (clone[0]+1)/2 + (clone[1]+1)/2; // System.out.println(Arrays.toString(clone)); for(int i =1;i<n-1;i++) { int min = Math.min(arr[i],arr[i-1]); int max = Math.max(arr[i],arr[i-1]); if(min*2 <= max) { ans = Math.min(ans ,(max+1)/2); } else { ans = Math.min(ans , (max + min +2)/3); } min = Math.min(arr[i],arr[i+1]); max = Math.max(arr[i],arr[i+1]); if(min*2 <= max) { ans = Math.min(ans ,(max+1)/2); } else { ans = Math.min(ans , (max + min +2)/3); } ans = Math.min(ans , (arr[i-1]+arr[i+1]+1)/2); } System.out.println(ans); } public static long callfun(int n) { if(n == 1) return 1; return n + n*callfun(n-1); } public static double getSlope(int a , int b,int x,int y) { if(a-x == 0) return Double.MAX_VALUE; if(b-y == 0) return 0.0; return ((double)b-(double)y)/((double)a-(double)x); } public static int callfun(int a[], int []b) { HashMap<Integer , Integer> map = new HashMap<>(); int n = a.length; for(int i =0;i<b.length;i++) { map.put(b[i] , i); } HashMap<Integer , Integer> cnt = new HashMap<>(); for(int i =0;i<n;i++) { int move = (map.get(a[i])-i+n)%n; cnt.put(move , cnt.getOrDefault(move,0) + 1); } int max =0; for(int x : cnt.keySet()) max = Math.max(max , cnt.get(x)); return max; } public static boolean collinearr(long a[] , long b[] , long c[]) { return (b[1]-a[1])*(b[0]-c[0]) == (b[0]-a[0])*(b[1]-c[1]); } public static boolean isSquare(int sum) { int root = (int)Math.sqrt(sum); return root*root == sum; } public static boolean canPlcae(int prev,int len , int sum,int arr[],int idx) { // System.out.println(sum + " is sum prev " + prev); if(len == 0) { if(isSquare(sum)) return true; return false; } for(int i = prev;i<=9;i++) { arr[idx] = i; if(canPlcae(i, len-1,sum + i*i,arr,idx + 1)) { return true; } } return false; } public static boolean isPalindrome(String s) { int i =0 , j = s.length() -1; while(i <= j && s.charAt(i) == s.charAt(j)) { i++; j--; } return i>j; } // digit dp hint; public static long callfun(String num , int N, int last ,int secondLast ,int bound ,long dp[][][][]) { if(N == 1) { if(last == -1 || secondLast == -1) return 0; long answer = 0; int max = (bound==1)?(num.charAt(num.length()-N)-'0') : 9; for(int i = 0;i<=max;i++) { if(last > secondLast && last > i) { answer++; } if(last < secondLast && last < i) { answer++; } } return answer; } if(secondLast == -1 || last == -1 ){ long answer = 0l; int max = (bound==1)?(num.charAt(num.length()-N)-'0') : 9; for(int i =0;i<=max;i++) { int nl , nsl , newbound = bound==0?0:i==max?1:0; if(last == - 1&& secondLast == -1 && i == 0) { nl = -1 ; nsl = -1; } else { nl = i;nsl = last; } long temp = callfun(num , N-1 , nl , nsl ,newbound, dp); answer += temp; if(last != -1 && secondLast != -1 &&((last > secondLast && last > i)||(last < secondLast && last < i))) answer++; } return answer; } if(dp[N][last][secondLast][bound] != -1) return dp[N][last][secondLast][bound]; long answer = 0l; int max = (bound==1)?(num.charAt(num.length()-N)-'0') : 9; for(int i =0;i<=max;i++) { int nl , nsl , newbound = bound==0?0:i==max?1:0; if(last == - 1&& secondLast == -1 && i == 0) { nl = -1 ; nsl = -1; } else { nl = i;nsl = last; } long temp = callfun(num , N-1 , nl , nsl ,newbound,dp); answer += temp; if(last != -1 && secondLast != -1 &&((last > secondLast && last > i)||(last < secondLast && last < i))) answer++; } return dp[N][last][secondLast][bound] = answer; } public static Long callfun(int index ,int pair,int arr[],Long dp[][]) { long mod = (long)998244353l; if(index >= arr.length) return 1l; if(dp[index][pair] != null) return dp[index][pair]; Long sum = 0l , ans = 0l; if(arr[index]%2 == pair) { return dp[index][pair] = callfun(index + 1,pair^1 , arr,dp)%mod + callfun(index + 1 ,pair , arr , dp)%mod; } else { return dp[index][pair] = callfun(index + 1,pair , arr,dp)%mod; } // for(int i =index;i<arr.length;i++) { // sum += arr[i]; // if(sum%2 == pair) { // ans = ans + callfun(i + 1,pair^1,arr , dp)%mod; // ans%=mod; // } // } // return dp[index][pair] = ans; } public static boolean callfun(int index , int n,int neg , int pos , String s) { if(neg < 0 || pos < 0) return false; if(index >= n) return true; if(s.charAt(0) == 'P') { if(neg <= 0) return false; return callfun(index + 1,n , neg-1 , pos , s.charAt(1) + "N"); } else { if(pos <= 0) return false; return callfun(index + 1 , n , neg , pos-1 , s.charAt(1) + "P"); } } public static void getPerm(int n , char arr[] , String s ,List<String>list) { if(n == 0) { list.add(s); return; } for(char ch : arr) { getPerm(n-1 , arr , s+ ch,list); } } public static int getLen(int i ,int j , char s[]) { while(i >= 0 && j < s.length && s[i] == s[j]) { i--; j++; } i++; j--; if(i>j) return 0; return j-i + 1; } public static int getMaxCount(String x) { char s[] = x.toCharArray(); int max = 0; int n = s.length; for(int i =0;i<n;i++) { max = Math.max(max,Math.max(getLen(i , i,s) , getLen(i ,i+1,s))); } return max; } public static double getDis(int arr[][] , int x, int y) { double ans = 0.0; for(int a[] : arr) { int x1 = a[0] , y1 = a[1]; ans += Math.sqrt((x-x1)*(x-x1) + (y-y1)*(y-y1)); } return ans; } public static boolean valid(String x ) { if(x.length() == 0) return true; if(x.length() == 1) return false; char s[] = x.toCharArray(); if(x.length() == 2) { if(s[0] == s[1]) { return false; } return true; } int r = 0 , b = 0; for(char ch : x.toCharArray()) { if(ch == 'R') r++; else b++; } return (r >0 && b >0); } public static long callfun(int day , int k, int limit,int n) { if(k > limit) return 0; if(day > n) return 1; long ans = callfun(day + 1 , k , limit, n)*k + callfun(day + 1,k+1,limit,n)*(k+1); return ans; } public static void primeDivisor(HashMap<Long , Long >cnt , long num) { for(long i = 2;i*i<=num;i++) { while(num%i == 0) { cnt.put(i ,(cnt.getOrDefault(i,0l) + 1)); num /= i; } } if(num > 2) { cnt.put(num ,(cnt.getOrDefault(num,0l) + 1)); } } public static boolean isSubsequene(char a[], char b[] ) { int i =0 , j = 0; while(i < a.length && j <b.length) { if(a[i] == b[j]) { j++; } i++; } return j >= b.length; } public static long fib(int n ,long M) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { long[][] mat = {{1, 1}, {1, 0}}; mat = pow(mat, n-1 , M); return mat[0][0]; } } public static long[][] pow(long[][] mat, int n ,long M) { if (n == 1) return mat; else if (n % 2 == 0) return pow(mul(mat, mat , M), n/2 , M); else return mul(pow(mul(mat, mat,M), n/2,M), mat , M); } static long[][] mul(long[][] p, long[][] q,long M) { long a = (p[0][0]*q[0][0] + p[0][1]*q[1][0])%M; long b = (p[0][0]*q[0][1] + p[0][1]*q[1][1])%M; long c = (p[1][0]*q[0][0] + p[1][1]*q[1][0])%M; long d = (p[1][0]*q[0][1] + p[1][1]*q[1][1])%M; return new long[][] {{a, b}, {c, d}}; } public static long[] kdane(long arr[]) { int n = arr.length; long dp[] = new long[n]; dp[0] = arr[0]; long ans = dp[0]; for(int i = 1;i<n;i++) { dp[i] = Math.max(dp[i-1] + arr[i] , arr[i]); ans = Math.max(ans , dp[i]); } return dp; } public static void update(int low , int high , int l , int r, int val , int treeIndex ,int tree[]) { if(low > r || high < l || high < low) return; if(l <= low && high <= r) { System.out.println("At " +low + " and " + high + " ans ttreeIndex " + treeIndex); tree[treeIndex] += val; return; } int mid = low + (high - low)/2; update(low , mid , l , r , val , treeIndex*2 + 1, tree); update(mid + 1 , high , l , r , val , treeIndex*2 + 2 , tree); } static int colx[] = {1 ,-1, 0,0 , 1,1,-1,-1}; static int coly[] = {0 ,0, 1,-1,1,-1,1,-1}; public static void reverse(char arr[]) { int i =0 , j = arr.length-1; while(i < j) { swap(i , j , arr); i++; j--; } } public static long[] reverse(long arr[]) { long newans[] = arr.clone(); int i =0 , j = arr.length-1; while(i < j) { swap(i , j , newans); i++; j--; } return newans; } public static long inverse(long x , long mod) { return pow(x , mod -2 , mod); } public static int maxArray(int arr[]) { int ans = arr[0] , n = arr.length; for(int i =1;i<n;i++) { ans = Math.max(ans , arr[i]); } return ans; } public static long maxArray(long arr[]) { long ans = arr[0]; int n = arr.length; for(int i =1;i<n;i++) { ans = Math.max(ans , arr[i]); } return ans; } public static int minArray(int arr[]) { int ans = arr[0] , n = arr.length; for(int i =0;i<n;i++ ) { ans = Math.min(ans ,arr[i]); } return ans; } public static long minArray(long arr[]) { long ans = arr[0]; int n = arr.length; for(int i =0;i<n;i++ ) { ans = Math.min(ans ,arr[i]); } return ans; } public static int sumArray(int arr[]) { int ans = 0; for(int x : arr) { ans += x; } return ans; } public static long sumArray(long arr[]) { long ans = 0; for(long x : arr) { ans += x; } return ans; } public static long rl() { return sc.nextLong(); } public static char[] rac() { return sc.next().toCharArray(); } public static String rs() { return sc.next(); } public static char rc() { return sc.next().charAt(0); } public static int [] rai(int n) { int ans[] = new int[n]; for(int i =0;i<n;i++) { ans[i] = sc.nextInt(); } return ans; } public static long [] ral(int n) { long ans[] = new long[n]; for(int i =0;i<n;i++) { ans[i] = sc.nextLong(); } return ans; } public static int ri() { return sc.nextInt(); } public static int getValue(int num ) { int ans = 0; while(num > 0) { ans++; num = num&(num-1); } return ans; } public static boolean isValid(int x ,int y , int n,char arr[][],boolean visited[][][][]) { return x>=0 && x<n && y>=0 && y <n && !(arr[x][y] == '#'); } // public static Pair join(Pair a , Pair b) { // Pair res = new Pair(Math.min(a.min , b.min) , Math.max(a.max , b.max) , a.count + b.count); // return res; // } // segment tree query over range // public static int query(int node,int l , int r,int a,int b ,Pair tree[] ) { // if(tree[node].max < a || tree[node].min > b) return 0; // if(l > r) return 0; // if(tree[node].min >= a && tree[node].max <= b) { // return tree[node].count; // } // int mid = l + (r-l)/2; // int ans = query(node*2 ,l , mid ,a , b , tree) + query(node*2 +1,mid + 1, r , a , b, tree); // return ans; // } // // segment tree update over range // public static void update(int node, int i , int j ,int l , int r,long value, long arr[] ) { // if(l >= i && j >= r) { // arr[node] += value; // return; // } // if(j < l|| r < i) return; // int mid = l + (r-l)/2; // update(node*2 ,i ,j ,l,mid,value, arr); // update(node*2 +1,i ,j ,mid + 1,r, value , arr); // } public static long pow(long a , long b , long mod) { if(b == 1) return a; if(b == 0) return 1; long ans = pow(a , b/2 , mod)%mod; if(b%2 == 0) { return (ans*ans)%mod; } else { return ((ans*ans)%mod*a)%mod; } } public static long pow(long a , long b ) { if(b == 1) return a; if(b == 0) return 1; long ans = pow(a , b/2); if(b%2 == 0) { return (ans*ans); } else { return ((ans*ans)*a); } } public static boolean isVowel(char ch) { if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true; if((ch == 'A' || ch == 'E'||ch == 'I' || ch == 'O' || ch == 'U')) return true; return false; } public static int getFactor(int num) { if(num==1) return 1; int ans = 2; int k = num/2; for(int i = 2;i<=k;i++) { if(num%i==0) ans++; } return Math.abs(ans); } public static int[] readarr()throws IOException { int n = sc.nextInt(); int arr[] = new int[n]; for(int i =0;i<n;i++) { arr[i] = sc.nextInt(); } return arr; } public static boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0); } public static boolean isPrime(long num) { if(num==1) return false; if(num<=3) return true; if(num%2==0||num%3==0) return false; for(long i =5;i*i<=num;i+=6) { if(num%i==0 || num%(i+2) == 0) return false; } return true; } public static boolean isPrime(int num) { // System.out.println("At pr " + num); if(num==1) return false; if(num<=3) return true; if(num%2==0||num%3==0) return false; for(int i =5;i*i<=num;i+=6) { if(num%i==0 || num%(i+2) == 0) return false; } return true; } // public static boolean isPrime(long num) { // if(num==1) return false; // if(num<=3) return true; // if(num%2==0||num%3==0) return false; // for(int i =5;i*i<=num;i+=6) { // if(num%i==0) return false; // } // return true; // } public static long gcd(long a , long b) { if (b == 0) return a; return gcd(b, a % b); } public static int gcd(int a , int b) { if (b == 0) return a; return gcd(b, a % b); } public static int get_gcd(int a , int b) { if (b == 0) return a; return gcd(b, a % b); } public static long get_gcd(long a , long b) { if (b == 0) return a; return gcd(b, a % b); } // public static long fac(long num) { // long ans = 1; // int mod = (int)1e9+7; // for(long i = 2;i<=num;i++) { // ans = (ans*i)%mod; // } // 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 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
50cc907c8606780b62333e4f2fc048ca
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.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.security.cert.X509CRL; import java.util.*; import java.lang.*; import java.util.stream.Collector; import java.util.stream.Collectors; @SuppressWarnings("unused") public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; static String OUTPUT = ""; //global //private final static long BASE = 998244353L; private final static int ALPHABET = (int)('z') - (int)('a') + 1; private final static int BASE = 1000000007; private final static int INF_I = (1<<31)-1; private final static long INF_L = (1l<<63)-1; private final static int MAXN = 100100; private final static int MAXK = 31; private static boolean isOk(int[] A, int shoot) { for (int i=0;i+1<A.length;i++) { int mi = (A[i]+A[i+1]+2)/3; if (mi<=shoot && A[i] <= 2*shoot && A[i+1] <= 2*shoot) return true; } for (int i=1;i+1<A.length;i++) { if ((A[i+1] + A[i-1] + 1)/2 <=shoot) return true; } return false; } static void solve() { int ntest = 1; for (int test=0;test<ntest;test++) { int N = readInt(); int[] A = readIntArray(N); int mi1=INF_I, mi2=INF_I; for (int i=0;i<N;i++) { if (mi1 >= A[i]) { mi2 = mi1; mi1 = A[i]; } else if (mi2 >= A[i]) { mi2 = A[i]; } } int lo=0, hi=(mi1+1)/2 + (mi2+1)/2; int ans=hi; while (lo<=hi) { int mid = (lo+hi)/2; if (isOk(A, mid)) { ans = mid; hi = mid-1; } else { lo = mid+1; } } out.println(ans); } } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); if (INPUT=="") { is = System.in; } else { File file = new File(INPUT); is = new FileInputStream(file); } if (OUTPUT == "") out = new PrintWriter(System.out); else out = new PrintWriter(OUTPUT); solve(); out.flush(); long G = System.currentTimeMillis(); } private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> { private T x; private T y; public Point(T x, T y) { this.x = x; this.y = y; } public T getX() {return x;} public T getY() {return y;} @Override public int compareTo(Point<T> o) { int cmp = x.compareTo(o.getX()); if (cmp==0) return y.compareTo(o.getY()); return cmp; } } private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> { public ClassComparator() {} @Override public int compare(T a, T b) { return a.compareTo(b); } } private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> { public ListComparator() {} @Override public int compare(List<T> o1, List<T> o2) { for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) { int c = o1.get(i).compareTo(o2.get(i)); if (c != 0) { return c; } } return Integer.compare(o1.size(), o2.size()); } } private static boolean eof() { if(lenbuf == -1)return true; int lptr = ptrbuf; while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false; try { is.mark(1000); while(true){ int b = is.read(); if(b == -1){ is.reset(); return true; }else if(!isSpaceChar(b)){ is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inbuf = new byte[1024]; static int lenbuf = 0, ptrbuf = 0; private static int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } // private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); } private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private static double readDouble() { return Double.parseDouble(readString()); } private static char readChar() { return (char)skip(); } private static String readString() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private static char[] readChar(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readTable(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = readChar(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = readInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i=0;i<n;i++) a[i] = readLong(); return a; } private static int readInt() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static long readLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); } }
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
9c4832a11f12a0aae8605550a760f581
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
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA import java.util.*; import java.util.Map.Entry; import java.util.stream.*; import java.lang.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.*; public class CodeForces { static private final String INPUT = "input.txt"; static private final String OUTPUT = "output.txt"; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static DecimalFormat df = new DecimalFormat("0.00000"); final static int mod = (int) (1e9 + 7); final static int MAX = Integer.MAX_VALUE; final static int MIN = Integer.MIN_VALUE; final static long INF = Long.MAX_VALUE; final static long NEG_INF = Long.MIN_VALUE; static Random rand = new Random(); // ======================= MAIN ================================== public static void main(String[] args) throws IOException { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; // ==== start ==== input(); preprocess(); int t = 1; // t = readInt(); while (t-- > 0) { solve(); } out.flush(); // ==== end ==== if (!oj) System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } private static void solve() throws IOException { int n = readInt(); int[] arr = readIntArray(n); int min = MAX, min2 = MAX; for (int i = 0; i < n; i++) { if (arr[i] < min) { min2 = min; min = arr[i]; } else if (arr[i] < min2) min2 = arr[i]; } int ans = (min + 1) / 2 + (min2 + 1) / 2; for (int i = 1; i < n - 1; i++) { min = Math.min(arr[i - 1], arr[i + 1]); min2 = Math.abs(arr[i - 1] - arr[i + 1]); ans = Math.min(ans, min + (min2 + 1) / 2); } for (int i = 1; i < n; i++) { min = Math.min(arr[i], arr[i - 1]); min2 = Math.max(arr[i], arr[i - 1]); int x = (min2 + (min2 - min) + 2) / 3, y = (min2 + min - 3 * x + 2) / 3; if (x <= 0) y = Math.max(min2, (min + 1) / 2); if (y <= 0) x = Math.max(min, (min2 + 1) / 2); ans = Math.min(ans, Math.max(x, 0) + Math.max(y, 0)); } out.println(ans); } private static void preprocess() throws IOException { } // cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces // javac CodeForces.java // java CodeForces // javac CodeForces.java && java CodeForces // ==================== CUSTOM CLASSES ================================ static class Pair { int first, second; Pair(int f, int s) { first = f; second = s; } public int compareTo(Pair o) { if (this.first == o.first) return this.second - o.second; return this.first - o.first; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (this.getClass() != obj.getClass()) return false; Pair other = (Pair) (obj); if (this.first != other.first) return false; if (this.second != other.second) return false; return true; } @Override public int hashCode() { return this.first ^ this.second; } @Override public String toString() { return this.first + " " + this.second; } } static class DequeNode { DequeNode prev, next; int val; DequeNode(int val) { this.val = val; } DequeNode(int val, DequeNode prev, DequeNode next) { this.val = val; this.prev = prev; this.next = next; } } // ======================= FOR INPUT ================================== private static void input() { FileInputStream instream = null; PrintStream outstream = null; try { instream = new FileInputStream(INPUT); outstream = new PrintStream(new FileOutputStream(OUTPUT)); System.setIn(instream); System.setOut(outstream); } catch (Exception e) { System.err.println("Error Occurred."); } br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(readLine()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readString() throws IOException { return next(); } static String readLine() throws IOException { return br.readLine().trim(); } static int[] readIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = readInt(); return arr; } static int[][] read2DIntArray(int n, int m) throws IOException { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) arr[i] = readIntArray(m); return arr; } static List<Integer> readIntList(int n) throws IOException { List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readInt()); return list; } static long[] readLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = readLong(); return arr; } static long[][] read2DLongArray(int n, int m) throws IOException { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) arr[i] = readLongArray(m); return arr; } static List<Long> readLongList(int n) throws IOException { List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(readLong()); return list; } static char[] readCharArray(int n) throws IOException { return readString().toCharArray(); } static char[][] readMatrix(int n, int m) throws IOException { char[][] mat = new char[n][m]; for (int i = 0; i < n; i++) mat[i] = readCharArray(m); return mat; } // ========================= FOR OUTPUT ================================== private static void printIList(List<Integer> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printLList(List<Long> list) { for (int i = 0; i < list.size(); i++) out.print(list.get(i) + " "); out.println(" "); } private static void printIArray(int[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DIArray(int[][] arr) { for (int i = 0; i < arr.length; i++) printIArray(arr[i]); } private static void printLArray(long[] arr) { for (int i = 0; i < arr.length; i++) out.print(arr[i] + " "); out.println(" "); } private static void print2DLArray(long[][] arr) { for (int i = 0; i < arr.length; i++) printLArray(arr[i]); } private static void yes() { out.println("YES"); } private static void no() { out.println("NO"); } // ====================== TO CHECK IF STRING IS NUMBER ======================== private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static boolean isLong(String s) { try { Long.parseLong(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } // ==================== FASTER SORT ================================ private static void sort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(int[] arr) { int n = arr.length; List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void sort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } private static void reverseSort(long[] arr) { int n = arr.length; List<Long> list = new ArrayList<>(n); for (int i = 0; i < n; i++) list.add(arr[i]); Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, int mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static int multiply(int a, int b) { return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod); } private static int divide(int a, int b) { return multiply(a, mod_pow(b, mod - 2, mod)); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } private static long nCr(long n, long r) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans *= i; for (long i = 2; i <= n - r; i++) ans /= i; return ans; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } // ==================== Primes using Seive ===================== private static List<Integer> getPrimes(int n) { boolean[] prime = new boolean[n + 1]; Arrays.fill(prime, true); for (int i = 2; 1L * i * i <= n; i++) if (prime[i]) for (int j = i * i; j <= n; j += i) prime[j] = false; // return prime; List<Integer> list = new ArrayList<>(); for (int i = 2; i <= n; i++) if (prime[i]) list.add(i); return list; } private static int[] SeivePrime(int n) { int[] primes = new int[n]; for (int i = 0; i < n; i++) primes[i] = i; for (int i = 2; 1L * i * i < n; i++) { if (primes[i] != i) continue; for (int j = i * i; j < n; j += i) if (primes[j] == j) primes[j] = i; } return primes; } // ==================== STRING FUNCTIONS ================================ private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } // check if a is subsequence of b private static boolean isSubsequence(String a, String b) { int idx = 0; for (int i = 0; i < b.length() && idx < a.length(); i++) if (a.charAt(idx) == b.charAt(i)) idx++; return idx == a.length(); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } // ==================== LIS & LNDS ================================ private static int LIS(int arr[], int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find1(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) >= val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } // =============== Lower Bound & Upper Bound =========== // less than or equal private static int lower_bound(List<Integer> list, int val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(List<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(List<Long> list, long val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== UNION FIND ===================== private static int find(int x, int[] parent) { if (parent[x] == x) return x; return parent[x] = find(parent[x], parent); } private static boolean union(int x, int y, int[] parent, int[] rank) { int lx = find(x, parent), ly = find(y, parent); if (lx == ly) return false; if (rank[lx] > rank[ly]) parent[ly] = lx; else if (rank[lx] < rank[ly]) parent[lx] = ly; else { parent[lx] = ly; rank[ly]++; } return true; } // ==================== TRIE ================================ static class Trie { class Node { Node[] children; boolean isEnd; Node() { children = new Node[26]; } } Node root; Trie() { root = new Node(); } void insert(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) curr.children[ch - 'a'] = new Node(); curr = curr.children[ch - 'a']; } curr.isEnd = true; } boolean find(String word) { Node curr = root; for (char ch : word.toCharArray()) { if (curr.children[ch - 'a'] == null) return false; curr = curr.children[ch - 'a']; } return curr.isEnd; } } // ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ================== public static class SegmentTree { int n; long[] arr, tree, lazy; SegmentTree(long arr[]) { this.arr = arr; this.n = arr.length; this.tree = new long[(n << 2)]; this.lazy = new long[(n << 2)]; build(1, 0, n - 1); } void build(int id, int start, int end) { if (start == end) tree[id] = arr[start]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; build(left, start, mid); build(right, mid + 1, end); tree[id] = tree[left] + tree[right]; } } void update(int l, int r, long val) { update(1, 0, n - 1, l, r, val); } void update(int id, int start, int end, int l, int r, long val) { distribute(id, start, end); if (end < l || r < start) return; if (start == end) tree[id] += val; else if (l <= start && end <= r) { lazy[id] += val; distribute(id, start, end); } else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; update(left, start, mid, l, r, val); update(right, mid + 1, end, l, r, val); tree[id] = tree[left] + tree[right]; } } long query(int l, int r) { return query(1, 0, n - 1, l, r); } long query(int id, int start, int end, int l, int r) { if (end < l || r < start) return 0L; distribute(id, start, end); if (start == end) return tree[id]; else if (l <= start && end <= r) return tree[id]; else { int mid = (start + end) / 2, left = (id << 1), right = left + 1; return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r); } } void distribute(int id, int start, int end) { if (start == end) tree[id] += lazy[id]; else { tree[id] += lazy[id] * (end - start + 1); lazy[(id << 1)] += lazy[id]; lazy[(id << 1) + 1] += lazy[id]; } lazy[id] = 0; } } // ==================== FENWICK TREE ================================ static class FT { int n; int[] arr; int[] tree; FT(int[] arr, int n) { this.arr = arr; this.n = n; this.tree = new int[n + 1]; for (int i = 1; i <= n; i++) { update(i, arr[i - 1]); } } FT(int n) { this.n = n; this.tree = new int[n + 1]; } // 1 based indexing void update(int idx, int val) { while (idx <= n) { tree[idx] += val; idx += idx & -idx; } } // 1 based indexing long query(int l, int r) { return getSum(r) - getSum(l - 1); } long getSum(int idx) { long ans = 0L; while (idx > 0) { ans += tree[idx]; idx -= idx & -idx; } return ans; } } // ==================== BINARY INDEX TREE ================================ static class BIT { long[][] tree; int n, m; BIT(int[][] mat, int n, int m) { this.n = n; this.m = m; tree = new long[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { update(i, j, mat[i - 1][j - 1]); } } } void update(int x, int y, int val) { while (x <= n) { int t = y; while (t <= m) { tree[x][t] += val; t += t & -t; } x += x & -x; } } long query(int x1, int y1, int x2, int y2) { return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1); } long getSum(int x, int y) { long ans = 0L; while (x > 0) { int t = y; while (t > 0) { ans += tree[x][t]; t -= t & -t; } x -= x & -x; } return ans; } } }
Java
["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
bbbfa738525290a1ff1649f5877feac7
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 temp { class Pair{ int i; int j; Pair(int i,int j){ this.i = i; this.j = j; } } 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 [] arr2 = Arrays.copyOf(arr,n); // for(int a:arr2)System.out.print(a + " "); long gbmin = 0; Arrays.sort(arr2); gbmin = (long)(arr2[0]+1)/2 + (long)(arr2[1]+1)/2; for(int i = 0;i<n-2;i++){ gbmin = Math.min(gbmin,Math.max(arr[i],arr[i+2])); if(arr[i]%2==1 || arr[i+2]%2==1)gbmin = Math.min(gbmin,(long)((long)arr[i]/2+(long)arr[i+2]/2 + 1)); } for(int i=0;i<n-1;i++){ long mn = Long.MAX_VALUE; long mx = Long.MIN_VALUE; mn = Math.min(arr[i],arr[i+1]); mx = Math.max(arr[i],arr[i+1]); if(mx > 2*mn)gbmin=Math.min(gbmin,(mx+1)/2); // if(arr[i]%2==1 || arr[i+2]%2==1)ans++; else gbmin = Math.min(gbmin,(mn + mx + 2)/3); } // System.out.println(); System.out.println(gbmin); } // public static boolean recur(int [][] m,ArrayList<Pair> check){ // boolean reached = false; // for(int k=0;k<check.size();k++){ // int i = check.get(k).i; // int j = check.get(k).j; // if(i==0 && j==0)reached = true; // // System.out.println("i" + i + "j" + j); // if(!boundary(m, i, j))return false; // } // if(reached)return true; // ArrayList<Pair> temp = new ArrayList<>(); // for(int k=0;k<check.size();k++){ // int i = check.get(k).i; // int j = check.get(k).j-1; // Pair ob1 = new temp().new Pair(i,j); // temp.add(ob1); // } // boolean left = recur(m,temp); // if(left)return true; // temp = new ArrayList<>(); // for(int k=0;k<check.size();k++){ // int i = check.get(k).i-1; // int j = check.get(k).j; // Pair ob1 = new temp().new Pair(i,j); // temp.add(ob1); // } // boolean up = recur(m,temp); // if(up || left)return true; // return false; // } // public static boolean boundary(int [][] m,int i,int j){ // if(i<0 || j<0 ||i>=m.length || j>m[0].length)return false; // return true; // } }
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
3f4b67e322ab1b1b4ed8401e948f9c9e
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 IOException{ FastReader fr=new FastReader(); PrintWriter pw=new PrintWriter(System.out); int n=fr.nextInt(); int [] arr=new int[n]; int a=1000001,b=1000001; for(int i=0;i<n;i++) { arr[i] = fr.nextInt(); if(arr[i]<=a){ b=a; a=arr[i]; } else if(arr[i]<b) b=arr[i]; } int result=(a+1)/2 + (b+1)/2; for(int i=0;i<n-1;i++){ result=Math.min(result, Math.max((Math.max(arr[i]+1,arr[i+1]+1))/2, (arr[i]+arr[i+1]+2)/3)); if(i>0) result = Math.min(result,Math.min(arr[i - 1], arr[i + 1]) + (Math.abs(arr[i - 1] - arr[i + 1])+1)/ 2); } pw.println(result); pw.close(); } 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
6b9d3c47bcc082ef0130821fadf5f3e4
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 E { static Scanner sc = new Scanner(System.in); static TreeMap<Integer, Integer> map; static StringBuilder sb; public static void main(String[] args) { // TODO Auto-generated method stub sb = new StringBuilder(); solve(0); System.out.println(sb); } private static void solve(int t) { int n = sc.nextInt(); int [] arr = new int [n]; for (int i = 0; i < n; ++i) { arr[i] = sc.nextInt(); } map = new TreeMap<>(); for (int num : arr) { map.put(num, map.getOrDefault(num, 0) + 1 ); } int current, prev, next; int newVal; int result = 1_000_000_000; int shots; prev = 0; next = 0; int min; for (int i = 0; i < arr.length; ++i) { current = arr[i]; newVal = map.get(current) - 1; if (newVal == 0) map.remove(current); else map.put(current, newVal); if (i > 0 && i < arr.length - 1) { int val = Math.min(arr[i - 1], arr[i + 1]); int d = Math.max(arr[i - 1], arr[i + 1]) - val; val += (d + 1)/2; result = Math.min(result, val); } shots = (current + 1) / 2; if (i > 0) { prev = arr[i - 1]; prev -= shots; prev = Math.max(0, prev); updateMap(arr[i - 1], prev); } if (i < arr.length - 1) { next = arr[i + 1]; next -= shots; next = Math.max(0, next); updateMap(arr[i + 1], next); } //System.out.println(map); min = map.firstKey(); shots += (min + 1)/2; result = Math.min(result, shots); //System.out.println(result); map.put(current, map.getOrDefault(current, 0) + 1); if (i > 0) { updateMap(prev , arr[i - 1]); } if (i < arr.length - 1) { updateMap(next , arr[i + 1]); } } int max; for (int i = 1; i < arr.length; ++i) { prev = arr[i]; next = arr[i - 1]; min = Math.min(prev, next); max = Math.max(prev, next); if (max >= 2*min) continue; int tot = (2 * max - min + 2)/ 3; tot += (min - tot + 1)/2; //System.out.println(prev + " " + next + " " + tot); result = Math.min(result, tot); } sb.append(result); sb.append("\n"); } private static void updateMap(int prev, int next) { int newVal = map.get(prev) - 1; if (newVal == 0) map.remove(prev); else map.put(prev, newVal); map.put(next, map.getOrDefault(next, 0) + 1); } public static void print(int test, long result) { System.out.println("Case #" + test + ": " + result); } }
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
974ec316aacd028c54e7f76887a41d3a
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 long nod(long a, long b) { while (Math.min(a, b) != 0) { if (a > b) { a = a % b; } else b = b % a; } return a + b; } public static void main(String[] args) throws IOException { // br = new BufferedReader(new FileReader("pencils.in")); // out = new PrintWriter("pencils.out"); int n=nextInt(); int[]a=new int[n]; long min=100000000; for (int i = 0; i < n; i++) { a[i]=nextInt(); if(i>0){ int l=Math.min(a[i-1],a[i]); int r=Math.max(a[i-1],a[i]); int ans=Math.min(r-l,l); l-=ans; r-=ans*2; if(l==0)ans+=(r+1)/2; else{ ans+=l/3*2+l%3; } if(ans<min)min=ans; } } for (int i = 0; i < n; i++) { if(i>0&&i<n-1){ int l=Math.min(a[i-1],a[i+1]); int r=Math.max(a[i-1],a[i+1]); int ans=l/2+r/2+1; if(ans<min)min=ans; } } Arrays.sort(a); out.println(Math.min(min,(a[0]+1)/2+(a[1]+1)/2)); out.close(); } static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); static StringTokenizer in = new StringTokenizer(""); public static boolean hasNext() throws IOException { if (in.hasMoreTokens()) return true; String s; while ((s = br.readLine()) != null) { in = new StringTokenizer(s); if (in.hasMoreTokens()) return true; } return false; } public static String nextToken() throws IOException { while (!in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static class Maincraft implements Comparable<Maincraft> { int x; int y; public Maincraft(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Maincraft o) { if(x!=o.x)return Integer.compare(x,o.x); else return Integer.compare(y,o.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 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
ce23af8b42c1c0e88880b56ef359af54
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 problem{ public static int answer(int x,int y){ int total = 0; while(x>0 || y>0){ if(x>y){ x = x - 2; y = y-1; }else{ y = y-2; x = x-1; } total++; } return total; } public static void main(String[] args) { Scanner sh = new Scanner(System.in); int n = sh.nextInt(); Queue<Integer> a = new PriorityQueue<>(); int arr[] = new int[n]; int idx = -1; int sum = 10000001; for(int i = 0; i<n; i++){ arr[i] = sh.nextInt(); a.add(arr[i]); if(i>0){ int sha = Math.min(arr[i],arr[i-1]); int ag = Math.abs(arr[i]-arr[i-1]); if(sha - ag > 0){ int check = ag + (2*(sha-ag)/3); if(2*(sha-ag)%3 != 0){ check++; } sum = Math.min(sum, check); }else{ int pa = Math.max(arr[i], arr[i-1]); sum = Math.min(sum,(pa/2) + (pa%2)); } }} if(n==2){ System.out.println(answer(arr[0],arr[1])); }else{ int temp = a.poll(); int p1 = temp/2 + temp%2; temp = a.poll(); p1 = p1 + temp/2 + temp%2; int p3 = 1000001; int x = 2; while(x<n){ if(arr[x-1]/2 + arr[x-1]%2 >= arr[x] && arr[x-1]/2 + arr[x-1]%2 >= arr[x-2]){ int q = Math.max(arr[x],arr[x-2]); p3 = Math.min(p3,q); } int num1 = arr[x]; int num2 = arr[x-2]; int temp_ = 0; if(num1 % 2 != 0){ temp_ = temp_ + (num1-1)/2; if(num2 % 2 != 0){ temp_ = temp_ + (num2-1)/2; temp_++; }else{ temp_ = temp_ + (num2-2)/2; temp_ = temp_ + 2; } }else{ temp_ = temp_ + (num1-2)/2; if(num2 % 2 != 0){ temp_ = temp_ + (num2-1)/2; temp_ = temp_ + 2; }else{ temp_ = temp_ + (num2-2)/2; temp_ = temp_ + 2; } } p3 = Math.min(p3, temp_); x++; } System.out.println(Math.min(p1, Math.min(sum ,p3))); } } }
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
e9a07c98950135675cf4639889a9b540
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.*; // you can compare with output.txt and expected out public class Round786E { MyPrintWriter out; MyScanner in; final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void preferFileIO(boolean isFileIO) { if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) { try{ in = new MyScanner(new FileInputStream("input.txt")); out = new MyPrintWriter(new FileOutputStream("output.txt")); } catch(FileNotFoundException e){ e.printStackTrace(); } } else{ in = new MyScanner(System.in); out = new MyPrintWriter(new BufferedOutputStream(System.out)); } } public static void main(String[] args){ // Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); Round786E sol = new Round786E(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; preferFileIO(isFileIO); int n = in.nextInt(); int[] a = in.nextIntArray(n); int ans = solve(a); out.println(ans); in.close(); out.close(); } private int solve(int[] a) { // 20 ..... 20 ......... 30 100 30 // -> not 40. it's 30 // case 1) target i-1 and i+1 (the only gain is +1 or +2 from parity) // case 2) target i and i+1 // case 2) target i and j int n=a.length; int min = (int) 1E9; for(int i=1; i+1<n; i++) { int p = a[i-1]; int r = a[i+1]; int need = Math.min(p, r); int left = Math.max(p, r)-need; min = Math.min(min, need+(left+1)/2); } for(int i=0; i+1<n; i++) { int p = Math.min(a[i], a[i+1]); int q = Math.max(a[i], a[i+1]); if(2*p <= q) { min = Math.min(min, (q+1)/2); } else { // 2p > q // p -> p-2t // q -> q-t // 2p - 4t = q - t // 3t = 2p-q int t1 = (2*p-q)/3; // floor int r1 = (q-t1+1)/2; int t2 = (2*p-q+2)/3; // ceil int r2 = (q-t2+1)/2; min = Math.min(min, t1+r1+Math.max(0, (p-2*t1-r1+1)/2)); min = Math.min(min, t2+r2); } } int min1 = (int) 1E9; int min2 = (int) 1E9; for(int i=0; i<n; i++) { if(a[i] < min1) { min2 = min1; min1 = a[i]; } else if(a[i] <= min2) min2 = a[i]; } min = Math.min(min, (min1+1)/2+(min2+1)/2); //System.out.println(min1 + " " + min2); return min; } public static class MyScanner { BufferedReader br; StringTokenizer st; // 32768? public MyScanner(InputStream is, int bufferSize) { br = new BufferedReader(new InputStreamReader(is), bufferSize); } public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); // br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } 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[][] nextGraphEdges(){ return nextGraphEdges(0); } int[][] nextGraphEdges(int offset) { int m = nextInt(); int[][] e = new int[m][2]; for(int i=0; i<m; i++){ e[i][0] = nextInt()+offset; e[i][1] = nextInt()+offset; } return e; } int[] nextIntArray(int len) { return nextIntArray(len, 0); } int[] nextIntArray(int len, int offset){ int[] a = new int[len]; for(int j=0; j<len; j++) a[j] = nextInt()+offset; return a; } long[] nextLongArray(int len) { return nextLongArray(len, 0); } long[] nextLongArray(int len, int offset){ long[] a = new long[len]; for(int j=0; j<len; j++) a[j] = nextLong()+offset; return a; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void print(long[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(long[] arr){ print(arr); println(); } public void print(int[] arr){ if(arr != null && arr.length > 0){ print(arr[0]); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]); } } } public void println(int[] arr){ print(arr); println(); } public <T> void print(ArrayList<T> arr){ if(arr != null && arr.size() > 0){ print(arr.get(0)); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)); } } } public <T> void println(ArrayList<T> arr){ print(arr); println(); } public void println(int[] arr, int split){ if(arr != null){ for(int i=0; i<arr.length; i+=split){ print(arr[i]); for(int j=i+1; j<i+split; j++){ print(" "); print(arr[j]); } println(); } } } public <T> void println(ArrayList<T> arr, int split){ if(arr != null && !arr.isEmpty()){ for(int i=0; i<arr.size(); i+=split){ print(arr.get(i)); for(int j=i+1; j<i+split; j++){ print(" "); print(arr.get(j)); } println(); } } } } static private int[][] constructChildren(int n, int[] parent, int parentRoot){ int[][] childrens = new int[n][]; int[] numChildren = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) numChildren[parent[i]]++; } for(int i=0; i<n; i++) { childrens[i] = new int[numChildren[i]]; } int[] idx = new int[n]; for(int i=0; i<parent.length; i++) { if(parent[i] != parentRoot) childrens[parent[i]][idx[parent[i]]++] = i; } return childrens; } static private int[][] constructNeighborhood(int n, int[][] e) { int[] degree = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; degree[u]++; degree[v]++; } int[][] neighbors = new int[n][]; for(int i=0; i<n; i++) neighbors[i] = new int[degree[i]]; int[] idx = new int[n]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][idx[u]++] = v; neighbors[v][idx[v]++] = u; } return neighbors; } static private void makeDotUndirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict graph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "--" + e[i][1] + ";"); } out2.println("}"); out2.close(); } static private void makeDotDirected(int[][] e) { MyPrintWriter out2 = null; try { out2 = new MyPrintWriter(new FileOutputStream("graph.dot")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } out2.println("strict digraph {"); for(int i=0; i<e.length; i++){ out2.println(e[i][0] + "->" + e[i][1] + ";"); } out2.println("}"); out2.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
819695371193a87a36aaa06314620eff
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.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class BreakingTheWall { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // int t = Integer.parseInt(br.readLine().trim()); int t = 1; StringBuilder sb = new StringBuilder(); while (t-- > 0) { int N = Integer.parseInt(br.readLine().trim()); int arr[] = nextIntArray(N, br); sb.append(solve(arr)).append("\n"); } br.close(); System.out.println(sb); } private static int solve(int arr[]) { int separate = getSeparateValues(arr); int min = Integer.MAX_VALUE; // Calculating Value if there is One Block in Between for (int i = 2; i < arr.length; i++) { int leftVal = arr[i - 2], rightVal = arr[i]; int steps = Math.min(leftVal, rightVal); leftVal -= steps; rightVal -= steps; steps += (leftVal + 1) / 2; steps += (rightVal + 1) / 2; min = Math.min(min, steps); } // Calculating for Adjacent Blocks for (int i = 0; i < arr.length - 1; i++) { int rightBlock = getAdjacentValue(arr[i], arr[i + 1]); min = Math.min(rightBlock, min); } return Math.min(min, separate); } private static int getAdjacentValue(int i, int j) { int X = Math.max(i, j), Y = Math.min(i, j); if (2 * Y <= X) return (X + 1) / 2; // Equating the X and Y int ret = X - Y; X -= 2 * ret; Y -= ret; ret += Math.ceil((X + Y * 1.0) / 3); return ret; } private static int getSeparateValues(int arr[]) { int minCache[] = new int[2]; Arrays.fill(minCache, (int) 1e7); for (int i : arr) { if (Math.max(minCache[0], minCache[1]) == minCache[0]) minCache[0] = Math.min(i, minCache[0]); else minCache[1] = Math.min(i, minCache[1]); } for (int i = 0; i < minCache.length; i++) minCache[i] = (minCache[i] + 1) / 2; int separate = minCache[0] + minCache[1]; return separate; } private static int[] nextIntArray(int N, BufferedReader br) throws Exception { StringTokenizer st = new StringTokenizer(br.readLine().trim(), " "); int arr[] = new int[N]; for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
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
5c5decc3bc5ce5d5657a4626aa7b87c3
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.*; public class E_Breaking_the_Wall { public static void main(String[] args) { FastReader rd = new FastReader(); // StringBuilder bd = new StringBuilder(); int n = rd.nextInt(); int a[] = new int[n]; int ans=Integer.MAX_VALUE; for(int i=0;i<n;i++) { a[i] = rd.nextInt(); } for(int i=0;i<n-2;i++) { int min = Math.min(a[i], a[i+2]); int max = Math.max(a[i], a[i+2]); ans = Math.min(ans, min +(int) Math.ceil((max-min+1)/2)); } for(int i=0;i<n-1;i++) { int min = Math.min(a[i], a[i+1]); int max = Math.max(a[i], a[i+1]); if(max>=2*min) { ans = Math.min(ans, (max+1)/2); } else { ans = Math.min(ans , (max+min+2)/3); } } Arrays.sort(a); ans = Math.min(ans, ((a[0]+1)/2) + ((a[1]+1)/2)); outn(ans); } public static void out(Object obj) { System.out.print(obj); } public static void outn(Object obj) { System.out.println(obj); } public static void outn() { System.out.println(); } 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; } } } // class Pair { // int first; // int second; // public Pair(int first, int second) { // this.first = first; // this.second = second; // } // } // class Compare { // static void compare(Pair arr[], int PRIORITY) { // Arrays.sort(arr, new Comparator<Pair>(){ // @Override // public int compare(Pair p1, Pair p2) { // if(PRIORITY == 1) return p1.second - p2.second; // else return p1.first - p2.first; // } // }); // } // }
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
9921c9ee949836d7183d55f2ba738533
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.concurrent.ThreadLocalRandom; public class E { //java -Xss515m Solution.java < input.txt private static final String SPACE = "\\s+"; private static final int MOD = 1_000_000_007; private static final Reader in = new Reader(); public static void main(String[] args) throws IOException { int n = in.readInt(); int[] nums = in.readInts(); int[] clone = Arrays.copyOf(nums, nums.length); shuffleSort(clone); int choice1 = (clone[0] + 1) / 2 + (clone[1] + 1) / 2; int choice2 = solveAdj(nums); int choice3 = solveSkip(nums); // System.out.println(choice1); // System.out.println(choice2); // System.out.println(choice3); System.out.println(min(choice1, choice2, choice3)); } private static int solveAdj(int[] nums) { int min = Integer.MAX_VALUE; for (int i = 0; i < nums.length - 1; i++) { int steps = 0; int num1 = nums[i]; int num2 = nums[i + 1]; if (num2 > num1) { num1 ^= num2 ^ (num2 = num1); } int diff = min(num2, num1 - num2); steps += diff; num1 -= 2 * diff; num2 -= diff; if (num2 == 0) steps += ( num1 + 1 ) / 2; else steps += (2 * num1 + 2 ) / 3; min = min(min, steps); } return min; } private static int solveSkip(int[] nums) { int min = Integer.MAX_VALUE; for (int i = 0; i < nums.length - 2; i++) { int steps = 0; int num1 = nums[i]; int num2 = nums[i + 2]; if (num1 % 2 == 1 && num2 % 2 == 1) { steps++; num1--; num2--; } steps += ( num1 + 1 ) / 2 + ( num2 + 1 ) / 2; min = min(min, steps); } return min; } // Utility functions private static int max(int... nums) { int max = Integer.MIN_VALUE; for (int num : nums) { max = Math.max(max, num); } return max; } private static int min(int... nums) { int min = Integer.MAX_VALUE; for (int num : nums) { min = Math.min(min, num); } return min; } private static long max(long... nums) { long max = Long.MIN_VALUE; for (long num : nums) { max = Math.max(max, num); } return max; } private static long min(long... nums) { long min = Long.MAX_VALUE; for (long num : nums) { min = Math.min(min, num); } return min; } private static void shuffleSort(int[] nums) { shuffle(nums); Arrays.sort(nums); } private static void shuffle(int[] nums) { Random random = ThreadLocalRandom.current(); for (int i = nums.length - 1; i > 0; i--) { swap(random.nextInt(i), i, nums); } } private static void swap(int a, int b, int[] nums) { int temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; } private static void shuffleSort(long[] nums) { shuffle(nums); Arrays.sort(nums); } private static void shuffle(long[] nums) { Random random = ThreadLocalRandom.current(); for (int i = nums.length - 1; i > 0; i--) { swap(random.nextInt(i), i, nums); } } private static void swap(int a, int b, long[] nums) { long temp = nums[a]; nums[a] = nums[b]; nums[b] = temp; } private static long pow(int base, int exp) { long res = 1; while (exp-- > 0) { res *= base; } return res; } private static long pow(int base, int exp, Long[][] memo) { if (exp == 0) return 1; if (memo[base][exp] != null) return memo[base][exp]; return memo[base][exp] = base * pow(base, exp - 1, memo) % MOD; } private static void print(int[] nums) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < nums.length; i++) { sb.append(nums[i]).append(" "); } System.out.println(sb); } private static void print(long[] nums) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < nums.length; i++) { sb.append(nums[i]).append(" "); } System.out.println(sb); } private static void print(String[] A) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < A.length; i++) { sb.append(A[i]).append(" "); } System.out.println(sb); } private static int gcd(int p, int q) { if (q == 0) return p; return gcd(q, p % q); } private static class Reader { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int index = 0; String[] tokens = {}; public int readInt() throws IOException { read(); return Integer.parseInt(tokens[index++]); } public long readLong() throws IOException { read(); return Long.parseLong(tokens[index++]); } public String readString() throws IOException { read(); return tokens[index++]; } public String readLine() throws IOException { return in.readLine(); } public int[] readInts() throws IOException { return Arrays.stream(in.readLine().split(SPACE)).mapToInt(Integer::parseInt).toArray(); } public long[] readLongs() throws IOException { return Arrays.stream(in.readLine().split(SPACE)).mapToLong(Long::parseLong).toArray(); } public String[] readStrings() throws IOException { return in.readLine().split(SPACE); } private void read() throws IOException { if (index >= tokens.length) { tokens = in.readLine().split(SPACE); index = 0; } } } private static class UnionFind { int[] p; public UnionFind(int n) { Arrays.fill(p = new int[n], -1); } public int find(int i) { return p[i] < 0 ? i : (p[i] = find(p[i])); } public boolean union(int i, int j) { if ((i = find(i)) == (j = find(j))) return false; if (p[i] == p[j]) p[i]--; if (p[i] <= p[j]) p[j] = i; else p[i] = j; return true; } } }
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
a992b0ef8f699256a1c098fb3a5dac50
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 E { // 注意不要用Arrays.sort() // 注意Math.pow可能导致精度问题 // 注意int溢出问题 static class Task { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } int ansMin = Integer.MAX_VALUE; // 只打一个 for (int i = 0; i < n; i++) { if (i == 0) { int count = arr[i] / 2 + (arr[i] % 2); count += Math.max(0, arr[i + 1] - count); ansMin = Math.min(ansMin, count); } else if (i == n - 1) { int count = arr[i] / 2 + (arr[i] % 2); count += Math.max(0, arr[i - 1] - count); ansMin = Math.min(ansMin, count); } else { // 左右都要考虑 int count = arr[i] / 2 + (arr[i] % 2); count += Math.max(0, Math.min(arr[i - 1] - count, arr[i + 1] - count)); ansMin = Math.min(ansMin, Math.min(count, Math.max(arr[i - 1], arr[i + 1]))); if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) { int min = Math.min(arr[i - 1], arr[i + 1]); int max = Math.max(arr[i - 1], arr[i + 1]); if (arr[i] > 2 * min) { count = min + (max - min) / 2 + (max - min) % 2; ansMin = Math.min(ansMin, count); } } } } // 打相邻两个 for (int i = 0; i < n - 1; i++) { if (arr[i] >= arr[i + 1] * 2 || arr[i] + 1 >= arr[i + 1] * 2) { // 只要击打当前的即可 ansMin = Math.min(ansMin, arr[i] / 2 + (arr[i] % 2)); continue; } if (arr[i + 1] >= arr[i] * 2 || arr[i + 1] + 1 >= arr[i] * 2) { // 只要击打当前的即可 ansMin = Math.min(ansMin, arr[i + 1] / 2 + (arr[i + 1] % 2)); continue; } int max = Math.max(arr[i], arr[i + 1]); int min = Math.min(arr[i], arr[i + 1]); int x = Math.max(1, (2 * min - max) / 3); if ((min - 2 * x) * 2 > max - x) { x++; } int count = x + (max - x) / 2 + (max - x) % 2; ansMin = Math.min(ansMin, count); x = Math.max(1, (2 * max - min) / 3); if ((max - 2 * x) * 2 > min - x) { x++; } count = x + (min - x) / 2 + (min - x) % 2; ansMin = Math.min(ansMin, count); } // 打不相邻两个,那就是打最小的 if (n == 2) { out.println(ansMin); return; } // todo sort(arr); int max1 = arr[0] / 2 + (arr[0] % 2); int max2 = arr[1] / 2 + (arr[1] % 2); ansMin = Math.min(ansMin, max1 + max2); out.println(ansMin); } } private static void sort(double[] arr) { Double[] objArr = Arrays.stream(arr).boxed().toArray(Double[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[i]; } } private static void sortDesc(double[] arr) { Double[] objArr = Arrays.stream(arr).boxed().toArray(Double[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[arr.length - i - 1]; } } private static void sort(int[] arr) { Integer[] objArr = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[i]; } } private static void sortDesc(int[] arr) { Integer[] objArr = Arrays.stream(arr).boxed().toArray(Integer[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[arr.length - i - 1]; } } private static void sort(long[] arr) { Long[] objArr = Arrays.stream(arr).boxed().toArray(Long[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[i]; } } private static void sortDesc(long[] arr) { Long[] objArr = Arrays.stream(arr).boxed().toArray(Long[]::new); Arrays.sort(objArr); for (int i = 0; i < arr.length; i++) { arr[i] = objArr[arr.length - i - 1]; } } private static void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task task = new Task(); task.solve(1, in, out); out.close(); } public static void main(String[] args) { new Thread(null, () -> solve(), "1", 1 << 26).start(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
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
48314689631738a02fff042ee9f17e8d
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.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int [] wall = new int[n]; for (int i = 0; i < n; i++) { wall[i]=scanner.nextInt(); } int t1 = 1000000000; int min2 = 1000000000; for (int i = 0; i < n - 1; i++) { int a = Math.max(wall[i],wall[i+1]); int b = Math.min(wall[i],wall[i+1]); if (a>=2*b) t1 = Math.min(t1,(a+1)/2); else t1 = Math.min(t1,(wall[i]+wall[i+1]+2)/3); } for (int i = 0; i < n-2; i++) { min2 = Math.min(min2,wall[i]+wall[i+2]); } int t2 = (min2+1)/2; Arrays.sort(wall); int t3 = (wall[0]+1)/2 + (wall[1]+1)/2; System.out.println(Math.min(Math.min(t1,t2),t3)); } }
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
f322c85901bf57f04baf9525b0146f2c
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.StreamTokenizer; import java.math.BigInteger; import static java.lang.System.out; import static java.lang.Math.*; import java.util.*; public class Main { static public void main(String[] args){ Read in = new Read(System.in); 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; int a1=Integer.MAX_VALUE,a2=Integer.MAX_VALUE; for(int i=0;i<n;i++){ if(a[i]<a1){ a2=a1; a1=a[i]; }else if(a[i]<a2){ a2 = a[i]; } } ans = (int)(Math.ceil(1.0*a1/2)+Math.ceil(1.0*a2/2)); for(int i=0;i<n-1;i++){ int k1=Math.max(a[i],a[i+1]); int k2=Math.min(a[i],a[i+1]); if(k2*2<=k1){ ans=Math.min(ans,(int)Math.ceil(1.0*k1/2)); }else{ int cen = k1 - k2; k1=k1-2*cen; int k = 2*(k1/3)+cen+k1%3; ans=Math.min(ans,k); } } for(int i=1;i<n-1;i++){ int k1=Math.max(a[i-1],a[i+1]); int k2=Math.min(a[i-1],a[i+1]); int k = (k1-k2)/2+(k1-k2)%2+k2; ans=Math.min(ans,k); } out.println(ans); } static void solve(Read in){ } static class Read {//自定义快读 Read public BufferedReader reader; public StringTokenizer tokenizer; public Read(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 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()); } } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static long gcd(long a, long b) { return (a % b == 0) ? b : 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 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
7a420d6988f1338af2a0b084d3291e3c
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.text.DecimalFormat; import java.util.*; public class Main { static class Pair { long a,b,c; public Pair(long a,long b,long c) { this.a=a; this.b=b; this.c=c; } // @Override // public int compareTo(Pair p) { // return Long.compare(l, p.l); // } } static final int INF = 1 << 30; static final long INFL = 1L << 60; static final long NINF = INFL * -1; static final long mod = (long) 1e9 + 7; static final long mod2 = 998244353; static DecimalFormat df = new DecimalFormat("0.00000000000000"); public static final double PI = 3.141592653589793d, eps = 1e-9; public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public static void solve(int testNumber, InputReader in, OutputWriter out) { //int t = in.ni(); int t=1; while (t-->0) { int n=in.ni(); int[] arr=in.na(n); long min=Long.MAX_VALUE; for(int i=0;i<n;i++) { if(i-1>=0 && i+1<n) { long tp=Math.min(arr[i-1],arr[i+1])+((Math.max(arr[i+1],arr[i-1])-Math.min(arr[i+1],arr[i-1])+1)/2L); //out.printLine(tp); min=Math.min(min,tp); } if(i+1<n) { long tp=Long.MAX_VALUE; if(arr[i+1]>=arr[i]) { if(arr[i+1]>=2*arr[i]) { tp=(arr[i+1]+1)/2L; } else { tp=(arr[i]+arr[i+1]+2)/3; //out.printLine(arr[i]+" "+arr[i+1]+" "+tp); } } else { if(arr[i]>=2*arr[i+1]) { tp=(arr[i]+1)/2L; } else { tp=(arr[i]+arr[i+1]+2)/3; //out.printLine(arr[i]+" "+arr[i+1]+" "+tp); } } min=Math.min(min,tp); } } CP.sort(arr); min=Math.min(min,((arr[0]+1)/2)+((arr[1]+1)/2)); out.printLine(min); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int ni() { 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; } private char nc() { return (char)skip(); } public int[] na(int arraySize) { int[] array = new int[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = ni(); } return array; } private int skip() { int b; while ((b = read()) != -1 && isSpaceChar(b)) ; return b; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = read(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } int[][] nim(int h, int w) { int[][] a = new int[h][w]; for (int i = 0; i < h; i++) { a[i] = na(w); } return a; } long[][] nlm(int h, int w) { long[][] a = new long[h][w]; for (int i = 0; i < h; i++) { a[i] = nla(w); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nla(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = nextLong(); } return array; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') { c = (byte) read(); } boolean neg = (c == '-'); if (neg) { c = (byte) read(); } do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') { while ((c = (byte) read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } } public static class CP { static boolean isPrime(long n) { if (n <= 1) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; (long) i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } public static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } public static boolean isComposite(long n) { if (n < 2) return true; if (n == 2 || n == 3) return false; if (n % 2 == 0 || n % 3 == 0) return true; for (long i = 6L; i * i <= n; i += 6) if (n % (i - 1) == 0 || n % (i + 1) == 0) return true; return false; } static int ifnotPrime(int[] prime, int x) { return (prime[x / 64] & (1 << ((x >> 1) & 31))); } static int log2(long n) { return (int) (Math.log10(n) / Math.log10(2)); } static void makeComposite(int[] prime, int x) { prime[x / 64] |= (1 << ((x >> 1) & 31)); } public static String swap(String a, int i, int j) { char temp; char[] charArray = a.toCharArray(); temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray); } static void reverse(long arr[]){ int l = 0, r = arr.length-1; while(l<r){ long temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } static void reverse(int arr[]){ int l = 0, r = arr.length-1; while(l<r){ int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; l++; r--; } } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } static long digit(long s) { long brute = 0; while (s > 0) { brute+=s%10; s /= 10; } return brute; } public static int[] primefacts(int n, int[] primes) { int[] ret = new int[15]; int rp = 0; for (int p : primes) { if (p * p > n) break; int i; for (i = 0; n % p == 0; n /= p, i++) ; if (i > 0) ret[rp++] = p; } if (n != 1) ret[rp++] = n; return Arrays.copyOf(ret, rp); } static ArrayList<Integer> bitWiseSieve(int n) { ArrayList<Integer> al = new ArrayList<>(); int prime[] = new int[n / 64 + 1]; for (int i = 3; i * i <= n; i += 2) { if (ifnotPrime(prime, i) == 0) for (int j = i * i, k = i << 1; j < n; j += k) makeComposite(prime, j); } al.add(2); for (int i = 3; i <= n; i += 2) if (ifnotPrime(prime, i) == 0) al.add(i); return al; } 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 long[] revsort(long[] arr) { List<Long> list = new ArrayList<>(); for (long n : arr) { list.add(n); } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static int[] revsort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int n : arr) { list.add(n); } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static ArrayList<Integer> reverse( ArrayList<Integer> data, int left, int right) { // Reverse the sub-array while (left < right) { int temp = data.get(left); data.set(left++, data.get(right)); data.set(right--, temp); } // Return the updated array return data; } static ArrayList<Integer> sieve(long size) { ArrayList<Integer> pr = new ArrayList<Integer>(); boolean prime[] = new boolean[(int) size]; for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i * i < prime.length; i++) { if (prime[i]) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i); return pr; } static boolean[] sieve1(long size) { ArrayList<Integer> pr = new ArrayList<Integer>(); boolean prime[] = new boolean[(int) size]; for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i * i < prime.length; i++) { if (prime[i]) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } //for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i); return prime; } static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) { ArrayList<Integer> al = new ArrayList<>(); if (l == 1) ++l; int max = r - l + 1; int arr[] = new int[max]; for (int p : primes) { if (p * p <= r) { int i = (l / p) * p; if (i < l) i += p; for (; i <= r; i += p) { if (i != p) { arr[i - l] = 1; } } } } for (int i = 0; i < max; ++i) { if (arr[i] == 0) { al.add(l + i); } } return al; } static boolean isfPrime(long n, int iteration) { if (n == 0 || n == 1) return false; if (n == 2) return true; if (n % 2 == 0) return false; Random rand = new Random(); for (int i = 0; i < iteration; i++) { long r = Math.abs(rand.nextLong()); long a = r % (n - 1) + 1; if (modPow(a, n - 1, n) != 1) return false; } return true; } static long modPow(long a, long b, long c) { long res = 1; for (int i = 0; i < b; i++) { res *= a; res %= c; } return res % c; } private static long binPower(long a, long l, long mod) { long res = 0; while (l > 0) { if ((l & 1) == 1) { res = mulmod(res, a, mod); l >>= 1; } a = mulmod(a, a, mod); } return res; } private static long mulmod(long a, long b, long c) { long x = 0, y = a % c; while (b > 0) { if (b % 2 == 1) { x = (x + y) % c; } y = (y * 2L) % c; b /= 2; } return x % c; } static long binary_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static void swap(int a, int b) { int tp = b; b = a; a = tp; } static long Modular_Expo(long a, long b, long mod) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % mod; --b; } a = (a * a) % mod; b /= 2; } return res % mod; } static int i_gcd(int a, int b) { while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long ceil_div(long a, long b) { return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } static long getIthBitFromLong(long bits, int i) { return (bits >> (i - 1)) & 1; } // static boolean isPerfectSquare(long a, long b) // { // long sq=Math.sqrt() // } private static TreeMap<Long, Long> primeFactorize(long n) { TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder()); long cnt = 0; long total = 1; for (long i = 2; (long) i * i <= n; ++i) { if (n % i == 0) { cnt = 0; while (n % i == 0) { ++cnt; n /= i; } pf.put(cnt, i); //total*=(cnt+1); } } if (n > 1) { pf.put(1L, n); //total*=2; } return pf; } //less than or equal private static int lower_bound(ArrayList<Long> list, long val) { int ans = -1, lo = 0, hi = list.size() - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(int[] arr, int val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= val) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } private static int lower_bound(long[] arr, long val) { int ans = -1, lo = 0, hi = arr.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid]>=val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // greater than or equal private static int upper_bound(List<Integer> list, int val) { int ans = list.size(), lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (list.get(mid) >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(int[] arr, int val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } private static int upper_bound(long[] arr, long val) { int ans = arr.length, lo = 0, hi = ans - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] >= val) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } // ==================== LIS & LNDS ================================ private static int[] LIS(long arr[], int n) { List<Long> list = new ArrayList<>(); int[] cnt=new int[n]; for (int i = 0; i < n; i++) { int idx = find1(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); cnt[i]=list.size(); } return cnt; } private static int find1(List<Long> list, long val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid)>=val) { ret = mid; j = mid - 1; } else { i = mid + 1; } } return ret; } private static int LNDS(int[] arr, int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { int idx = find2(list, arr[i]); if (idx < list.size()) list.set(idx, arr[i]); else list.add(arr[i]); } return list.size(); } private static int find2(List<Integer> list, int val) { int ret = list.size(), i = 0, j = list.size() - 1; while (i <= j) { int mid = (i + j) / 2; if (list.get(mid) <= val) { i = mid + 1; } else { ret = mid; j = mid - 1; } } return ret; } private static long nCr(long n, long r,long mod) { if (n - r > r) r = n - r; long ans = 1L; for (long i = r + 1; i <= n; i++) ans = (ans%mod*i%mod)%mod; for (long i = 2; i <= n - r; i++) ans /= i; return ans%mod; } private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } static ArrayList<StringBuilder> permutations(StringBuilder s) { int n=s.length(); ArrayList<StringBuilder> al=new ArrayList<>(); getpermute(s,al,0,n); return al; } // static String longestPalindrome(String s) // { // int st=0,ans=0,len=0; // // // } static void getpermute(StringBuilder s,ArrayList<StringBuilder> al,int l, int r) { if(l==r) { al.add(s); return; } for(int i=l+1;i<r;++i) { char c=s.charAt(i); s.setCharAt(i,s.charAt(l)); s.setCharAt(l,c); getpermute(s,al,l+1,r); c=s.charAt(i); s.setCharAt(i,s.charAt(l)); s.setCharAt(l,c); } } static void initStringHash(String s,long[] dp,long[] inv,long p) { long pow=1; inv[0]=1; int n=s.length(); dp[0]=((s.charAt(0)-'a')+1); for(int i=1;i<n;++i) { pow=(pow*p)%mod; dp[i]=(dp[i-1]+((s.charAt(i)-'a')+1)*pow)%mod; inv[i]=CP.modinv(pow,mod)%mod; } } static long getStringHash(long[] dp,long[] inv,int l,int r) { long ans=dp[r]; if(l-1>=0) { ans-=dp[l-1]; } ans=(ans*inv[l])%mod; return ans; } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } private static String sortString(String str) { int[] arr = new int[256]; for (char ch : str.toCharArray()) arr[ch]++; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 256; i++) while (arr[i]-- > 0) sb.append((char) i); return sb.toString(); } static boolean isSquarefactor(int x, int factor, int target) { int s = (int) Math.round(Math.sqrt(x)); return factor * s * s == target; } static boolean isSquare(long x) { long s = (long) Math.round(Math.sqrt(x)); return x * x == s; } static int bs(ArrayList<Integer> al, int val) { int l = 0, h = al.size() - 1, mid = 0, ans = -1; while (l <= h) { mid = (l + h) >> 1; if (al.get(mid) == val) { return mid; } else if (al.get(mid) > val) { h = mid - 1; } else { l = mid + 1; } } return ans; } static void sort(int a[]) // heap sort { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); fast_swap(in, idx, i); } } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for (int v : a) { c0[(v & 0xff) + 1]++; c1[(v >>> 8 & 0xff) + 1]++; c2[(v >>> 16 & 0xff) + 1]++; c3[(v >>> 24 ^ 0x80) + 1]++; } for (int i = 0; i < 0xff; i++) { c0[i + 1] += c0[i]; c1[i + 1] += c1[i]; c2[i + 1] += c2[i]; c3[i + 1] += c3[i]; } int[] t = new int[n]; for (int v : a) t[c0[v & 0xff]++] = v; for (int v : t) a[c1[v >>> 8 & 0xff]++] = v; for (int v : a) t[c2[v >>> 16 & 0xff]++] = v; for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v; return a; } static int[] computeLps(String pat) { int len = 0, i = 1, m = pat.length(); int lps[] = new int[m]; 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; } } } return lps; } static ArrayList<Integer> kmp(String s, String pat) { ArrayList<Integer> al = new ArrayList<>(); int n = s.length(), m = pat.length(); int lps[] = computeLps(pat); int i = 0, j = 0; while (i < n) { if (s.charAt(i) == pat.charAt(j)) { i++; j++; if (j == m) { al.add(i - j); j = lps[j - 1]; } } else { if (j != 0) { j = lps[j - 1]; } else { i++; } } } return al; } static void reverse_ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); for (int l = 0, r = a.length - 1; l < r; ++l, --r) fast_swap(a, l, r); } static void ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } static ArrayList<Long> primeFact(long n) { ArrayList<Long> al = new ArrayList<>(); al.add(1L); while (n % 2 == 0) { if (!al.contains(2L)) { al.add(2L); } n /= 2L; } for (long i = 3; (long) i * i <= n; i += 2) { while ((n % i == 0)) { if (!al.contains((long) i)) { al.add((long) i); } n /= i; } } if (n > 2) { if (!al.contains(n)) { al.add(n); } } return al; } public static long totFact(long n) { long cnt = 0, tot = 1; while (n % 2 == 0) { n /= 2; ++cnt; } tot *= (cnt + 1); for (int i = 3; i <= Math.sqrt(n); i += 2) { cnt = 0; while (n % i == 0) { n /= i; ++cnt; } tot *= (cnt + 1); } if (n > 2) { tot *= 2; } return tot; } static int[] z_function(String s) { int n = s.length(), z[] = new int[n]; for (int i = 1, l = 0, r = 0; i < n; ++i) { if (i <= r) z[i] = Math.min(z[i - l], r - i + 1); while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) ++z[i]; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } static void fast_swap(int[] a, int idx1, int idx2) { if (a[idx1] == a[idx2]) return; a[idx1] ^= a[idx2]; a[idx2] ^= a[idx1]; a[idx1] ^= a[idx2]; } public static void fast_sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } static int factorsCount(int n) { boolean hash[] = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } static long binomialCoeff(long n, long k) { long res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res = (res * (n - i)); res /= (i + 1); } return res; } static long nck(long fact[], long inv[], long n, long k) { if (k > n) return 0; long res = fact[(int) n]%mod; res = (int) ((res%mod* inv[(int) k]%mod))%mod; res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod; return res % mod; } public static long fact(long x) { long fact = 1; for (int i = 2; i <= x; ++i) { fact = fact * i; } return fact; } public static ArrayList<Long> getFact(long x) { ArrayList<Long> facts = new ArrayList<>(); facts.add(1L); for (long i = 2; i * i <= x; ++i) { if (x % i == 0) { facts.add(i); if (i != x / i) { facts.add(x / i); } } } return facts; } static void matrix_ex(long n, long[][] A, long[][] I) { while (n > 0) { if (n % 2 == 0) { Multiply(A, A); n /= 2; } else { Multiply(I, A); n--; } } } static void Multiply(long[][] A, long[][] B) { int n = A.length, m = A[0].length, p = B[0].length; long[][] C = new long[n][p]; for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { for (int k = 0; k < m; k++) { C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod; C[i][j] = C[i][j] % mod; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { A[i][j] = C[i][j]; } } } public static HashMap<Long, Integer> sortMapDesc(HashMap<Long,Integer> map) { List<Map.Entry<Long, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); HashMap<Long, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Long, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Character, Integer> sortMapDescch(HashMap<Character, Integer> map) { List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); HashMap<Character, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Character, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Long,Long> sortMapAsclng(HashMap<Long,Long> map) { List<Map.Entry<Long,Long>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> (int)(o1.getValue() - o2.getValue())); HashMap<Long,Long> temp = new LinkedHashMap<>(); for (Map.Entry<Long,Long> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) { List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue()); HashMap<Integer, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Integer, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static long lcm(long l, long l2) { long val = gcd(l, l2); return (l * l2) / val; } public static boolean isSubsequence(String s, String t) { int n = s.length(); int m = t.length(); if (m > n) { return false; } int i = 0, j = 0, skip = 0; while (i < n && j < m) { if (s.charAt(i) == t.charAt(j)) { --skip; ++j; } ++skip; ++i; } return j==m; } public static long[][] combination(int l, int r) { long[][] pascal = new long[l + 1][r + 1]; pascal[0][0] = 1; for (int i = 1; i <= l; ++i) { pascal[i][0] = 1; for (int j = 1; j <= r; ++j) { pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j]; } } return pascal; } public static long gcd(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]); return ret; } public static long lcm(int... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]); return ret; } public static int min(int a, int b) { return a < b ? a : b; } public static int min(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]); return ret; } public static long min(long a, long b) { return a < b ? a : b; } public static long min(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]); return ret; } public static int max(int a, int b) { return a > b ? a : b; } public static int max(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]); return ret; } public static long max(long a, long b) { return a > b ? a : b; } public static long max(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]); return ret; } public static long sum(int... array) { long ret = 0; for (int i : array) ret += i; return ret; } public static long sum(long... array) { long ret = 0; for (long i : array) ret += i; return ret; } public static long[] facts(int n) { long[] fact=new long[1005]; fact[0]=1; fact[1]=1; for(int i=2;i<n;i++) { fact[i]=(long)(i*fact[i-1])%mod; } return fact; } public static long[] inv(long[] fact,int n) { long[] inv=new long[n]; inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod; for(int i=n-2;i>=0;--i) { inv[i]=(inv[i+1]*(i+1))%mod; } return inv; } public static int modinv(long x, long mod) { return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod); } public static int lcs(String s, String t) { int n = s.length(), m = t.length(); int dp[][] = new int[n + 1][m + 1]; for (int i = 0; i <= n; ++i) { for (int j = 0; j <= m; ++j) { if (i == 0 || j == 0) { dp[i][j] = 0; } else if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[n][m]; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void printLine(long[] array) { print(array); writer.println(); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } public void printLine(int i) { writer.println(i); } public void printLine(char c) { writer.println(c); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void py() { print("YES"); writer.println(); } public void pn() { print("NO"); writer.println(); } public void printLine(Object... objects) { print(objects); writer.println(); } void flush() { writer.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
22ef29d8828938dcf271ef6fe7175292
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
/*----------- ---------------* Author : Ryan Ranaut __Hope is a big word, never lose it__ ------------- --------------*/ import java.io.*; import java.util.*; public class Codeforces2 { static PrintWriter out = new PrintWriter(System.out); //static final int mod = 1_000_000_007; static final int mod = 998244353; static final int max = (int)(1e6); 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()); } 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; } 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; } } /*-------------------------------------------------------------------------*/ //Try seeing general case //Think edge cases public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); int[] a = s.readIntArray(n); out.println(find(n, a)); out.close(); } public static int find(int n, int[] a) { int[] b = a.clone(); sort(b); int x1 = b[0]; int x2 = b[1]; int res = find(x1) + find(x2); for(int i=1;i<n;i++) { x1 = Math.min(a[i-1], a[i]); x2 = Math.max(a[i-1], a[i]); if(x2>=2*x1) res = Math.min(res, find(x2)); else { int val = (int)Math.ceil((x1+x2)/3.0); res = Math.min(res, val); } } for(int i=1;i<n-1;i++) { x1 = Math.min(a[i-1], a[i+1]); x2 = Math.max(a[i-1], a[i+1]); res = Math.min(res, x1 + find(x2-x1)); } return res; } public static int find(int x) { return (int)Math.ceil(x/2.0); } /*-----------------------------------End of the road--------------------------------------*/ static class DSU { int[] parent; int[] ranks; int[] groupSize; int size; public DSU(int n) { size = n; parent = new int[n];//0 based ranks = new int[n]; groupSize = new int[n];//Size of each component for (int i = 0; i < n; i++) { parent[i] = i; ranks[i] = 1; groupSize[i] = 1; } } public int find(int x)//Path Compression { if (parent[x] == x) return x; else return parent[x] = find(parent[x]); } public void union(int x, int y)//Union by rank { int x_rep = find(x); int y_rep = find(y); if (x_rep == y_rep) return; if (ranks[x_rep] < ranks[y_rep]) { parent[x_rep] = y_rep; groupSize[y_rep] += groupSize[x_rep]; } else if (ranks[x_rep] > ranks[y_rep]) { parent[y_rep] = x_rep; groupSize[x_rep] += groupSize[y_rep]; } else { parent[y_rep] = x_rep; ranks[x_rep]++; groupSize[x_rep] += groupSize[y_rep]; } size--;//Total connected components } } public static int gcd(int x,int y) { return y==0?x:gcd(y,x%y); } public static long gcd(long x,long y) { return y==0L?x:gcd(y,x%y); } 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); } public static long pow(long a,long b) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1) tmp*=a; a*=a; b>>=1; } return (tmp*a); } public static long modPow(long a,long b,long mod) { if(b==0L) return 1L; long tmp=1; while(b>1L) { if((b&1L)==1L) tmp*=a; a*=a; a%=mod; tmp%=mod; b>>=1; } return (tmp*a)%mod; } static long mul(long a, long b) { return a*b%mod; } static long fact(int n) { long ans=1; for (int i=2; i<=n; i++) ans=mul(ans, i); return ans; } static long fastPow(long base, long exp) { if (exp==0) return 1; long half=fastPow(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static void debug(int ...a) { for(int x: a) out.print(x+" "); out.println(); } static void debug(long ...a) { for(long x: a) out.print(x+" "); out.println(); } static void debugMatrix(int[][] a) { for(int[] x:a) out.println(Arrays.toString(x)); } static void debugMatrix(long[][] a) { for(long[] x:a) out.println(Arrays.toString(x)); } static void reverseArray(int[] a) { int n = a.length; int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void sort(int[] a) { ArrayList<Integer> ls = new ArrayList<>(); for(int x: a) ls.add(x); Collections.sort(ls); for(int i=0;i<a.length;i++) a[i] = ls.get(i); } static void sort(long[] a) { ArrayList<Long> ls = new ArrayList<>(); for(long x: a) ls.add(x); Collections.sort(ls); for(int i=0;i<a.length;i++) a[i] = ls.get(i); } static class Pair{ int x, y; Pair(int x, int y) { this.x = x; this.y = 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 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
9be7268749db4f5b1dd308fd1f182ef4
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 { static StringBuilder sb; static dsu dsu; static long fact[]; static int mod = (int) (1e9 + 7); static long get(int a,int b){ if(b>a){ int temp=a; a=b; b=temp; } long diff=a-b; long ans=0; if(a-(2*diff)<=0){ ans=(a/2) + (a%2); } else{ a-=2*diff; ans+=diff; ans+=(a+a)/3; if((a+a)%3!=0)ans++; } return ans; } static void solve() { int n=i(); int[]arr=new int[n]; for(int i=0;i<n;i++)arr[i]=i(); int []prefix=new int[n]; int []suffix=new int[n]; prefix[0]=arr[0]; for(int i=1;i<n;i++){ prefix[i]=Math.min(prefix[i-1],arr[i]); } suffix[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ suffix[i]=Math.min(suffix[i+1],arr[i]); // System.out.println(i+" "+suffix[i]); } long ans=Long.MAX_VALUE; for(int i=0;i<n;i++){ if(i==0){ long cans=Long.MAX_VALUE; if(i+2<n){ int v1=(arr[i]/2 )+(arr[i]%2); int v2=suffix[i+2]/2 +suffix[i+2]%2; cans=Math.min(cans,v1+v2); } cans=Math.min(cans,get(arr[i],arr[i+1])); ans=Math.min(ans,cans); } else if(i==n-1){ long cans=Long.MAX_VALUE; if(i-2>=0){ int v1=(arr[i]/2 )+(arr[i]%2); int v2=prefix[i-2]/2 +prefix[i-2]%2; cans=Math.min(cans,v1+v2); } cans=Math.min(cans,get(arr[i],arr[i-1])); ans=Math.min(ans,cans); } else{ long cans=Long.MAX_VALUE; if(i+2<n){ int v1=(arr[i]/2 )+(arr[i]%2); int v2=suffix[i+2]/2 +suffix[i+2]%2; cans=Math.min(cans,v1+v2); } cans=Math.min(cans,get(arr[i],arr[i+1])); // long cans=Long.MAX_VALUE; if(i-2>=0){ int v1=(arr[i]/2 )+(arr[i]%2); int v2=prefix[i-2]/2 +prefix[i-2]%2; cans=Math.min(cans,v1+v2); } cans=Math.min(cans,get(arr[i],arr[i-1])); int a1=arr[i+1] ; int a2=arr[i-1]; if(a2>a1){ a1=arr[i-1]; a2=arr[i+1]; } int tans=a2; a1-=a2; tans +=(a1/2) +(a1%2); cans=Math.min(tans,cans); ans=Math.min(ans,cans); } } sb.append(ans+"\n") ; } public static void main(String[] args) { sb = new StringBuilder(); int test = 1; while (test-- > 0) { solve(); } System.out.println(sb); } /* * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++) * { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; } */ //**************NCR%P****************** static long ncr(int n, int r) { if (r > n) return (long) 0; long res = fact[n] % mod; // System.out.println(res); res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod; res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod; // System.out.println(res); return res; } /////////////////////////////////////////// static class Pair { long x; long y; long gcd; public Pair(long x, long y, long gcd) { this.x = x; this.y = y; this.gcd = gcd; } } static Pair euclids(long a, long b) { if (b == 0) { return new Pair(1, 0, a); } Pair dash = euclids(b, a % b); return new Pair(dash.y, dash.x - ((a / b) * dash.y), dash.gcd); } /////////////////////////////////// static int euler(int n) { int count = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) { n = n / i; } count = count - count / i; } } if (n > 1) { count = count - count / n; } return count; } ////////////////////////////////// static long[][] ncrcoll(int n, int k, int p) { long[][] arr = new long[n + 1][k + 1]; for (int i = 1; i < arr.length; i++) { arr[i][0] = 1; } for (int i = 1; i < arr.length; i++) { for (int j = 1; j <= i && j < arr[0].length; j++) { if (i == 1 && j == 1) { arr[i][j] = 1; } else { arr[i][j] = (arr[i - 1][j] + arr[i - 1][j - 1]) % (p); } } } return arr; } ////////////////////////////////// static void sieve() { int MAXN=spf.length; spf[1] = 1; for (int i = 2; i < MAXN; i++) { spf[i] = i; } for (int i = 2; i * i < MAXN; i++) { if (spf[i] == i) { for (int j = i * i; j < MAXN; j += i) { if (spf[j] == j) { spf[j] = i; } } } } } static int[] spf=new int[1000000]; static ArrayList<Integer> getFactorization(int x) { ArrayList<Integer> ret = new ArrayList<>(); while (x != 1) { ret.add(spf[x]); x = x / spf[x]; } return ret; } ////////////////////////////////// static long p(long x, long y)// POWER FXN // { if (y == 0) return 1; long res = 1; while (y > 0) { if (y % 2 == 1) { res = (res * x) % mod; y--; } x = (x * x) % mod; y = y / 2; } return res; } //**************END****************** // *************Disjoint set // union*********// static class dsu { int parent[]; dsu(int n) { parent = new int[n]; for (int i = 0; i < n; i++) parent[i] = -1; } int find(int a) { if (parent[a] < 0) return a; else { int x = find(parent[a]); parent[a] = x; return x; } } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) return; parent[b] = a; } } //**************PRIME FACTORIZE **********************************// static TreeMap<Integer, Integer> prime(long n) { TreeMap<Integer, Integer> h = new TreeMap<>(); long num = n; for (int i = 2; i <= Math.sqrt(num); i++) { if (n % i == 0) { int nt = 0; while (n % i == 0) { n = n / i; nt++; } h.put(i, nt); } } if (n != 1) h.put((int) n, 1); return h; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); public static long[] sort(long[] a2) { int n = a2.length; ArrayList<Long> l = new ArrayList<>(); for (long i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static char[] sort(char[] a2) { int n = a2.length; ArrayList<Character> l = new ArrayList<>(); for (char i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static long pow(long x, long y) { long res = 1; while (y > 0) { if (y % 2 != 0) { res = (res * x);// % modulus; y--; } x = (x * x);// % modulus; y = y / 2; } return res; } //GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } // ******LOWEST COMMON MULTIPLE // ********************************************* public static long lcm(long x, long y) { return (x * (y / gcd(x, y))); } //INPUT PATTERN******************************************************** public static int i() { return in.Int(); } public static long l() { String s = in.String(); return Long.parseLong(s); } public static String s() { return in.String(); } public static int[] readArrayi(int n) { int A[] = new int[n]; for (int i = 0; i < n; i++) { A[i] = i(); } return A; } public static long[] readArray(long n) { long A[] = new long[(int) n]; for (int i = 0; i < n; i++) { A[i] = l(); } return A; } }
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
c24b66693e8cc41642de89bbe39d950e
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); EBreakingTheWall solver = new EBreakingTheWall(); solver.solve(1, in, out); out.close(); } static class EBreakingTheWall { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.nextIntArray(n); int ans = Integer.MAX_VALUE; int[] pref = new int[n]; int[] suff = new int[n]; pref[0] = arr[0]; suff[n - 1] = arr[n - 1]; for (int i = 1; i < n; i++) { pref[i] = Math.min(pref[i - 1], arr[i]); } for (int i = n - 2; i >= 0; i--) { suff[i] = Math.min(suff[i + 1], arr[i]); } for (int i = 0; i < n; i++) { int req = arr[i] / 2; int left = arr[i] % 2; int min = Integer.MAX_VALUE; if (i >= 3) { min = Math.min(min, (pref[i - 3] + 1) / 2 + (arr[i] + 1) / 2); } if (i + 3 < n) { min = Math.min(min, (suff[i + 3] + 1) / 2 + (arr[i + 1] + 1) / 2); } if (i - 2 >= 0) { min = Math.min(min, (arr[i - 2] + arr[i] + 1) / 2); } if (i + 2 < n) { min = Math.min(min, (arr[i + 2] + arr[i] + 1) / 2); } if (i - 1 >= 0) { int t = Math.max(0, (2 * arr[i] - arr[i - 1] - 1 + 2) / 3); if (t > arr[i - 1]) { min = Math.min(min, (arr[i] + 1) / 2); } else min = Math.min(min, t + (arr[i - 1] - t + 1) / 2); } if (i + 1 < n) { int t = Math.max(0, (2 * arr[i] - arr[i + 1] - 1 + 2) / 3); if (t > arr[i + 1]) { min = Math.min(min, (arr[i] + 1) / 2); } else min = Math.min(min, t + (arr[i + 1] - t + 1) / 2); } ans = Math.min(min, ans); } out.println(ans); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { BufferedReader reader; 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(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
1abb8da06be78215a01383006d0b2790
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.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; public class E { public static void main(String[] args) { Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int r = 2_000_000; int min1 = a[0]; int min2 = r; for (int i = 1; i < n; i++) { int min = Math.min(a[i - 1], a[i]); int max = Math.max(a[i - 1], a[i]); if (min * 2 <= max) { r = Math.min(r, min + (max - min * 2 + 1) / 2); } else { r = Math.min(r, (a[i] + a[i - 1] + 2) / 3); } if (i < n - 1) { min = Math.min(a[i - 1], a[i + 1]); max = Math.max(a[i - 1], a[i + 1]); r = Math.min(r, Math.min(max, min + (max - min + 1) / 2)); } if (a[i] < min1) { min2 = min1; min1 = a[i]; } else if (a[i] < min2) { min2 = a[i]; } } r = Math.min(r, (min1 + 1) / 2 + (min2 + 1) / 2); out.println(r); out.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
829974acb55695d704902ceab286d754
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
//Utilities import java.io.*; import java.util.*; public class a { static int n; static int[] a, b; static int res = Integer.MAX_VALUE; public static void main(String[] args) throws IOException { n = in.iscan(); a = new int[n]; b = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.iscan(); b[i] = a[i]; } UTILITIES.sort(b, true); res = (b[0] + 1) / 2 + (b[1] + 1) / 2; for (int i = 0; i < n; i++) { if (i - 1 >= 0 && i + 1 < n) { int min = Math.min(a[i-1], a[i+1]); int max = Math.max(a[i-1], a[i+1]); res = Math.min(res, min + (max - min + 1) / 2); } if (i + 1 < n) { int min = Math.min(a[i], a[i+1]); int max = Math.max(a[i], a[i+1]); if (max / 2 > min) { res = Math.min(res, (max+1)/2); } else { res = Math.min(res, (min + max + 2) / 3); } } } out.println(res); out.close(); } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static void sort(int[] a, boolean increasing) { ArrayList<Integer> arr = new ArrayList<Integer>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(long[] a, boolean increasing) { ArrayList<Long> arr = new ArrayList<Long>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static void sort(double[] a, boolean increasing) { ArrayList<Double> arr = new ArrayList<Double>(); int n = a.length; for (int i = 0; i < n; i++) { arr.add(a[i]); } Collections.sort(arr); for (int i = 0; i < n; i++) { if (increasing) { a[i] = arr.get(i); } else { a[i] = arr.get(n-1-i); } } } public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static void updateMap(HashMap<Integer, Integer> map, int key, int v) { if (!map.containsKey(key)) { map.put(key, v); } else { map.put(key, map.get(key) + v); } if (map.get(key) == 0) { map.remove(key); } } 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 * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static long fast_pow (long b, long x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } // start of permutation and lower/upper bound template public static void nextPermutation(int[] nums) { //find first decreasing digit int mark = -1; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] > nums[i - 1]) { mark = i - 1; break; } } if (mark == -1) { reverse(nums, 0, nums.length - 1); return; } int idx = nums.length-1; for (int i = nums.length-1; i >= mark+1; i--) { if (nums[i] > nums[mark]) { idx = i; break; } } swap(nums, mark, idx); reverse(nums, mark + 1, nums.length - 1); } public static void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } public static void reverse(int[] nums, int i, int j) { while (i < j) { swap(nums, i, j); i++; j--; } } static int lower_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= cmp) high = mid; else low = mid + 1; } return low; } static int upper_bound (int[] arr, int hi, int cmp) { int low = 0, high = hi, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > cmp) high = mid; else low = mid + 1; } return low; } // end of permutation and lower/upper bound template } }
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
43609e269b88afd89f3b6cb5c86326dc
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
//some updates in import stuff import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; //key points learned //max space ever that could be alloted in a program to pass in cf //int[][] prefixSum = new int[201][200_005]; -> not a single array more!!! //never allocate memory again again to such bigg array, it will give memory exceeded for sure //believe in your fucking solution and keep improving it!!! (sometimes) //few things to figure around //getting better and faster at taking input/output with normal method (buffered reader and printwriter) //memorise all the key algos! a public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static List<Integer> primeNumbers = new ArrayList<>(); public static void main(String[] args) { MyScanner sc = new MyScanner(); //pretty important for sure - out = new PrintWriter(new BufferedOutputStream(System.out)); //dope shit output for sure //code here int n = sc.nextInt(); long[] arr = new long[n]; long[] moves = new long[n]; for(int i= 0; i < n; i++){ arr[i] = sc.nextLong(); //simple sober technique bois moves[i] = arr[i]; } long ans = Integer.MAX_VALUE; //find the two smallest first sort(moves); long f = moves[0]; long s = moves[1]; long count = (f+ 1)/2 + (s + 1)/2; ans = min(count, ans); // out.println(ans); //now find one pair gap thingie for(int i= 0; i < n -2; i++){ long one = arr[i]; long two = arr[i + 2]; //how to write that mathematically boss long sum = one + two; count = (sum + 1)/2; ans = min(count, ans); } // out.println(ans); //no gap, adjacent ones!! best case solutions? for(int i= 0; i < n-1; i++){ long cur = 0; long xx = arr[i], yy = arr[i + 1]; long x = max(xx, yy); long y = min(xx, yy); long cnt = min(x - y, (x + 1) / 2); cur += cnt; x -= 2 * cnt; y -= cnt; if (x > 0 && y > 0) { cur += (x + y + 2) / 3; } ans = min(ans, cur); } out.println(ans); out.close(); } //new stuff to learn (whenever this is need for them, then only) //Lazy Segment Trees //Persistent Segment Trees //Square Root Decomposition //Geometry & Convex Hull //High Level DP -- yk yk //String Matching Algorithms //Heavy light Decomposition //Updation Required //Fenwick Tree - both are done (sum) //Segment Tree - both are done (min, max, sum) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //primeExponentCounts //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); edges.get(to).add(from); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ //union by size if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; 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/ x = (x * x); } return res; } public static class segmentTree{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query -> O(logn) //update -> O(logn) //update-range -> O(n) (worst case) //simple iteration and stuff for sure public segmentTree(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long query(int s, int e, int qs , int qe, int index){ //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //no overlap if(qe < s || qs > e){ return Integer.MAX_VALUE; } //partial overlap int mid = (s + e)/2; long left = query( s, mid , qs, qe, 2*index); long right = query( mid + 1, e, qs, qe, 2*index + 1); return min(left, right); } //gonna do range updates for sure now!! //let's do this bois!!! (solve this problem for sure) public void updateRange(int s, int e, int l, int r, long increment, int index){ //out of bounds if(l > e || r < s){ return; } //leaf node if(s == e){ tree[index] += increment; return; //behnchoda return tera baap krvayege? } //recursive case int mid = (s + e)/2; updateRange(s, mid, l, r, increment, 2 * index); updateRange(mid + 1, e, l, r, increment, 2 * index + 1); tree[index] = min(tree[2 * index], tree[2 * index + 1]); } } public static class segmentTreeLazy{ //so let's make a constructor function for this bad boi for sure!!! public long[] arr; public long[] tree; public long[] lazy; //COMPLEXITY (normal segment tree, stuff) //build -> O(n) //query-range -> O(logn) //lazy update-range -> O(logn) (imp) //simple iteration and stuff for sure public segmentTreeLazy(long[] arr){ int n = arr.length; this.arr = new long[n]; for(int i= 0; i < n; i++){ this.arr[i] = arr[i]; } tree = new long[4*n + 1]; lazy = new long[1000000]; //pretty big for no inconvenience (no?) NONONONOONON! NO fucker NO! } //pretty basic idea if you read the code once //first make child node once //then form the parent node using them public void buildTree(int s, int e, int index){ if(s == e){ tree[index] = arr[s]; return; } //recursive case int mid = (s + e)/2; buildTree(s, mid, 2 * index); buildTree(mid + 1, e, 2*index + 1); //the condition we want from children be like this tree[index] = min(tree[2 * index], tree[2 * index + 1]); return; } //definitely index based 0 query!!! //only int index = 1!! //baaki everything is simple as fuck public long queryLazy(int s, int e, int qs, int qe, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > qe || e < qs){ return Long.MAX_VALUE; } //complete overlap if(s >= qs && e <= qe){ return tree[index]; } //partial overlap int mid = (s + e)/2; long left = queryLazy(s, mid, qs, qe, 2 * index); long right = queryLazy(mid + 1, e, qs, qe, 2 * index + 1); return Math.min(left, right); } //update range in O(logn) -- using lazy array public void updateRangeLazy(int s, int e, int l, int r, int inc, int index){ //before going down resolve if it exist if(lazy[index] != 0){ tree[index] += lazy[index]; //non leaf node if(s != e){ lazy[2*index] += lazy[index]; lazy[2*index + 1] += lazy[index]; } lazy[index] = 0; //clear the lazy value at current node for sure } //no overlap if(s > r || l > e){ return; } //another case if(l <= s && e <= r){ tree[index] += inc; //create a new lazy value for children node if(s != e){ lazy[2*index] += inc; lazy[2*index + 1] += inc; } return; } //recursive case int mid = (s + e)/2; updateRangeLazy(s, mid, l, r, inc, 2*index); updateRangeLazy(mid + 1, e, l, r, inc, 2*index + 1); //update the tree index tree[index] = Math.min(tree[2*index], tree[2*index + 1]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors public static int countDivisors(long number){ if(number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while(curr * curr <= number){ while(number % curr == 0){ number = number/curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if(number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //primeExponentCounts public static int primeExponentsCount(int n) { if (n <= 1) return 0; int sqrt = (int) Math.sqrt(n); int remainingNumber = n; int result = 0; for (int i = 2; i <= sqrt; i++) { while (remainingNumber % i == 0) { result++; remainingNumber /= i; } } //in case of prime numbers this would happen if (remainingNumber > 1) { result++; } return result; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public 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); } //sort long public static void sort(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); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; public int hashCode; Pair(int a , int b){ this.a = a; this.b = b; this.hashCode = Objects.hash(a, b); } @Override public String toString(){ return a + " -> " + b; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair that = (Pair) o; return a == that.a && b == that.b; } @Override public int hashCode() { return this.hashCode; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // long[] fact = new long[2 * n + 1]; // long[] ifact = new long[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (long i = 1; i <= 2 * n; i++) // { // fact[(int)i] = mod_mul(fact[(int)i - 1], i, mod); // ifact[(int)i] = mminvprime(fact[(int)i], mod); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------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 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
cc4a0aaeed4f63c0fe469ee0f16f8e30
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 E1 { public static void main (String[] args) throws IOException { Kattio io = new Kattio(); int n = io.nextInt(); long[] arr = new long[n]; for (int i=0; i<n; i++) { arr[i] = io.nextLong(); } //case 1: long min1 = Integer.MAX_VALUE; long min2 = Integer.MAX_VALUE; for (int i=0; i<n; i++) { long x = arr[i]; if (x <= min1) { min2 = min1; min1 = x; } else if (min1 < x && x < min2) { min2 = x; } } //System.out.println(min1 + " " + min2); long ans = (min1 + 1)/2 + (min2 + 1)/2; //case 2: for (int i=0; i<n-1; i++) { long x = arr[i]; long y = arr[i+1]; if (x > y) { long temp = y; y = x; x = temp; } long ops = Math.min(x, y-x); x -= ops; y -= 2 * ops; //System.out.println("xy: " + x + " " + y); if (x == 0) { ops += (y+1)/2; } else { ops += (x + y + 2)/3; } //System.out.println(i + " " + ops); ans = Math.min(ans, ops); } //case 3: for (int i=0; i<n-2; i++) { long x = arr[i]; long y = arr[i+2]; long ops = Math.min(x, y); ops += (Math.max(x, y) - Math.min(x, y) + 1)/2; ans = Math.min(ans, ops); } System.out.println(ans); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(new FileWriter(problemName + ".out")); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["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
3a51d5b325b95e224077b18d3185f9ed
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.lang.Math; import java.lang.reflect.Array; import java.util.*; import javax.swing.text.DefaultStyledDocument.ElementSpec; public final class Solution { static BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); static BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(System.out) ); static StringTokenizer st; /*write your constructor and global variables here*/ static class sortCond implements Comparator<Pair<Integer, Integer>> { @Override public int compare(Pair<Integer, Integer> p1, Pair<Integer, Integer> p2) { if (p1.a <= p2.a) { return -1; } else { return 1; } } } static class Rec { int a; int b; long c; Rec(int a, int b, long c) { this.a = a; this.b = b; this.c = c; } } static class Pair<f, s> { f a; s b; Pair(f a, s b) { this.a = a; this.b = b; } } interface modOperations { int mod(int a, int b, int mod); } static int findBinaryExponentian(int a, int pow, int mod) { if (pow == 1) { return a; } else if (pow == 0) { return 1; } else { int retVal = findBinaryExponentian(a, (int) pow / 2, mod); int val = (pow % 2 == 0) ? 1 : a; return modMul.mod(modMul.mod(retVal, retVal, mod), val, mod); } } static int findPow(int a, int b, int mod) { if (b == 1) { return a % mod; } else if (b == 0) { return 1; } else { int res = findPow(a, (int) b / 2, mod); return modMul.mod(res, modMul.mod(res, (b % 2 == 1 ? a : 1), mod), mod); } } static int bleft(int ele, int[] sortedArr) { int l = 0; int h = sortedArr.length - 1; int ans = -1; while (l <= h) { int mid = l + (int) (h - l) / 2; if (sortedArr[mid] < ele) { ans = mid; l = mid + 1; } else if (sortedArr[mid] >= ele) { h = mid - 1; } } return ans; } static int gcd(int a, int b) { int div = b; int rem = a % b; while (rem != 0) { int temp = rem; rem = div % rem; div = temp; } return div; } static long[] log(long no, long n) { long i = 1; int cnt = 0; long sum = 0l; long arr[] = new long[2]; while (i < no) { sum += i; cnt++; if (sum == n) { arr[0] = 1l * cnt; arr[1] = sum; break; } i *= 2l; } if (arr[0] == 0) { arr[0] = cnt; arr[1] = sum; } return arr; } static modOperations modAdd = (int a, int b, int mod) -> { return (a % mod + b % mod) % mod; }; static modOperations modSub = (int a, int b, int mod) -> { return (int) ((1l * a % mod - 1l * b % mod + 1l * mod) % mod); }; static modOperations modMul = (int a, int b, int mod) -> { return (int) ((1l * (a % mod) * 1l * (b % mod)) % (1l * mod)); }; static modOperations modDiv = (int a, int b, int mod) -> { return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod); }; static HashSet<Integer> primeList(int MAXI) { int[] prime = new int[MAXI + 1]; HashSet<Integer> obj = new HashSet<>(); for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) { if (prime[i] == 0) { obj.add(i); for (int j = i * i; j <= MAXI; j += i) { prime[j] = 1; } } } for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) { if (prime[i] == 0) { obj.add(i); } } return obj; } static int[] factorialList(int MAXI, int mod) { int[] factorial = new int[MAXI + 1]; factorial[2] = 1; for (int i = 3; i < MAXI + 1; i++) { factorial[i] = modMul.mod(factorial[i - 1], i, mod); } return factorial; } static void put(HashMap<Integer, Integer> cnt, int key) { if (cnt.containsKey(key)) { cnt.replace(key, cnt.get(key) + 1); } else { cnt.put(key, 1); } } static long arrSum(ArrayList<Long> arr) { long tot = 0; for (int i = 0; i < arr.size(); i++) { tot += arr.get(i); } return tot; } static int ord(char b) { return (int) b - (int) 'a'; } static int optimSearch(int[] cnt, int lower_bound, int pow, int n) { int l = lower_bound + 1; int h = n; int ans = 0; while (l <= h) { int mid = l + (h - l) / 2; if (cnt[mid] - cnt[lower_bound] == pow) { return mid; } else if (cnt[mid] - cnt[lower_bound] < pow) { ans = mid; l = mid + 1; } else { h = mid - 1; } } return ans; } static Pair<Long, Integer> ret_ans(ArrayList<Integer> ans) { int size = ans.size(); int mini = 1000000000 + 1; long tit = 0l; for (int i = 0; i < size; i++) { tit += 1l * ans.get(i); mini = Math.min(mini, ans.get(i)); } return new Pair<>(tit - mini, mini); } static int factorList( HashMap<Integer, Integer> maps, int no, int maxK, int req ) { int i = 1; while (i * i <= no) { if (no % i == 0) { if (i != no / i) { put(maps, no / i); } put(maps, i); if (maps.get(i) == req) { maxK = Math.max(maxK, i); } if (maps.get(no / i) == req) { maxK = Math.max(maxK, no / i); } } i++; } return maxK; } static ArrayList<Integer> getKeys(HashMap<Integer, Integer> maps) { ArrayList<Integer> vals = new ArrayList<>(); for (Map.Entry<Integer, Integer> map : maps.entrySet()) { vals.add(map.getKey()); } return vals; } static ArrayList<Integer> getValues(HashMap<Integer, Integer> maps) { ArrayList<Integer> vals = new ArrayList<>(); for (Map.Entry<Integer, Integer> map : maps.entrySet()) { vals.add(map.getValue()); } return vals; } static int getMax(ArrayList<Integer> arr) { int max = arr.get(0); for (int i = 1; i < arr.size(); i++) { if (arr.get(i) > max) { max = arr.get(i); } } return max; } static int getMin(ArrayList<Integer> arr) { int max = arr.get(0); for (int i = 1; i < arr.size(); i++) { if (arr.get(i) < max) { max = arr.get(i); } } return max; } static int list[][] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } }; /*write your methods and classes here*/ public static void main(String[] args) throws IOException { int cases = 1, n, i; while (cases-- != 0) { n = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); int arr[] = new int[n]; for (i = 0; i < n; i++) { arr[i] = Integer.parseInt(st.nextToken()); } int tot = 10000001; for (i = 0; i < n - 1; i++) { int val1 = Math.max(arr[i], arr[i + 1]); int val2 = Math.min(arr[i], arr[i + 1]); if (2 * val2 >= val1) { tot = Math.min((arr[i] + arr[i + 1] + 2) / 3, tot); } else { tot = Math.min(tot, (val1 + 1) / 2); } if (i + 2 < n) { tot = Math.min(tot, Math.max(arr[i], arr[i + 2])); tot = Math.min(tot, arr[i] / 2 + arr[i + 2] / 2 + 1); } } Arrays.sort(arr); for (i = 0; i < n - 1; i++) { tot = Math.min(tot, (arr[i] + 1) / 2 + (arr[i + 1] + 1) / 2); } bw.write(Integer.toString(tot) + "\n"); } 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
3b431b5382bbe0e41e364e547928943b
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.lang.reflect.Array; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { public static void main(String[] args) { in = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); try { // int t = in.nextInt(); while(t-- > 0) { solve(); out.println();} solve(); } finally { out.close(); } return; } public static void solve() { int n = in.nextInt(); int[] a = fillArray(n); Integer[] A = new Integer[n]; for(int i = 0; i < n; i++) { A[i] = a[i]; } Arrays.sort(A); int min = (A[0] + 1) / 2 + (A[1] + 1) / 2; for(int i = 1; i < n - 1; i++) { int mm = Math.min(a[i-1], a[i+1]); int prev = a[i-1] - mm; int next = a[i+1] - mm; min = Math.min(min, mm + Math.max((prev+1)/2, ((next +1) /2 ))); } for(int i = 0; i + 1 < n; i++) { if(a[i] <= (a[i+1]+1) / 2) { min = Math.min(min, (a[i+1]+1)/2); continue; } if(a[i+1] <= (a[i] + 1) / 2) { min = Math.min(min, (a[i] +1)/2); continue; } min = Math.min(min, (a[i] + a[i+1] + 2) / 3); } out.print(min); return; } //-------------- Helper methods------------------- public static int[] fillArray(int n) { int[] array = new int[n]; for(int i = 0; i < n; i++) { array[i] = in.nextInt(); } return array; } public static char[] fillArray() { char[] array = in.next().toCharArray(); return array; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static MyScanner in; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } void shuffleArray(int[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } //-------------------------------------------------------- }
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
75fa85f40ef2f2b7378248eb861ce097
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 sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; int b[]=new int[n]; for(int i=0;i<a.length;i++){ a[i]=sc.nextInt(); b[i]=a[i]; } Arrays.sort(b); int ans=(b[0]+1)/2+(b[1]+1)/2; for(int i=1;i<a.length-1;i++){ int prev=a[i-1]; int next=a[i+1]; int min=Math.min(prev,next); int max=Math.max(prev,next); ans=Math.min(ans,min+(max-min+1)/2); } for(int i=0;i<b.length-1;i++){ int prev=Math.min(a[i+1],a[i]); int next=Math.max(a[i+1],a[i]); int sum=Math.min((prev+1)/2+Math.max(0,((next-(prev+1)/2+1)/2)),(next+1)/2+Math.max(0,((prev-(next+1)/2+1)/2))); ans=Math.min(ans,sum); if(prev>(next+1)/2){ ans=Math.min(ans,(prev+next+2)/3); } } 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
6c0db65131301121f297d565ee38ef0e
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 { private int min2(int a, int b) { int max = Math.max(a, b); int min = Math.min(a, b); if((max + 1) / 2 >= min) { return (max + 1) / 2; } else { return (max + min + 2) / 3; } } private int min3(int a, int b, int c) { int cand1 = min2(a, b); int cand2 = min2(b, c); int cand3 = (a + c + 1) / 2; return Math.min(Math.min(cand1, cand2), cand3); } void go() { int n = Reader.nextInt(); int[] A = new int[n]; for(int i = 0; i < n; i++) { A[i] = Reader.nextInt(); } int adj = Integer.MAX_VALUE; int min1 = Integer.MAX_VALUE; int min2 = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { int m = (A[i] + 1) / 2; if(i == 0) { adj = Math.min(adj, min2(A[i], A[i + 1])); } else if(i == n - 1) { adj = Math.min(adj, min2(A[i], A[i - 1])); } else { adj = Math.min(adj, min3(A[i - 1], A[i], A[i + 1])); } if(m < min1) { min2 = min1; min1 = m; } else if(m < min2){ min2 = m; } } Writer.println(Math.min(adj, min1 + min2)); } void solve() { go(); } void run() throws Exception { Reader.init(System.in); Writer.init(System.out); solve(); Writer.close(); } public static void main(String[] args) throws Exception { new E().run(); } public static class Reader { public static StringTokenizer st; public static BufferedReader br; public static void init(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public static String next() { while(!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new InputMismatchException(); } } return st.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static double nextDouble() { return Double.parseDouble(next()); } } public static class Writer { public static PrintWriter pw; public static void init(OutputStream os) { pw = new PrintWriter(new BufferedOutputStream(os)); } public static void print(String s) { pw.print(s); } public static void print(char c) { pw.print(c); } public static void print(int x) { pw.print(x); } public static void print(long x) { pw.print(x); } public static void println(String s) { pw.println(s); } public static void println(char c) { pw.println(c); } public static void println(int x) { pw.println(x); } public static void println(long x) { pw.println(x); } public static void flush() { pw.flush(); } public static void close() { pw.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
92e3bf63d10ec1dc994b78a44c7d74e5
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.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; public class Main { static long MOD = 998244353l; int min = Integer.MAX_VALUE; int max = 0; char result[][]; int count = 0; int pattern = 0; public static void main(String[] args) throws Exception { // FileInputStream fis = new FileInputStream(new File("1.txt")); var sc = new FastScanner(); // var sc = new FastScanner(fis); // var pw = new FastPrintStream("test_normal_result.csv"); var pw = new FastPrintStream(); solve(sc, pw); sc.close(); pw.flush(); pw.close(); } public static void solve(FastScanner sc, FastPrintStream pw) { int n = sc.nextInt(); int a[] = new int[n]; Arrays.setAll(a, i -> sc.nextInt()); int re = Integer.MAX_VALUE; int times[] = new int[n]; for (int i = 0; i < n; i++) { times[i] = a[i] / 2 + a[i] % 2; } Arrays.sort(times); re = times[0] + times[1]; for (int i = 0; i + 1 < n; i++) { int min = Math.min(a[i], a[i + 1]); int max = Math.max(a[i], a[i + 1]); if (max > 2 * min) { int temp = max / 2 + max % 2; re = Math.min(re, temp); } else { int temp = (a[i] + a[i + 1]) / 3; if ((a[i] + a[i + 1]) % 3 != 0) { temp++; } re = Math.min(re, temp); } } for (int i = 0; i + 2 < n; i++) { if (a[i] % 2 == 1 && a[i + 2]%2 == 1) { re = Math.min(re, a[i] / 2 + a[i + 2] / 2 + 1); } } pw.println(re); } public static Point checkPoint(char ch) { Point re = new Point(0, 0); switch (ch) { case 'N': { re.x--; break; } case 'S': { re.x++; break; } case 'E': { re.y++; break; } case 'W': { re.y--; break; } } return re; } public char[][] copyArray(char c[][], int n) { char re[][] = new char[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { re[i][j] = c[i][j]; } } return re; } public static void swap(int[] s, int i, int j) { int tmp = s[i]; s[i] = s[j]; s[j] = tmp; } public void permutation(int[] s, int from, int to, int a[]) { if (to <= 1) return; if (from == to) { check(s, a); } else { for (int i = from; i <= to; i++) { swap(s, i, from); permutation(s, from + 1, to, a); swap(s, from, i); } } } public void check(int[] s, int a[]) { int re = 0; int b[][] = new int[2][3]; for (int i = 0; i < 6; i++) { b[i / 3][i % 3] = a[s[i]]; } int maxx = 0; int maxy = 0; int minx = 10000; int miny = 10000; for (int i = 0; i < 3; i++) { maxx = Math.max(maxx, b[0][i]); minx = Math.min(minx, b[0][i]); maxy = Math.max(maxy, b[1][i]); miny = Math.min(miny, b[1][i]); } re = (maxx - minx) * (maxy - miny) * 2; re = re - (Math.abs(b[0][0] - b[0][1]) * Math.abs(b[1][0] - b[1][1])); re = re - (Math.abs(b[0][0] - b[0][2]) * Math.abs(b[1][0] - b[1][2])); re = re - (Math.abs(b[0][2] - b[0][1]) * Math.abs(b[1][2] - b[1][1])); max = Math.max(re, max); } public static long anothertoTen(long ano, int another) { long ten = 0; long now = 1; long temp = ano; while (temp > 0) { long i = temp % 10; ten += now * i; now *= another; temp /= 10; } return ten; } public static long tentoAnother(long ten, int another) { Stack<Long> stack = new Stack<Long>(); while (ten > 0) { stack.add(ten % another); ten /= another; } long re = 0; while (!stack.isEmpty()) { long pop = stack.pop(); re = re * 10 + pop; } return re; } // 2C5 = 5*4/(2*1) public static long XCY(long x, long y) { long temp = 1; for (int i = 0; i < x; i++) { temp = (temp * (y - i)) % MOD; } long tempx = 1; for (int i = 2; i <= x; i++) { tempx = (tempx * i) % MOD; } tempx = modpow(tempx, (long) MOD - 2); temp = (temp * tempx) % MOD; return temp; } static long modpow(long N, Long K) { return BigInteger.valueOf(N).modPow(BigInteger.valueOf(K), BigInteger.valueOf(MOD)).longValue(); } static long modpow(long N, Long K, long mod) { return BigInteger.valueOf(N).modPow(BigInteger.valueOf(K), BigInteger.valueOf(mod)).longValue(); } public static long gcd(long a, long b) { if (b == 0) { return a; } if (a < b) { return gcd(b, a); } return gcd(b, a % b); } public static int gcd(int a, int b) { if (b == 0) { return a; } if (a < b) { return gcd(b, a); } return gcd(b, a % b); } } class Range { long x = 0; long c = 0; public Range(long x, long c) { this.x = x; this.c = c; } } class Target { int t; long c; boolean bool; } class Point implements Comparable { int x; int y; public Point() { } public Point(int x, int y) { this.x = x; this.y = y; } public int compareTo(Object p) { Point t = (Point) p; if (this.y < t.y) { return -1; } if (this.y > t.y) { return 1; } if (this.x < t.x) { return -1; } return 1; } } class PointY implements Comparable { int a; int b; public int compareTo(Object p) { PointY t = (PointY) p; if (this.a > t.a) { return -1; } if (this.a < t.a) { return 1; } return 0; } } class FastPrintStream implements AutoCloseable { private static final int BUF_SIZE = 1 << 15; private final byte[] buf = new byte[BUF_SIZE]; private int ptr = 0; private final java.lang.reflect.Field strField; private final java.nio.charset.CharsetEncoder encoder; private java.io.OutputStream out; public FastPrintStream(java.io.OutputStream out) { this.out = out; java.lang.reflect.Field f; try { f = java.lang.String.class.getDeclaredField("value"); f.setAccessible(true); } catch (NoSuchFieldException | SecurityException e) { f = null; } this.strField = f; this.encoder = java.nio.charset.StandardCharsets.US_ASCII.newEncoder(); } public FastPrintStream(java.io.File file) throws java.io.IOException { this(new java.io.FileOutputStream(file)); } public FastPrintStream(java.lang.String filename) throws java.io.IOException { this(new java.io.File(filename)); } public FastPrintStream() { this(System.out); try { java.lang.reflect.Field f = java.io.PrintStream.class.getDeclaredField("autoFlush"); f.setAccessible(true); f.set(System.out, false); } catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException e) { // ignore } } public FastPrintStream println() { if (ptr == BUF_SIZE) internalFlush(); buf[ptr++] = (byte) '\n'; return this; } public FastPrintStream println(java.lang.Object o) { return print(o).println(); } public FastPrintStream println(java.lang.String s) { return print(s).println(); } public FastPrintStream println(char[] s) { return print(s).println(); } public FastPrintStream println(char c) { return print(c).println(); } public FastPrintStream println(int x) { return print(x).println(); } public FastPrintStream println(long x) { return print(x).println(); } public FastPrintStream println(double d, int precision) { return print(d, precision).println(); } private FastPrintStream print(byte[] bytes) { int n = bytes.length; if (ptr + n > BUF_SIZE) { internalFlush(); try { out.write(bytes); } catch (java.io.IOException e) { throw new RuntimeException(); } } else { System.arraycopy(bytes, 0, buf, ptr, n); ptr += n; } return this; } public FastPrintStream print(java.lang.Object o) { return print(o.toString()); } public FastPrintStream print(java.lang.String s) { if (strField == null) { return print(s.getBytes()); } else { try { return print((byte[]) strField.get(s)); } catch (IllegalAccessException e) { return print(s.getBytes()); } } } public FastPrintStream print(char[] s) { try { return print(encoder.encode(java.nio.CharBuffer.wrap(s)).array()); } catch (java.nio.charset.CharacterCodingException e) { byte[] bytes = new byte[s.length]; for (int i = 0; i < s.length; i++) { bytes[i] = (byte) s[i]; } return print(bytes); } } public FastPrintStream print(char c) { if (ptr == BUF_SIZE) internalFlush(); buf[ptr++] = (byte) c; return this; } public FastPrintStream print(int x) { if (x == 0) { if (ptr == BUF_SIZE) internalFlush(); buf[ptr++] = '0'; return this; } int d = len(x); if (ptr + d > BUF_SIZE) internalFlush(); if (x < 0) { buf[ptr++] = '-'; x = -x; d--; } int j = ptr += d; while (x > 0) { buf[--j] = (byte) ('0' + (x % 10)); x /= 10; } return this; } public FastPrintStream print(long x) { if (x == 0) { if (ptr == BUF_SIZE) internalFlush(); buf[ptr++] = '0'; return this; } int d = len(x); if (ptr + d > BUF_SIZE) internalFlush(); if (x < 0) { buf[ptr++] = '-'; x = -x; d--; } int j = ptr += d; while (x > 0) { buf[--j] = (byte) ('0' + (x % 10)); x /= 10; } return this; } public FastPrintStream print(double d, int precision) { if (d < 0) { print('-'); d = -d; } d += Math.pow(10, -d) / 2; print((long) d).print('.'); d -= (long) d; for (int i = 0; i < precision; i++) { d *= 10; print((int) d); d -= (int) d; } return this; } private void internalFlush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (java.io.IOException e) { throw new RuntimeException(e); } } public void flush() { try { out.write(buf, 0, ptr); out.flush(); ptr = 0; } catch (java.io.IOException e) { throw new RuntimeException(e); } } public void close() { try { out.close(); } catch (java.io.IOException e) { throw new RuntimeException(e); } } private static int len(int x) { int d = 1; if (x >= 0) { d = 0; x = -x; } int p = -10; for (int i = 1; i < 10; i++, p *= 10) if (x > p) return i + d; return 10 + d; } private static int len(long x) { int d = 1; if (x >= 0) { d = 0; x = -x; } long p = -10; for (int i = 1; i < 19; i++, p *= 10) if (x > p) return i + d; return 19 + d; } } class FastScanner implements AutoCloseable { private final java.io.InputStream in; private final byte[] buf = new byte[2048]; private int ptr = 0; private int buflen = 0; public FastScanner(java.io.InputStream in) { this.in = in; } public FastScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) return true; ptr = 0; try { buflen = in.read(buf); } catch (java.io.IOException e) { throw new RuntimeException(e); } return buflen > 0; } private int readByte() { return hasNextByte() ? buf[ptr++] : -1; } public boolean hasNext() { while (hasNextByte() && !(32 < buf[ptr] && buf[ptr] < 127)) ptr++; return hasNextByte(); } private StringBuilder nextSequence() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); for (int b = readByte(); 32 < b && b < 127; b = readByte()) { sb.appendCodePoint(b); } return sb; } public String next() { return nextSequence().toString(); } public String next(int len) { return new String(nextChars(len)); } public char nextChar() { if (!hasNextByte()) throw new java.util.NoSuchElementException(); return (char) readByte(); } public char[] nextChars() { StringBuilder sb = nextSequence(); int l = sb.length(); char[] dst = new char[l]; sb.getChars(0, l, dst, 0); return dst; } public char[] nextChars(int len) { if (!hasNext()) throw new java.util.NoSuchElementException(); char[] s = new char[len]; int i = 0; int b = readByte(); while (32 < b && b < 127 && i < len) { s[i++] = (char) b; b = readByte(); } if (i != len) { throw new java.util.NoSuchElementException( String.format("Next token has smaller length than expected.", len)); } return s; } public long nextLong() { if (!hasNext()) throw new java.util.NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) throw new NumberFormatException(); while (true) { if ('0' <= b && b <= '9') { n = n * 10 + b - '0'; } else if (b == -1 || !(32 < b && b < 127)) { return minus ? -n : n; } else throw new NumberFormatException(); b = readByte(); } } public int nextInt() { return Math.toIntExact(nextLong()); } public double nextDouble() { return Double.parseDouble(next()); } public void close() { try { in.close(); } catch (java.io.IOException e) { throw new RuntimeException(e); } } } /** * @verified https://atcoder.jp/contests/practice2/tasks/practice2_j */ class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException(String.format("Invalid range: [%d, %d)", l, r)); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Long.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX)); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX)); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n-- > 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n) || !(0 <= b && b < n)) { return -1; } int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n) || !(0 <= b && b < n)) { return false; } return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) { return -1; } return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i < n; i++) { result.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } return result; } }
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
4f7f14918a709f314ea6869b73659f55
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.*; public class X { public boolean[] V; public ArrayList<ArrayList<Integer>> E; public int S; public boolean[] P; public int Curr; public HashSet<Integer> Tot; public HashSet<Integer> Child; public ArrayList<ArrayList<Integer>> RevE; public int[] Rev; public HashSet<Integer> RevV; public static void main(String[] args) { X ob=new X(); 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(); System.out.println(ob.solve(A)); } int solve(int[] A) { int N=A.length; double min=1000000000; PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); pq.add(A[0]); for(int i=1;i<N;i++) { double d1=A[i]+A[i-1]; d1=Math.ceil(d1/3); if((2*d1)<(Math.max(A[i],A[i-1]))) { d1=Math.max(A[i],A[i-1]); d1=Math.ceil(d1/2); } double d2=1000000000; if(1<i) d2=A[i]+A[i-2]; d2=Math.ceil(d2/2); min=Math.min(min,d1); min=Math.min(min,d2); pq.add(A[i]); } double m1=pq.poll(); //System.out.println("min1 - "+m1); m1=Math.ceil(m1/2); double m2=pq.poll(); //System.out.println("min2 - "+m2); m2=Math.ceil(m2/2); int min1=(int)min; int min2=(int)(m1+m2); return Math.min(min1,min2); } void dfs(int N) { //System.out.println("mkdfs -> "+N); for(int i=0;i<E.get(N).size();i++) { int NN=E.get(N).get(i); if(Curr!=NN) { P[NN]=true; } if(!V[NN]) { V[NN]=true; dfs(NN); } } } void udfs(int N) { //System.out.println("C-> "+Curr+" , N -> "+N+" , "); if(Curr!=N) { Child.add(N); } if(Rev[N]!=0) { Child.add(Rev[N]); } for(int i=0;i<E.get(N).size();i++) { int NN=E.get(N).get(i); //System.out.println("loop NN ->"+NN); if(Curr!=NN && Tot.contains(NN)) { Child.add(NN); } if(!V[NN]) { V[NN]=true; udfs(NN); } if(Rev[NN]!=0) { Child.add(Rev[NN]); } } //System.out.println(""); } void revdfs(int N) { //System.out.println("mkdfs -> "+N); Rev[N]=Curr; for(int i=0;i<RevE.get(N).size();i++) { int NN=RevE.get(N).get(i); Rev[NN]=Curr; if(!RevV.contains(NN)) { RevV.add(NN); revdfs(NN); } } } }
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
096d1613cc5ac7bbe20bb71e0520861b
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.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class E implements Runnable { public static void main(String[] args) { new Thread(null, new E(), "whatever", 1 << 26).start(); } FastScanner s = new FastScanner(System.in); StringBuilder sb = new StringBuilder(); public void run() { int t = 1; for (int test = 0; test < t; test++) { test(); } System.out.print(sb); } void test() { // Read input // Process // If targets are known, it's easy. // If targets are separated by at least 3, independent problems. // Sliding window, size 3. Brute force all possible // Add output to string builder sb (with newline if needed). // If there are two 1's on the board close to eachother (distance 2), // then answer is 1. // If there are two 1's, only farther apart, two separate shots are needed. // Same for 3's. 3's far apart are same as 2 4's close? // Process in 3 phases. // Pairs right next to eachother // Pairs 2 apart. // Pairs more than 2 apart. // Take min over all. int n = s.nextInt(); int minVal = Integer.MAX_VALUE; int[] nums = new int[n]; ArrayList<Integer> sorted = new ArrayList<>(); for (int i = 0; i < n; i++) { nums[i] = s.nextInt(); sorted.add(nums[i]); } Collections.sort(sorted); if (nums.length == 1) { int res = directHits(nums[0]); sb.append(res); sb.append("\n"); return; } { int a = sorted.get(0); int b = sorted.get(1); int res = directHits(a) + directHits(b); minVal = Integer.min(res, minVal); } { // Adjacent for (int i = 0; i < n - 1; i++) { int times = 0; int max = Integer.max(nums[i], nums[i + 1]); int min = Integer.min(nums[i], nums[i + 1]); // Always shoot larger until both are 0 or less int equalizer = max - min; if (equalizer > directHits(max)) { // hit 0 before equal times = directHits(max); } else { times += equalizer; max -= equalizer * 2; min -= equalizer; // now both are equal times += max / 3 * 2; max = max % 3; min = max; if (max == 1) { times++; } else if (max == 2) { times += 2; } } minVal = Integer.min(minVal, times); } } { // 1 1000 // Two apart for (int i = 0 ; i < n - 2; i++) { int max = Integer.max(nums[i], nums[i + 2]); int min = Integer.min(nums[i], nums[i + 2]); int equalizer = (max - min) / 2; max -= equalizer * 2; int middleOnly = max; int val = equalizer + middleOnly; minVal = Integer.min(minVal, val); } } sb.append(minVal); sb.append("\n"); } int directHits(int val) { int res = val / 2; if (val % 2 == 1) { res++; } return res; } 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 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
bb71ec36528cb362cf630f09a07ccf10
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.Arrays; import java.util.Random; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) { PrintWriter out = new PrintWriter(System.out); FastScanner fs = new FastScanner(); DecimalFormat formatter = new DecimalFormat("#0.000000"); int ti = 1; outer: while (ti-- > 0) { int n = fs.nextInt(); int[] a = fs.readArray(n); int min = Integer.MAX_VALUE; for (int i = 1; i < n; i++) { min = Math.min(min, two(a[i], a[i - 1])); } // System.out.println(min); for (int i = 1; i < n - 1; i++) { min = Math.min(min, the(a[i - 1], a[i + 1])); } sort(a); int t = (a[0] + 1) / 2 + (a[1] + 1) / 2; min = Math.min(min, t); out.println(min); } out.close(); } private static int two(int a, int b) { int x = Math.min(a, b); int y = Math.max(a, b); if (y >= 2 * x) return (y + 1) / 2; else return (x + y + 2) / 3; } private static int the(int a, int b) { if (b < a) return the(b, a); return a + (b - a + 1) / 2; } static final int mod = 1_000_000_007; static void sort(long[] a) { Random random = new Random(); int n = a.length; for (int i = 0; i < n; i++) { int oi = random.nextInt(n); long temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static void sort(int[] a) { Random random = new Random(); 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 int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } 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()); } float nextFloat() { return Float.parseFloat(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()); } } static class Pair { int a; int b; public Pair(int a, int b) { this.a = a; this.b = 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
41738afec9b1a0e5f269ccda8c07be59
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
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.util.*; import java.lang.*; import java.io.*; public class Solution { static int INF = (int) 1e9 + 7; public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); int[] heights = new int[n]; for (int i = 0; i < n; i++) { heights[i] = sc.nextInt(); } List<Integer> list = new ArrayList<>(); for (int height : heights) { list.add(height); } Collections.sort(list); int minHits = (list.get(0) + 1) / 2 + (list.get(1) + 1) / 2; // hitting two min height walls separately for (int i = 0; i < n; i++) { int left = INF, mid = heights[i], right = INF; if (i > 0) { left = heights[i - 1]; } if (i + 1 < n) { right = heights[i + 1]; } // hitting two walls having one more wall between them, we can see that hitting any of them causes two damage in total to the walls we want to break. minHits = Math.min(minHits, (left + right + 1) / 2); int currLeft = Math.max(left, mid); int currMid = Math.min(left, mid); // hitting two adjacent walls, left and mid, assuming left >= mid if (currLeft > 2 * currMid) { // just hitting currLeft would be enough to break both left and mid walls. minHits = Math.min(minHits, (currLeft + 1) / 2); }else { // we can see that hitting any of them causes three damage in total to the walls we want to break. minHits = Math.min(minHits, (currLeft + currMid + 2) / 3); } } out.println(minHits); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["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
74c95e6ad838faeb744358ba37538d34
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 { public static void main(String args[])throws Exception { BufferedReader bu=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); int n=Integer.parseInt(bu.readLine()); int i,a[]=new int[n]; String s[]=bu.readLine().split(" "); for(i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); int M=(int)1e9,min[]={M,M}; for(i=0;i<n;i++) { int here=(a[i]+1)/2; if(here<min[0]) {min[1]=min[0]; min[0]=here;} else min[1]=Math.min(min[1],here); } int ans=min[0]+min[1]; for(i=1;i<n;i++) //ajdacent 2 or x_x { int here=operations(Math.min(a[i],a[i-1]),Math.max(a[i],a[i-1])); ans=Math.min(ans,here); if(i-2>=0) { int op=Math.min((a[i-1]+1)/2,Math.min(a[i-2],a[i])),u=Math.max(a[i-2]-op,0),v=Math.max(a[i]-op,0); here=op+operations(Math.min(u,v),Math.max(u,v)); ans=Math.min(ans,here); } } System.out.println(ans); } static int operations(int a,int b) { int ans=Math.min(a,b-a); a-=ans; b-=2*ans; if(a==0) return ans+((b+1)/2); ans+=(a/3)*2; a%=3; return ans+a; } }
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
e3737846fac78c0eb9429b86c76c3dfd
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 extends PrintWriter { Main() { super(System.out); } static boolean cases = false; // Solution void solve(int t) { int n = sc.nextInt(); int a[] = sc.readIntArray(n); int b[] = a.clone(); sort(b); int ans = (b[0] + 1) / 2 + (b[1] + 1) / 2; for (int i = 0; i < n - 2; i++) { ans = Math.min(ans, a[i] / 2 + a[i + 2] / 2 + ((a[i] % 2 == 1 || a[i + 2] % 2 == 1) ? 1 : 0)); } for (int i = 0; i < n - 1; i++) { int min = Math.min(a[i], a[i + 1]); int max = Math.max(a[i], a[i + 1]); if (max > 2 * min) ans = Math.min(ans, (max + 1) / 2); else ans = Math.min(ans, (min + max + 2) / 3); } System.out.println(ans); } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(c); obj.solve(c); obj.flush(); } 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[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } 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()); } } private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
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
ac7be6c1dd6f2a2ec8f454ec4ad59bca
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.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class E { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(input.readLine()); int[] a = new int[n]; ArrayList<Integer> mn = new ArrayList<>(); StringTokenizer data = new StringTokenizer(input.readLine()); for(int i = 0; i < n; i++) { a[i] = Integer.parseInt(data.nextToken()); mn.add(a[i] / 2 + a[i] % 2); } Collections.sort(mn); int sol = mn.get(0) + mn.get(1); for(int i = 0; i < n; i++) { if(i > 0) { int x = Math.max(a[i-1], a[i]); int y = Math.min(a[i-1], a[i]); if(2*y <= x) { sol = Math.min(sol, x / 2 + x % 2); } else { int diff = x - y; x -= 2 * diff; y -= diff; int z = x + y; sol = Math.min(sol, diff + z / 3 + (z % 3 != 0 ? 1 : 0)); } } if(i > 1) { int x = a[i] + a[i - 2]; sol = Math.min(sol, x / 2 + x % 2); } } System.out.println(sol); } }
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
fb684d17996dc9843fda50a4704a726c
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.math.BigInteger; public class Main { public static FastReader cin; public static PrintWriter out; /*static int []arr=new int [5005]; static int []he=new int[5005]; static int []e=new int [100005]; static int []ne=new int [100005]; static int []dfn=new int [5005]; static int []low=new int [5005]; static int []stack=new int [5005]; static int []contains=new int [5005];//是否在栈中 static int []size=new int [5005]; static int []num=new int [5005]; static boolean[]visited=new boolean[5005]; static int idx=0; static int cnt=0;//用于初始化low和dfn static int top=0;//栈顶 static int index=0;//强连通分量的个数 static int INF=0x3f3f3f3f;*/ public static void main(String[] args) throws Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); cin = new FastReader(); //int u=cin.nextInt(); //label:for(int Q=0;Q<u;Q++){ int n=cin.nextInt(); int []arr=new int [n]; for(int i=0;i<n;i++){ arr[i]=cin.nextInt(); } int min=Integer.MAX_VALUE; int cimin=Integer.MAX_VALUE; int ans=Integer.MAX_VALUE; for(int i=0;i<n;i++){ if(arr[i]<=min){ cimin=min; min=arr[i]; }else if(arr[i]<cimin){ cimin=arr[i]; } if(i<n-2){//情况2 int temp = (arr[i]+arr[i+2]+1)/2; ans=Math.min(ans,temp); } if(i<n-1){//情况3 int x=Math.max(arr[i],arr[i+1]); int y=Math.min(arr[i],arr[i+1]); if(x>=2*y){ int temp=(x+1)/2; ans=Math.min(ans,temp); continue; }else{ int temp=x-y; int nowx=2*y-x; int nowy=2*y-x; temp+=(nowx+nowy+2)/3; ans=Math.min(temp,ans); } } } //out.println("min="+min+" cimin="+cimin); ans=Math.min(ans,(min+1)/2+(cimin+1)/2); out.println(ans); //} out.close(); } static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
Java
["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
b57c271a2ec2b7c7b1661d254635b992
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 MyClass { public static int formula(int a,int b){ int n=a-b; if(a-n*2<0){return (a+1)/2;} float v = 2*b - a; return a-b+(int)Math.ceil(2*v/3); } public static int compute(int[] a){ int n = a.length; int dp=0; int min=-1; if(a[0]<a[1]){ min=0; } else min=1; dp = formula(Math.max(a[0],a[1]),Math.min(a[0],a[1])); if(n==2) return dp; for(int i=2;i<n;i++){ int x=0; int y=formula(Math.max(a[i],a[i-1]),Math.min(a[i],a[i-1])); if(min==i-1){ x=y; } else{ x = (a[i]+1)/2 + (a[min]+1)/2; if(min==i-2){ if(a[min]%2!=0 && a[i]%2!=0) x--; } } dp=Math.min(dp,Math.min(y,x)); if(a[i]<=a[min]) min=i; } return dp; } public static void main (String[] args) { Scanner in= new Scanner(System.in); int n=in.nextInt(); int[] a = new int[n]; for(int l=0;l<n;l++){ a[l]=in.nextInt(); } System.out.println(compute(a)); } }
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
13cd81459c9803020eaec0d4fadc535e
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 MyClass { public static int formula(int a,int b){ int n=a-b; if(a-n*2<0){return (a+1)/2;} float v = 2*b - a; return a-b+(int)Math.ceil(2*v/3); } public static int compute(int[] a){ int n = a.length; int [] dp = new int[n]; int min=-1; if(a[0]<a[1]){ min=0; } else min=1; dp[0] = formula(Math.max(a[0],a[1]),Math.min(a[0],a[1])); dp[1]=dp[0]; if(n==2) return dp[0]; //System.out.println(dp[0]); //System.out.println(dp[1]); for(int i=2;i<n;i++){ int x=0; int y=formula(Math.max(a[i],a[i-1]),Math.min(a[i],a[i-1])); if(min==i-1){ x=y; } else{ x = (a[i]+1)/2 + (a[min]+1)/2; if(min==i-2){ if(a[min]%2!=0 && a[i]%2!=0) x--; } } dp[i]=Math.min(dp[i-1],Math.min(y,x)); if(a[i]<=a[min]) min=i; //System.out.println(dp[i]); } return dp[n-1]; } public static void main (String[] args) { Scanner in= new Scanner(System.in); int n=in.nextInt(); int[] a = new int[n]; for(int l=0;l<n;l++){ a[l]=in.nextInt(); } System.out.println(compute(a)); } }
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
3c5f82c98dabb25a88be734ee3cf94d0
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 codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class CF786_E { public static void main (String[] args) throws java.lang.Exception { /* BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0){ int n=Integer.parseInt(br.readLine()); String[] inp=br.readLine().trim().split(" "); } */ /* Scanner cs=new Scanner(System.in); int t=cs.nextInt(); while(t-->0){ int n=cs.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=cs.nextInt(); } } */ Scanner cs=new Scanner(System.in); // int t=cs.nextInt(); int t=1; while(t-->0){ int n=cs.nextInt(); int[] a=new int[n]; int[] b=new int[n]; for(int i=0;i<n;i++){ a[i]=cs.nextInt(); } System.arraycopy(a,0,b,0,n); // for(int i=0;i<n;i++){ // System.out.println(b[i]); // } Arrays.sort(b); int ans=(b[0]+1)/2+(b[1]+1)/2; for(int i=1;i<n-1;i++){ int prev=a[i-1]; int next=a[i+1]; int now=(prev/2)+(next/2); prev%=2; next%=2; if(prev!=0 || next!=0) now++; ans=Math.min(ans, now); } 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); continue; } ans=Math.min(ans, (x+y+2)/3); } 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
6199c33403b199bde6f358719a24044f
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
d6723a950c0a95ce26cbb0135caa7e14
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 codechef; // don't place package name! */ //package com.company; import java.util.*; import java.io.*; import java.lang.*; public class Main{ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int[][] vis; static int dfs(char[][] a, int i, int j, int[] dx, int[] dy, int m, int n) { int c = a[i][j]; int max = 0; for (int k = 0; k < 8; k++) { int x = i + dx[k]; int y = j + dy[k]; if (x >= 0 && x < m && y >= 0 && y < n) { int c1 = a[x][y]; if (c1 == c + 1) { if (vis[x][y] == 0) vis[x][y] = dfs(a, x, y, dx, dy, m, n); max = Math.max(max, vis[x][y]); } } } vis[i][j] = 1 + max; return vis[i][j]; } static class obj { int a1; int a2; obj(int i, int j) { this.a1 = i; this.a2 = j; //this.a3=k; } } static class sortby implements Comparator<obj> { public int compare(obj o1, obj o2) { if (o1.a2 > o2.a2) return 1; return -1; } } static class sortby1 implements Comparator<obj> { public int compare(obj o1, obj o2) { if (o1.a1 > o2.a1) return 1; else if(o1.a2==o1.a2){ return o2.a1-o1.a1; } return -1; } } public static long sum(int[] c, int m1, int m2) { if (m1 == m2) { return c[m1]; } return c[m1] + c[m2]; } /*static int[] dx={1,-1,0,0,1,-1,-1,1}; static int[] dy={1,-1,1,-1,0,0,1,-1}; // static int min=Integer.MAX_VALUE; public static void solve(int n,int x1,int y1,int x2,int y2,int k){ if(x1==x2&&y1==y2){ min=Math.min(k,min); return ; } for(int i=0;i<8;i++){ int x3=x1+dx[i]; int y3=y1+dy[i]; solve(n,x3,y3,x2,y2,k+1); } }*/ public static long sum(long x) { if (x % 2 == 0) return (x / 2) * (x + 1); return x * ((x + 1) / 2); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static boolean[] bfs(ArrayList<ArrayList<Integer>> adj,int k,int n){ Queue<Integer> q=new LinkedList<>(); q.add(k); boolean[] v=new boolean[n+1]; while(q.size()>0){ int j=q.poll(); v[j]=true; for(int x:adj.get(j)){ if(!v[x]){ q.add(x); } } } return v; } /* static int minCoins(int coins[], int m, int V) { // table[i] will be storing // the minimum number of coins // required for i value. So // table[V] will have result long table[] = new long[V + 1]; // Base case (If given value V is 0) table[0] = 0; // Initialize all table values as Infinite for (int i = 1; i <= V; i++) table[i] = Integer.MAX_VALUE; // Compute minimum coins required for all // values from 1 to V for (int i = 1; i <= V; i++) { // Go through all coins smaller than i for (int j = 0; j < m; j++) if (coins[j] <= i) { int sub_res = table[i - coins[j]]; if (sub_res != Integer.MAX_VALUE && sub_res + 1 < table[i]) table[i] = sub_res + 1; } } if(table[V]==Integer.MAX_VALUE) return -1; return table[V]; }*/ static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) > 0) res = (res * x) % p; y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } static long solve(long[] a,int s,int e,long x){ long y=Long.MAX_VALUE; for(int i=s;i<=e;i++){ y=Math.min(y,Math.abs(x-a[i])); } return y; } static int llps(String str) { int n = str.length(); // calculcharAting size of string if (n < 2) return n; // if string is empty then size will be 0. // if n==1 then, answer will be 1(single // character will always palindrome) int maxLength = 1,start=0; int low, high; for (int i = 0; i < n; i++) { low = i - 1; high = i + 1; while ( high < n && str.charAt(high) == str.charAt(i)) //increment 'high' high++; while ( low >= 0 && str.charAt(low) == str.charAt(i)) // decrement 'low' low--; while (low >= 0 && high < n && str.charAt(low) == str.charAt(high) ){ low--; high++; } int length = high - low - 1; if (maxLength < length){ maxLength = length; start=low+1; } } return maxLength; } static boolean bf=false; public static void solve(String a,int pos,int n){ if(n==pos){ int x=llps(a); if(x<5){ bf=true; } return; } if(bf){ return; } if(a.charAt(pos)!='?'){ solve(a,pos+1,n); return;} String a1=a.substring(0,pos)+"0"+a.substring(pos+1,n); solve(a1,pos+1,n); String a2=a.substring(0,pos)+"1"+a.substring(pos+1,n); solve(a2,pos+1,n); } static long[][] mem; public static long solve(int[] a,int[] b,int l,int r){ if(l==r){ return 0; } if(mem[l][r]!=0){ return mem[l][r]; } long m=Long.MAX_VALUE; for(int i=l;i<=r;i++){ if(i==l){ long m1=b[i]+solve(a,b,l+1,r); m=Math.min(m,m1); } else if(i==r){ long m1=a[i]+solve(a,b,l,r-1); m=Math.min(m,m1); } else{ long m1=a[i]+b[i]+solve(a,b,l,i-1)+solve(a,b,i+1,r); m=Math.min(m,m1); } } return mem[l][r]=m; } public static long solve(long n,long c){ ArrayList<Long> r1=new ArrayList<>(); ArrayList<Long> r2=new ArrayList<>(); for(long i=1;i<Math.sqrt(n);i++){ if(n%i==0){ r1.add(i); r2.add(n/i); } } boolean b=false; for(int i=r2.size()-1;i>=0;i--){ r1.add(r2.get(i)); } //System.out.println(r1.size()+" "+n); for(int i=1;i<r1.size();i++){ long r=(long)Math.pow(r1.get(i),c); //System.out.println(r+" "+r1.get(i)+" "+n); long g1=gcd(r,n); long n1=(r/g1)*(n/g1); if(n1<n){ return solve(n1,c); } } return n; } public static boolean palindrome(String s){ int n=s.length(); for(int i=0;i<n/2;i++){ if(s.charAt(i)!=s.charAt(n-1-i)) return false; } return true; } static long countWays(int S[], int m, int n) { //Time complexity of this function: O(mn) //Space Complexity of this function: O(n) // table[i] will be storing the number of solutions // for value i. We need n+1 rows as the table is // constructed in bottom up manner using the base // case (n = 0) long[] table = new long[n+1]; // Initialize all table values as 0 Arrays.fill(table, 0); //O(n) // Base case (If given value is 0) table[0] = 1; // Pick all coins one by one and update the table[] // values after the index greater than or equal to // the value of the picked coin for (int i=0; i<m; i++) for (int j=S[i]; j<=n; j++) table[j] += table[j-S[i]]; return table[n]; } public static int combinationSum4(int[] nums, int target) { int[] comb = new int[target + 1]; comb[0] = 1; for (int i = 1; i < comb.length; i++) { for (int j = 0; j < nums.length; j++) { if (i - nums[j] >= 0) { comb[i] += comb[i - nums[j]]; } } } return comb[target]; } public static int count( int S[], int m, int n ) { // table[i] will be storing the number of solutions for // value i. We need n+1 rows as the table is constructed // in bottom up manner using the base case (n = 0) int table[]=new int[n+1]; // Base case (If given value is 0) table[0] = 1; // Pick all coins one by one and update the table[] values // after the index greater than or equal to the value of the // picked coin for(int i=0; i<m; i++) for(int j=S[i]; j<=n; j++) table[j] += table[j-S[i]]; return table[n]; } static long[][] m; public static void solve(int arr[],int n){ long d=1000000007; m=new long[40002][499]; for(int i=0;i<499;i++){ m[0][i]=1; } for(int i=1;i<40002;i++){ for(int j=1;j<499;j++){ if(arr[j-1]<=i){ m[i][j]=(m[i-arr[j-1]][j]+m[i][j-1])%d; } else m[i][j]=m[i][j-1]; } } } public static void main(String[] args) { //System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); // write your code here FastReader s = new FastReader(); //InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); // Scanner s=new Scanner(System.in); //int t = s.nextInt(); //while(t-->0) { int n=s.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) a[i] = s.nextInt(); int r=Integer.MAX_VALUE; int s1=Math.min(a[0],a[1]); int s2=Math.max(a[0],a[1]); for(int i=2;i<n;i++){ if(a[i]<=s1){ s2=s1; s1=a[i]; } else if(a[i]<s2){ s2=a[i]; } } int t1=0; t1+=s1/2; if(s1%2!=0) t1++; t1+=s2/2; if(s2%2==1) t1++; r=Math.min(t1,r); for(int i=0;i<n-1;i++){ int g=Math.max(a[i],a[i+1]); int f=Math.min(a[i],a[i+1]); if((int)(g+1)/2<=f){ int l=a[i]+a[i+1]; int h=l/3; if(l%3!=0) h++; r=Math.min(h,r);} else{ //out.println("*&*"); r=Math.min((g+1)/2,r); } } for(int i=1;i<n-1;i++){ int l=a[i-1]; int k=a[i+1]; int h=Math.min(k,l); int d=Math.abs(k-l); h+=d/2; if(d%2==1) h++; r=Math.min(r,h); } out.println(r); //} out.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
2209a06b8a81afb7aedd7f95d1a1175c
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 App{ 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 res = Integer.MAX_VALUE; for(int i = 0; i < n - 1; i++){ int a,b; int x1 = Integer.MAX_VALUE; int x2 = Integer.MAX_VALUE; a = Math.min(arr[i],arr[i + 1]); b = Math.max(arr[i],arr[i + 1]); if(a > b/2){ x1 = (int)Math.ceil((double)(2*a - b)/(double)3*2) + b - a; } else{ x2 = (int)Math.ceil((double)b/(double)2); } res = Math.min(res, x1); res = Math.min(res, x2); } for(int i = 0; i < n - 2; i++){ int x; if(arr[i] < arr[i + 2]){ x = arr[i] + (arr[i + 2] - arr[i] + 1)/2; } else{ x = arr[i + 2] + (arr[i] - arr[i + 2] + 1)/2; } res = Math.min(res, x); } Arrays.sort(arr); res = Math.min(res,(int)Math.ceil((double)arr[0]/(double)2) + (int)Math.ceil((double)arr[1]/(double)2)); System.out.println(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 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
865cffa35e191ec550d64f2ff2a6b054
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
f961cb9a1467f5620bfd746799ca1bf0
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 c1674; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; // // Codeforces Round #786 (Div. 3) 2022-05-02 07:35 // E. Breaking the Wall // https://codeforces.com/contest/1674/problem/E // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // 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, . // // Monocarp wants to calculate the minimum number of onager shots needed to break at least two // sections. Help him! // // Input // // The first line contains one integer n (2 <= n <= 2 * 10^5) -- the number of sections. // // The second line contains the sequence of integers a_1, a_2, ..., a_n (1 <= a_i <= 10^6), where // a_i is the initial durability of the i-th section. // // Output // // Print one integer -- the minimum number of onager shots needed to break at least two sections of // the wall. // // Example /* input: 5 20 10 30 10 20 output: 10 input: 3 1 8 1 output: 1 input: 6 7 6 6 8 5 8 output: 4 input: 6 14 3 8 10 15 4 output: 4 input: 4 1 100 100 1 output: 2 input: 3 40 10 10 output: 7 */ // Note // // In 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. // public class C1674E { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int[] a) { int n = a.length; // check 11, 12, 21, 1*1 for (int i = 0; i < n - 1; i++) { if (a[i] == 1) { if (a[i+1] <= 2 || (i+2 < n && a[i+2] == 1)) { return 1; } } else if (a[i] == 2 && a[i+1] == 1) { return 1; } } // option 1: shoot at a single section x to break two in (x-1,x,x+1) int ans = a[0] + a[1]; for (int i = 0; i < n; i++) { int v = 0; int w = (a[i] + 1) / 2; if (i == 0) { v = max(w, a[1]); } else if (i == n - 1) { v = max(w, a[n-2]); } else { v = min(max(a[i-1], a[i+1]), max(a[i-1], w), max(w, a[i+1])); } ans = Math.min(ans, v); } // option 2: shoot at two consecutive sections to break these two sections for (int i = 0; i < n-1; i++) { // a b // ^ ^ // x times y times // we want the minimal (x+y) to have 2x+y >= a and x + 2y >= b // we have x + y >= (a+b)/3 int v = 0; if (2 * a[i] <= a[i+1]) { // x <= 0 v = (a[i+1] + 1) / 2; } else if (2 * a[i+1] <= a[i]) { v = (a[i] + 1) / 2; } else { v = (a[i] + a[i+1] + 2) / 3; /* a\b 21 22 23 12 11 12 12 13 12 12 12 14 12 12 13 */ } ans = Math.min(ans, v); } if (n >= 3) { // option 3a: shoot at i and i+1 to break i and i+2 for (int i = 0; i < n-2; i++) { // * * * // ^ ^ // i i+2 if (a[i+1] > 2 * a[i+2]) { int y = a[i+2]; if (a[i] <= a[i+2]) { ans = Math.min(ans, y); } else { int v = (a[i] + a[i+2] + 1) / 2; ans = Math.min(ans, v); } } } // option 3b: shoot at i and i-1 to break i and i-2 for (int i = 2; i < n; i++) { // * * * // ^ ^ // i-2 i if (a[i-1] > 2 * a[i-2]) { int y = a[i-2]; if (a[i] <= a[i-2]) { ans = Math.min(ans, y); } else { int v = (a[i] + a[i-2] + 1) / 2; ans = Math.min(ans, v); } } } // option 3c: shoot at two separate sections int x = Math.min(a[0], a[1]); int y = Math.max(a[0], a[1]); for (int i = 2; i < n; i++) { if (a[i] <= x) { y = x; x = a[i]; } else if (a[i] < y) { y = a[i]; } } ans = Math.min(ans, (x+1)/2 + (y+1)/2); } return ans; } static int max(int x, int y) { return Math.max(x, y); } static int min(int x, int y, int z) { return Math.min(Math.min(x, y), z); } static void test(int exp, int[] a) { int ans = solve(a); System.out.format("%s => %d%s\n", Arrays.toString(a), ans, ans == exp ? "":" Expected " + exp); myAssert(ans == exp); } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); test(10, new int[] {20,10,30,10,20}); test(1, new int[] {1,8,1}); test(4, new int[] {7,6,6,8,5,8}); test(4, new int[] {14,3,8,10,15,4}); test(2, new int[] {1,100,100,1}); test(7, new int[] {40,10,10}); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int ans = solve(a); System.out.println(ans); } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 500) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["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
cf5b99eaa130db42c0837e3b5ff3a8de
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 Solution { static Reader input = new Reader(); public static void main(String[] args) throws IOException { int n = input.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; ++i) a[i] = input.nextInt(); int min1 = -1, min2 = -1, min = Integer.MAX_VALUE; for(int i = 0; i < n; ++i) { if(min > a[i]) { min = a[i]; min1 = i; } } min = Integer.MAX_VALUE; for(int i = 0; i < n; ++i) { if(i != min1) { if(min > a[i]) { min = a[i]; min2 = i; } } } int answer = ((a[min1]/2)+(a[min1]%2)) + ((a[min2]/2)+(a[min2]%2)); for(int i = 1; i < n-1; ++i) { int minV = Math.min(a[i+1], a[i-1]); int maxV = Math.max(a[i+1], a[i-1]); answer = Math.min(answer, minV+((maxV-minV)/2)+((maxV-minV)%2)); } for(int i = 1; i < n; ++i) { int minV = Math.min(a[i], a[i-1]); int maxV = Math.max(a[i], a[i-1]); int diff = maxV-minV; if(diff > minV) { answer = Math.min(answer, (maxV/2)+(maxV%2)); } else { minV -= diff; int steps = diff+(minV/3)*2+(minV%3); answer = Math.min(answer, steps); } } System.out.print(answer); } static class Reader { BufferedReader bufferedReader; StringTokenizer string; public Reader() { InputStreamReader inr = new InputStreamReader(System.in); bufferedReader = new BufferedReader(inr); } public String next() throws IOException { while(string == null || ! string.hasMoreElements()) { string = new StringTokenizer(bufferedReader.readLine()); } return string.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return bufferedReader.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 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
f98508b290e8eb2dd5a28b5474c0bc40
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 Linova { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(st.nextToken()); } int ans = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) { int x = arr[i]; int y = arr[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++) { ans = Math.min(ans, (arr[i] + arr[i + 2] + 1) / 2); } Arrays.sort(arr); ans = Math.min(ans, (arr[1] + 1) / 2 + (arr[0] + 1) / 2); out.println(ans); out.close(); f.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