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
c2e97ad40a11b823639bec7961041c8e
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); int t =1; while ( t > 0 ){ int n = Reader.nextInt(); int array[] = new int[1000001]; int i = 0; while ( i < n){ array[Reader.nextInt()] = 1; i++; } i = 1; while ( i <= 1000000){ if ( array[i] == 0){ boolean found = false; int j = i+i; long g = -1; while ( j <= 1000000){ if ( array[j] == 1){ if ( found){ g = gcd(g,j); //System.out.println(g+" "+i); } else{ found = true; g = j; //System.out.println(g+" "+i); } } j+=i; } if ( g == i){ array[i] = 1; } } i++; } int size = 0; i = 1; while ( i <= 1000000){ if (array[i]==1){ size++; } i++; } int ans = size-n; output.write(ans+"\n"); t--; } output.flush(); } private static int bs(int low,int high,ArrayList<Integer> array,int find){ if ( low <= high ){ int mid = low + (high-low)/2; if ( array.get(mid) > find){ high = mid -1; return bs(low,high,array,find); } else if ( array.get(mid) < find){ low = mid+1; return bs(low,high,array,find); } return mid; } return -1; } private static long max(long a, long b) { return Math.max(a,b); } private static long min(long a,long b){ return Math.min(a,b); } public static long modularExponentiation(long a,long b,long mod){ if ( b == 1){ return a; } else{ long ans = modularExponentiation(a,b/2,mod)%mod; if ( b%2 == 1){ return (a*((ans*ans)%mod))%mod; } return ((ans*ans)%mod); } } public static long sum(long n){ return (n*(n+1))/2; } public static long abs(long a){ return a < 0 ? (-1*a) : a; } public static long gcd(long a,long b){ if ( a == 0){ return b; } else{ return gcd(b%a,a); } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next()); } } /* class NComparator implements Comparator<Node>{ @Override public int compare(Node o1, Node o2) { if ( o2.position > o1.position){ return 1; } else if ( o2.position < o1.position){ return -1; } else{ if ( o2.time < o1.time){ return 1; } else if ( o2.time > o2.time){ return -1; } else{ return 0; } } } } */ class DComparator implements Comparator<Long>{ @Override public int compare(Long o1, Long o2) { if ( o2 > o1){ return 1; } else if ( o2 < o1){ return -1; } else{ return 0; } } } class Node{ long u; long v; long w; Node(long U,long V, long W ){ u = U; v = V; w = W; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
f0e90a08035a535860bd3cca1993966f
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
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 java.util.*; import java.lang.*; import java.io.*; public class Solution { static int MAX = 1000005; static int[] arr = new int[MAX]; 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 = 0; t < test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); for (int i = 0; i < n; i++) { int value = sc.nextInt(); arr[value]++; } int operations = 0; for (int i = MAX - 1; i >= 1; i--) { if (arr[i] > 0) { continue; } // we want to find two values in the array whose gcd is i, or we can divide all multiples of i by i, and now we can find two numbers whose gcd is 1. List<Integer> multiples = new ArrayList<>(); for (int j = 2 * i; j < MAX; j += i) { if (arr[j] > 0) { multiples.add(j / i); } } if (multiples.size() <= 1) { continue; } int m = multiples.size(), a = multiples.get(0); for (int j = 1; j < m; j++) { int b = multiples.get(j); if (gcd(a, b) == 1) { operations++; arr[i] = 1; break; } } } out.println(operations); } private static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } 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 end) { end.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 end) { end.printStackTrace(); } return str; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
58150d31c338038db7fd13e041c2cb81
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
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.*; public class D{ 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(); out = new PrintWriter(new BufferedOutputStream(System.out)); //code below int n = sc.nextInt(); int[] arr = new int[n]; for(int i= 0; i < n; i++){ arr[i] = sc.nextInt(); } //setting present if the value is there or not int[] present = new int[1000_001]; for(int i = 0; i < n; i++){ present[arr[i]] = 1; } //so now counting how many gcd's could be there int count = 0; for(int i = 1; i <= 1000_000; i++){ int curr = i; //check if the gcd of all mulitple of those is int gcd = -1; for(int j = 1; j*curr < 1000_001; j++){ if(present[j*curr] == 1){ if(gcd == -1) gcd = j*curr; gcd = gcd(gcd, j*curr); } } if(gcd == i) count++; } out.println(count - n); out.close(); } //Updation Required //Fenwick Tree (customisable) //Segment Tree (customisable) //-----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 //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); } } //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){ 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{ public long[] arr; public long[] tree; public long[] lazy; segmentTree(long[] array){ int n = array.length; arr = new long[n]; for(int i= 0; i < n; i++) arr[i] = array[i]; tree = new long[4*n + 1]; lazy = new long[4*n + 1]; } public void build(int[]arr, int s, int e, int[] tree, int index){ if(s == e){ tree[index] = arr[s]; return; } //otherwise divide in two parts and fill both sides simply int mid = (s+e)/2; build(arr, s, mid, tree, 2*index); build(arr, mid+1, e, tree, 2*index+1); //who will build the current position dude tree[index] = Math.min(tree[2*index], tree[2*index+1]); } public int query(int sr, int er, int sc, int ec, int index, int[] tree){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(sc != ec){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap if(sr > ec || sc > er) return Integer.MAX_VALUE; //found the index baby if(sr <= sc && ec <= er) return tree[index]; //finding the index on both sides hehehehhe int mid = (sc + ec)/2; int left = query(sr, er, sc, mid, 2*index, tree); int right = query(sr, er, mid+1, ec, 2*index + 1, tree); return Integer.min(left, right); } //now we will do point update implementation //it should be simple then we expected for sure public void update(int index, int indexr, int increment, int[] tree, int s, int e){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] = lazy[index]; lazy[2*index] = lazy[index]; } lazy[index] = 0; } //no overlap if(indexr < s || indexr > e) return; //found the required index if(s == e){ tree[index] += increment; return; } //search for the index on both sides int mid = (s+e)/2; update(2*index, indexr, increment, tree, s, mid); update(2*index+1, indexr, increment, tree, mid+1, e); //now update the current range simply tree[index] = Math.min(tree[2*index+1], tree[2*index]); } public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){ //if not at all in the same range if(e < sr || er < s) return; //complete then also move forward if(s == e){ tree[index] += increment; return; } //otherwise move in both subparts int mid = (s+e)/2; rangeUpdate(tree, 2*index, s, mid, sr, er, increment); rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment); //update current range too na //i always forget this step for some reasons hehehe, idiot tree[index] = Math.min(tree[2*index], tree[2*index + 1]); } public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){ //update lazy values //resolve lazy value before going down if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap case if(sr > e || s > er) return; //complete overlap if(sr <= s && er >= e){ tree[index] += increment; if(s != e){ lazy[2*index+1] += increment; lazy[2*index] += increment; } return; } //otherwise go on both left and right side and do your shit int mid = (s + e)/2; rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment); rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment); tree[index] = Math.min(tree[2*index+1], tree[2*index]); 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; } //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; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } //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; } // ll *fact = new ll[2 * n + 1]; // ll *ifact = new ll[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (ll i = 1; i <= 2 * n; i++) // { // fact[i] = mod_mul(fact[i - 1], i, MOD1); // ifact[i] = mminvprime(fact[i], MOD1); // } //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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
ac4f8fbb56bbf7b8bc3de8459b88ce82
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class taskd { public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); taskd sol = new taskd(); sol.solve(in, out); out.flush(); } void solve(FastScanner in, PrintWriter out) { int n = in.nextInt(); int a[] = new int[n]; int cnt[] = new int[1_000_050]; int mx = 0; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); cnt[a[i]]++; mx = Math.max(mx, a[i]); } int ans = 0; for (int x = 1; x <= mx; x++) { if (cnt[x] > 0) { ans++; continue; } ArrayList<Integer> b = new ArrayList<>(); for (int j = x; j <= mx; j += x) { if (cnt[j] > 0) { b.add(j); } } if (!b.isEmpty()) { int g = b.get(0); for (int j : b) g = gcd(g, j); if (g == x) ans++; } } out.println(ans - n); } static int gcd(int a, int 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()); } long nextLong() { return Long.parseLong(next()); } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a71bb06d32cc16c76be9ac8587b6bd87
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class NotAdding { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String[] terms = br.readLine().split(" "); HashSet<Integer> set = new HashSet<>(); int largest = -1; for (String t: terms) { set.add(Integer.parseInt(t)); largest = Math.max(largest,Integer.parseInt(t)); } for (int i=largest-1;i>0;i--) { boolean found = false; int prev = -1; for (int j=2*i;j<=largest;j+=i) { if (set.contains(j)) { if (prev == -1) { prev = j; } else { if (gcd(prev,j) == i) { found=true; break; } } } } if (found) set.add(i); } System.out.println(set.size()-n); } public static int gcd(int x, int y) { while (y!=0) { int temp = x; x=y; y=temp%y; } return x; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
771c757636befedd66c7e74e17698004
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Main { static class Scanner { Scanner(InputStream in) { this.in = in; } InputStream in; byte[] bb = new byte[1 << 15]; int i, n; byte getc() { if (i == n) { i = n = 0; try { n = in.read(bb); } catch (IOException e) {} } return i < n ? bb[i++] : 0; } int nextInt() { byte c = 0; while (c <= ' ') c = getc(); int a = 0; while (c > ' ') { a = a * 10 + c - '0'; c = getc(); } return a; } } private static int GCD(int a, int b) { if (a < b) return GCD(b, a); if (b == 0) return a; return GCD(b, a % b); } public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int N = in.nextInt(); int MAXA = 1000000; boolean[] present = new boolean[MAXA+1]; for (int i=1; i<=N; i++) { present[in.nextInt()] = true; } int count = 0; for (int i=1; i<=MAXA; i++) { if (present[i]) continue; int gcd = 0; for (int j=i*2; j<=MAXA; j+=i) { if (present[j]) gcd = GCD(gcd, j); } if (gcd == i) count++; } out.write(count + "\n"); out.close(); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
d055472cfadba1131bee3aa3f9d706ff
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Main { static final int MAX = (int) 1e6; public static int gcd(int a, int b) { while (a % b != 0) { int temp = b; b = a % b; a = temp; } return b; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int length = Integer.parseInt(br.readLine()); boolean[] array = new boolean[MAX + 1]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < length; i++) { array[Integer.parseInt(st.nextToken())] = true; } int ret = 0; for (int i = MAX; i > 0; i--) { if (!array[i] && 3 * i <= MAX) { int gcd = 0; for (int j = 2 * i; j <= MAX; j += i) { if (array[j]) { if (gcd == 0) gcd = j; else gcd = gcd(j, gcd); } } if (gcd == i) { array[i] = true; ret++; } } } pw.println(ret); br.close(); pw.close(); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
d740028d553b7bcf51f510418ca94712
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
/* Rating: 1367 Date: 15-01-2022 Time: 22-41-15 Author: Kartik Papney Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/ Leetcode: https://leetcode.com/kartikpapney/ Codechef: https://www.codechef.com/users/kartikpapney */ import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class D_Not_Adding { public static void s() { int n = sc.nextInt(); int[] gcd = new int[1000001]; int[] arr = sc.readArray(n); boolean[] in = new boolean[1000001]; for(int val : arr) in[val] = true; int cnt = 0; for(int i=1; i<1000001; i++) { for(int j=i; j<1000001; j+=i) { if(in[j]) { gcd[i] = (int)Functions.gcd(gcd[i], j); } } cnt += (gcd[i] == i) ? 1: 0; } p.writeln(cnt-n); } public static void main(String[] args) { int t = 1; // t = sc.nextInt(); while (t-- != 0) { s(); } p.print(); } static final Integer MOD = (int) 1e9 + 7; static final FastReader sc = new FastReader(); static final Print p = new Print(); static class Functions { static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static void 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); } static int max(int[] a) { int max = Integer.MIN_VALUE; for (int val : a) max = Math.max(val, max); return max; } static int min(int[] a) { int min = Integer.MAX_VALUE; for (int val : a) min = Math.min(val, min); return min; } static long min(long[] a) { long min = Long.MAX_VALUE; for (long val : a) min = Math.min(val, min); return min; } static long max(long[] a) { long max = Long.MIN_VALUE; for (long val : a) max = Math.max(val, max); return max; } static long sum(long[] a) { long sum = 0; for (long val : a) sum += val; return sum; } static int sum(int[] a) { int sum = 0; for (int val : a) sum += val; return sum; } public static long mod_add(long a, long b) { return (a % MOD + b % MOD + MOD) % MOD; } public static long pow(long a, long b) { long res = 1; while (b > 0) { if ((b & 1) != 0) res = mod_mul(res, a); a = mod_mul(a, a); b >>= 1; } return res; } public static long mod_mul(long a, long b) { long res = 0; a %= MOD; while (b > 0) { if ((b & 1) > 0) { res = mod_add(res, a); } a = (2 * a) % MOD; b >>= 1; } return res; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long factorial(long n) { long res = 1; for (int i = 1; i <= n; i++) { res = (i % MOD * res % MOD) % MOD; } return res; } public static int count(int[] arr, int x) { int count = 0; for (int val : arr) if (val == x) count++; return count; } public static ArrayList<Integer> generatePrimes(int n) { boolean[] primes = new boolean[n]; for (int i = 2; i < primes.length; i++) primes[i] = true; for (int i = 2; i < primes.length; i++) { if (primes[i]) { for (int j = i * i; j < primes.length; j += i) { primes[j] = false; } } } ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < primes.length; i++) { if (primes[i]) arr.add(i); } return arr; } } static class Print { StringBuffer strb = new StringBuffer(); public void write(Object str) { strb.append(str); } public void writes(Object str) { char c = ' '; strb.append(str).append(c); } public void writeln(Object str) { char c = '\n'; strb.append(str).append(c); } public void writeln() { char c = '\n'; strb.append(c); } public void writes(int[] arr) { for (int val : arr) { write(val); write(' '); } } public void writes(long[] arr) { for (long val : arr) { write(val); write(' '); } } public void writeln(int[] arr) { for (int val : arr) { writeln(val); } } public void print() { System.out.print(strb); } public void println() { System.out.println(strb); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } double[] readArrayDouble(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } String nextLine() { String str = new String(); try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
1165d4f83461a51efae19e555625fc53
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main{ public static void main(String args[]){ InputReader in=new InputReader(System.in); TASK solver = new TASK(); int t=1; // t = in.nextInt(); for(int i=1;i<=t;i++) { solver.solve(in,i); } } static class TASK { static int mod = 1000000007; static void solve(InputReader in, int testNumber) { int a[] = new int[1000001]; int n = in.nextInt(); for(int i=0;i<n;i++) { a[in.nextInt()]++; } int ans=0; for(int i=1000000;i>0;i--) { long gcd=0; for(int j=i;j<=1000000;j+=i) { if(a[j]>0) gcd=Maths.gcd(gcd,j); } if(gcd==i) { a[i]++; ans++; } } System.out.println(ans-n); } } static class pair{ int x; int y; int z; pair(int x,int y,int z) { this.x=x; this.y=y; this.z=z; } } static class Maths { static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static long factorial(int n) { long fact = 1; for (int i = 1; i <= n; i++) { fact *= i; } return fact; } } 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 String nextLine() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { 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 readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
0f5a845193d0687ec8c78d7c0239d7b1
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
/** * Created by Himanshu **/ import java.util.*; import java.io.*; import java.math.*; public class D1627 { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Reader s = new Reader(); int n = s.i(); int [] arr = s.arr(n); boolean [] vis = new boolean[(int) (1e6 + 1)]; int max = 0; for (int i : arr) { vis[i] = true; max = Math.max(max,i); } int ans = 0; for (int i=1;i<=max;i++) { if (!vis[i]) { int gcd = 0; for (int j=i;j<=max;j+=i) { if (vis[j]) { gcd = gcd(gcd,j); } } if (gcd == i) { vis[i] = true; ans ++; } } } out.println(ans); out.flush(); } public static void shuffle(long[] arr) { int n = arr.length; Random rand = new Random(); for (int i = 0; i < n; i++) { long temp = arr[i]; int randomPos = i + rand.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = temp; } } private static long phi(long n) { long result = n; for (long i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } } if (n > 1) result -= result / n; return result; } private static int gcd(int a, int b) { if(b == 0) return a; return gcd(b,a%b); } public static long nCr(long[] fact, long[] inv, int n, int r, long mod) { if (n < r) return 0; return ((fact[n] * inv[n - r]) % mod * inv[r]) % mod; } private static void factorials(long[] fact, long[] inv, long mod, int n) { fact[0] = 1; inv[0] = 1; for (int i = 1; i <= n; ++i) { fact[i] = (fact[i - 1] * i) % mod; inv[i] = power(fact[i], mod - 2, mod); } } private static long power(long a, long n, long p) { long result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a) % p; n /= 2; } else { result = (result * a) % p; n--; } } return result; } private static long power(long a, long n) { long result = 1; while (n > 0) { if (n % 2 == 0) { a = (a * a); n /= 2; } else { result = (result * a); n--; } } return result; } private static long query(long[] tree, int in, int start, int end, int l, int r) { if (start >= l && r >= end) return tree[in]; if (end < l || start > r) return 0; int mid = (start + end) / 2; long x = query(tree, 2 * in, start, mid, l, r); long y = query(tree, 2 * in + 1, mid + 1, end, l, r); return x + y; } private static void update(int[] arr, long[] tree, int in, int start, int end, int idx, int val) { if (start == end) { tree[in] = val; arr[idx] = val; return; } int mid = (start + end) / 2; if (idx > mid) update(arr, tree, 2 * in + 1, mid + 1, end, idx, val); else update(arr, tree, 2 * in, start, mid, idx, val); tree[in] = tree[2 * in] + tree[2 * in + 1]; } private static void build(int[] arr, long[] tree, int in, int start, int end) { if (start == end) { tree[in] = arr[start]; return; } int mid = (start + end) / 2; build(arr, tree, 2 * in, start, mid); build(arr, tree, 2 * in + 1, mid + 1, end); tree[in] = (tree[2 * in + 1] + tree[2 * in]); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar, numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String s() { 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 l() { 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 i() { 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 double d() throws IOException { return Double.parseDouble(s()); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = i(); } return ret; } public long[] arrLong(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = l(); } return ret; } } // static class pairLong implements Comparator<pairLong> { // long first, second; // // pairLong() { // } // // pairLong(long first, long second) { // this.first = first; // this.second = second; // } // // @Override // public int compare(pairLong p1, pairLong p2) { // if (p1.first == p2.first) { // if(p1.second > p2.second) return 1; // else return -1; // } // if(p1.first > p2.first) return 1; // else return -1; // } // } // static class pair implements Comparator<pair> { // int first, second; // // pair() { // } // // pair(int first, int second) { // this.first = first; // this.second = second; // } // // @Override // public int compare(pair p1, pair p2) { // if (p1.first == p2.first) return p1.second - p2.second; // return p1.first - p2.first; // } // } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
8da19c2d783ed4b99263013dd21d435d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class D { public static final int MAX_A = 1000000; public static void main(String[] args) { var io = new Kattio(System.in, System.out); solve(io); io.close(); } public static void solve(Kattio io) { int n = io.nextInt(); boolean[] inArray = new boolean[MAX_A + 1]; for (int i = 0; i < n; i++) { int a = io.nextInt(); inArray[a] = true; } int count = 0; for (int i = MAX_A; i > 0; i--) { int g = 0; for (int j = i; j <= MAX_A; j += i) { if (inArray[j]) { g = gcd(g, j); } } if (i == g) { inArray[i] = true; count++; } } io.println(count - n); } public static int gcd(int x, int y) { int temp; while (y > 0) { x %= y; temp = x; x = y; y = temp; } return x; } } // modified from https://github.com/Kattis/kattio/blob/master/Kattio.java class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public String next() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
0b7e94a2c2245d373c2bd92ab3577867
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class new1{ static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader s = new FastReader(); int t = 1;//s.nextInt(); for(int z = 0; z < t; z++) { int n = s.nextInt(); int n1 = 1000005; int[] arr = new int[n1]; for(int i = 0; i < n; i++) { int val = s.nextInt(); arr[val] = 1; } int[] vis= new int[n1]; int ans = 0; for(int i = n1 - 1; i >= 1; i--) { if(arr[i] == 1) continue; int c = 0; int gcd = -1; for(int j = i + i; j < n1; j = j + i) { if(arr[j] == 1) { if(c == 0) gcd = j; else gcd = gcd(gcd, j); c++; } } if(c >= 2 && gcd == i) { ans++; //System.out.println(i + "r"); arr[i] = 1 ; vis[i] = 1; } } System.out.println(ans); } output.flush(); } } 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(); } public 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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
cd140341949da50ff2f4de96026a22c2
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.TreeSet; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; import java.util.Random; import java.io.FileWriter; import java.io.PrintWriter; /* Solution Created: 18:29:32 15/01/2022 Custom Competitive programming helper. */ public class Main { //78498 public static void solve1() { int n = in.nextInt(); HashSet<Integer> have = new HashSet<>(); PriorityQueue<Integer> p = new PriorityQueue<>(); for(int i = 0; i<n; i++) { int v = in.nextInt(); p.add(v); have.add(v); } int ans = 0; while(p.size()>1) { int f = p.poll(), s = p.poll(); int gcd = Util.gcd(f, s); if(!have.contains(gcd)) { ans++; have.add(gcd); p.add(gcd); } f/=gcd; s/=gcd; } out.println(ans); } public static void solve() { int n = in.nextInt(); int mx = 1000000; int ans = 0; boolean[] dp = new boolean[mx+1]; for(int i = 0; i<n; i++) dp[in.nextInt()] = true; for(int i = mx; i>=1; i--) { if(dp[i]) continue; int gcd = 0; for(int mul = i*2; mul<=mx && !dp[i]; mul+=i) { if(!dp[mul]) continue; int left = mul/i; gcd = Util.gcd(left, gcd); if(gcd == 1) { dp[i] = true; ans++; } } } out.println(ans); } public static void main(String[] args) { in = new Reader(); out = new Writer(); int t = 1; while(t-->0) solve(); out.exit(); } static Reader in; static Writer out; static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String f){ try { this.br = new BufferedReader(new FileReader(f)); } catch (IOException e) { e.printStackTrace(); } } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nd(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[] nca() { return next().toCharArray(); } public String[] ns(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { ensureNext(); return Integer.parseInt(st.nextToken()); } public double nextDouble() { ensureNext(); return Double.parseDouble(st.nextToken()); } public Long nextLong() { ensureNext(); return Long.parseLong(st.nextToken()); } public String next() { ensureNext(); return st.nextToken(); } public String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureNext() { if (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } } } static class Util{ private static Random random = new Random(); static long[] fact; public static void initFactorial(int n, long mod) { fact = new long[n+1]; fact[0] = 1; for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod; } public static long modInverse(long a, long MOD) { long[] gcdE = gcdExtended(a, MOD); if (gcdE[0] != 1) return -1; // Inverted doesn't exist long x = gcdE[1]; return (x % MOD + MOD) % MOD; } public static long[] gcdExtended(long p, long q) { if (q == 0) return new long[] { p, 1, 0 }; long[] vals = gcdExtended(q, p % q); long tmp = vals[2]; vals[2] = vals[1] - (p / q) * vals[2]; vals[1] = tmp; return vals; } public static long nCr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nCr(int n, int r) { return (fact[n]/fact[r])/fact[n-r]; } public static long nPr(int n, int r, long MOD) { if (r == 0) return 1; return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD; } public static long nPr(int n, int r) { return fact[n]/fact[n-r]; } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } static long pow(long x, long pow, long mod){ long res = 1; x = x % mod; if (x == 0) return 0; while (pow > 0){ if ((pow & 1) != 0) res = (res * x) % mod; pow >>= 1; x = (x * x) % mod; } return res; } public static int gcd(int a, int b) { int tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static long gcd(long a, long b) { long tmp = 0; while(b != 0) { tmp = b; b = a%b; a = tmp; } return a; } public static int random(int min, int max) { return random.nextInt(max-min+1)+min; } public static void dbg(Object... o) { System.out.println(Arrays.deepToString(o)); } public static void reverse(int[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { int tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(int[] s) { reverse(s, 0, s.length-1); } public static void reverse(long[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { long tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(long[] s) { reverse(s, 0, s.length-1); } public static void reverse(float[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { float tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(float[] s) { reverse(s, 0, s.length-1); } public static void reverse(double[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { double tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(double[] s) { reverse(s, 0, s.length-1); } public static void reverse(char[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { char tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static void reverse(char[] s) { reverse(s, 0, s.length-1); } public static <T> void reverse(T[] s, int l , int r) { for(int i = l; i<=(l+r)/2; i++) { T tmp = s[i]; s[i] = s[r+l-i]; s[r+l-i] = tmp; } } public static <T> void reverse(T[] s) { reverse(s, 0, s.length-1); } public static void shuffle(int[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); int t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(long[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); long t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(float[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); float t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(double[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); double t = s[i]; s[i] = s[j]; s[j] = t; } } public static void shuffle(char[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); char t = s[i]; s[i] = s[j]; s[j] = t; } } public static <T> void shuffle(T[] s) { for (int i = 0; i < s.length; ++i) { int j = random.nextInt(i + 1); T t = s[i]; s[i] = s[j]; s[j] = t; } } public static void sortArray(int[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(long[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(float[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(double[] a) { shuffle(a); Arrays.sort(a); } public static void sortArray(char[] a) { shuffle(a); Arrays.sort(a); } public static <T extends Comparable<T>> void sortArray(T[] a) { Arrays.sort(a); } public static int[][] rotate90(int[][] a){ int n = a.length, m = a[0].length; int[][] ans = new int[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } public static char[][] rotate90(char[][] a){ int n = a.length, m = a[0].length; char[][] ans = new char[m][n]; for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j]; return ans; } } static class Writer { private PrintWriter pw; public Writer(){ pw = new PrintWriter(System.out); } public Writer(String f){ try { pw = new PrintWriter(new FileWriter(f)); } catch (IOException e) { e.printStackTrace(); } } public void yesNo(boolean condition) { println(condition?"YES":"NO"); } public void printArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(int[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void printArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); } public void printlnArray(long[] a) { for(int i = 0; i<a.length; i++) print(a[i]+" "); pw.println(); } public void print(Object o) { pw.print(o.toString()); } public void println(Object o) { pw.println(o.toString()); } public void println() { pw.println(); } public void flush() { pw.flush(); } public void exit() { pw.close(); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
16dae3e079ba31333b5531b3c23e9822
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main{ public static void process(int t)throws IOException { int n = ni(); int max = 1000000; boolean[]arr = new boolean[max + 1]; for(int i = 0;i<n;i++){ arr[ni()] = true; } for(int i=max;i>=1;i--){ int gcd = 0; for(int j = i;j<=max;j+=i){ if(arr[j]){ gcd = gcd(gcd, j); } } if(gcd == i){ arr[i] = true; } } int ans = 0; for(int i=1;i<=max;i++){ if(arr[i]) ans++; } pn(ans - n); } static long mod = 998244353l; static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { boolean oj = System.getProperty("ONLINE_JUDGE") != null; if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);} else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");} int t=1; // t=ni(); while(t-- > 0) {process(t);} out.flush();out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;} static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
95ed5281ef85fdf8582eb6cb07b1599d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.Scanner; public class D { public static void main(String[] args) { Scanner s = new Scanner(System.in); solve(s.nextInt(), s); } public static void solve(int n, Scanner s) { boolean[] inside = new boolean[1000001]; for (int i = 0; i < n; i++) { inside[s.nextInt()] = true; } int ggt; for (int i = 1; i <= 1000000; i++) { ggt = 0; for (int j = 2; j * i <= 1000000; j++) { if (inside[j * i]) ggt = ggt(ggt, j); } if (ggt == 1) inside[i] = true; } int c = 0; for (int i = 1; i <= 1000000; i++) { if (inside[i]) c++; } System.out.println(c - n); } public static int ggt(int a, int b) { if (a == 0) return b; if (a > b) return ggt(b, a); return ggt(b % a, a); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
67ccb9bb50c8db8cf2dcc1b494b44118
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
// \(≧▽≦)/ // Terminus // TODO : get good import java.io.*; import java.util.*; public class tank { static final FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int t = 1; while(t-- > 0) run_case(); out.close(); } static void run_case() { int n = fs.nextInt(), mx = (int) 1e6; int[] a = fs.readArray(n); boolean[] v = new boolean[mx + 1]; for(int i: a) v[i] = true; for (int i = 1; i <= mx; i++) { boolean fn = false; long val = 0; for(int j = i;j <= mx;j += i) { if(v[j]) { if(!fn) { val = j; fn = true; } else { val = gcd(val, j); } } } if(val == i) v[i] = true; } int ans = 0; for(boolean i: v) if(i) ans++; System.out.println(ans - n); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } 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(){ try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
1f4465d8aebd0b86e8593aced7835cee
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author null */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { private void solve(Input in, PrintWriter out) throws Exception { final int max = 1000010; boolean[] b = new boolean[max]; int n = in.readInt(); for (int i = 0; i < n; i++) { b[in.readInt()] = true; } int ans = 0; for (int x = max - 1; x > 0; x--) { if (!b[x]) { int g = 0; for (int i = 2; i * x < max; i++) { if (b[i * x]) { g = (int) GCD.gcd(g, i); } } if (g == 1) { b[x] = true; ans++; } } } out.println(ans); } public void solve(int testNumber, Input in, PrintWriter out) { try { solve(in, out); } catch (Exception e) { throw new RuntimeException(e); } } } static class Input { public final BufferedReader reader; private String line = ""; private int pos = 0; public Input(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private boolean isSpace(char ch) { return ch <= 32; } public String readWord() throws IOException { skip(); int start = pos; while (pos < line.length() && !isSpace(line.charAt(pos))) { pos++; } return line.substring(start, pos); } public int readInt() throws IOException { return Integer.parseInt(readWord()); } private void skip() throws IOException { while (true) { if (pos >= line.length()) { line = reader.readLine(); pos = 0; } while (pos < line.length() && isSpace(line.charAt(pos))) { pos++; } if (pos < line.length()) { return; } } } } static class GCD { public static long gcd(long a, long b) { if (a < 0) { return gcd(-a, b); } if (b < 0) { return gcd(a, -b); } if (a < b) { return gcd(b, a); } while (b > 0) { long c = a % b; a = b; b = c; } return a; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
fb63dca89fbba41fb2fe80ae1955afa6
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Array; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { public static void main(String[] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solve(in, out); out.close(); } static String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar) { factors[1]=1; int p; for(p = 2; p*p <=n; p++) { if(factors[p] == 0) { ar.add(p); factors[p]=p; for(int i = p*p; i <= n; i += p) if(factors[i]==0) factors[i] = p; } } for(;p<=n;p++){ if(factors[p] == 0) { factors[p] = p; ar.add(p); } } } static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static void sort2(char ar[]) { int n = ar.length; ArrayList<Character> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++) ar[i] = a.get(i); } static long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static class SegTree { long tree[]; long lz[]; long r; long combine(long a, long b){ return Math.min(a,b); } void build(long a[], int v, int tl, int tr) { if (tl == tr) { tree[v] = a[tl]; } else { int tm = (tl + tr) / 2; build(a, v*2, tl, tm); build(a, v*2+1, tm+1, tr); tree[v] = combine(tree[2*v], tree[2*v+1]); } } void pointUpdate(int v, int tl, int tr, int pos, long val) { if(tl>pos||tr<pos) return; if(tl==pos&&tr==pos){ tree[v] = val; return; } int tm = ((tl + tr) >> 1); pointUpdate(v*2, tl, tm, pos, val); pointUpdate(v*2+1, tm+1, tr, pos, val); tree[v] = combine(tree[2*v],tree[2*v+1]); } // void push(int v, int tl, int tr){ // if(tl==tr){ // lz[v] = 0; // return; // } // tree[2*v] += lz[v]; // tree[2*v+1] += lz[v]; // lz[2*v] += lz[v]; // lz[2*v+1] += lz[v]; // lz[v] = 0; // } // void rangeUpdate(int v, int tl, int tr, int l, int r, long val) { // if(tl>r||tr<l) // return; // push(v, tl, tr); // if(tl>=l&&tr<=r){ // tree[v] += val; // lz[v] += val; // return; // } // int tm = ((tl + tr) >> 1); // rangeUpdate(v*2, tl, tm, l, r, val); // rangeUpdate(v*2+1, tm+1, tr, l, r, val); // tree[v] = combine(tree[2*v],tree[2*v+1]); // } long get(int v, int tl, int tr, int l, int r, long val) { if(l>tr||r<tl||tree[v]>val){ return 0; } if (tl == tr) { tree[v] = Integer.MAX_VALUE; return 1; } int tm = ((tl + tr) >> 1); long al = get(2*v, tl, tm, l, r, val); long ar = get(2*v+1, tm+1, tr, l, r, val); tree[v] = combine(tree[2*v],tree[2*v+1]); return al+ar; } } static class BIT{ int n; long tree[]; long operate(long el, long val){ return el+val; } void update(int x, long val){ for(;x<n;x+=(x&(-x))){ tree[x] = operate(tree[x], val); } } long get(int x){ long sum = 0; for(;x>0;x-=(x&(-x))){ sum = operate(sum, tree[x]); } return sum; } } static int parent[]; static int rank[]; static long m = 0; static int find_set(int v) { if (v == parent[v]) return v; return find_set(parent[v]); } static void make_set(int v) { parent[v] = v; rank[v] = 1; } static void union_sets(int a, int b) { a = find_set(a); b = find_set(b); if (a != b) { if (rank[a] < rank[b]){ int tmp = a; a = b; b = tmp; } parent[b] = a; // if (rank[a] == rank[b]) // rank[a]++; rank[a] += rank[b]; max1 = Math.max(max1,rank[a]); } } static int parent1[]; static int rank1[]; static int find_set1(int v) { if (v == parent1[v]) return v; return find_set1(parent1[v]); } static void make_set1(int v) { parent1[v] = v; rank1[v] = 1; } static void union_sets1(int a, int b) { a = find_set1(a); b = find_set1(b); if (a != b) { if (rank1[a] < rank1[b]){ int tmp = a; a = b; b = tmp; } parent1[b] = a; // if (rank1[a] == rank1[b]) // rank1[a]++; rank1[a] += rank1[b]; } } static long max1 = 0; static int count = 0; static int count1 = 0; static boolean possible; public static void solve(InputReader sc, PrintWriter pw){ int i, j = 0; int t = 1; long mod = 1000000007; // int factors[] = new int[1000001]; // ArrayList<Integer> ar = new ArrayList<>(); // sieveOfEratosthenes(1000000, factors, ar); // HashSet<Integer> set = new HashSet<>(); // for(int x:ar){ // set.add(x); // } // int t = sc.nextInt(); u: while (t-- > 0) { int n = sc.nextInt(); int y[] = new int[1000001]; for(i=0;i<n;i++){ y[sc.nextInt()] = 1; } int x = 0; for(i=1000000;i>=1;i--){ if(y[i]==1) continue; int g = 0; for(j=i*2;j<=1000000;j+=i){ if(y[j]==0) continue; if(g==0) g = j; else g = (int)gcd(j,g); if(g==i) break; } if(g==i){ y[i] = 1; x++; } } pw.println(x); } } static void visit(int d, ArrayList<Integer> ar[], ArrayList<Integer> ar1[], int ans[], int par, int v){ if(ar[d].get(0)!=par){ ans[ar1[d].get(0)] = v; visit(ar[d].get(0), ar, ar1, ans, d, 5-v); return; } if(ar[d].size()==1) return; ans[ar1[d].get(1)] = v; visit(ar[d].get(1), ar, ar1, ans, d, 5-v); } static void KMPSearch(char pat[], char txt[], int pres[]){ int M = pat.length; int N = txt.length; int lps[] = new int[M]; int j = 0; computeLPSArray(pat, M, lps); int i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { pres[i-1] = 1; j = lps[j - 1]; } else if (i < N && pat[j] != txt[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } } static void computeLPSArray(char pat[], int M, int lps[]) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } static long[][] matrixMult(long a[][], long b[][], long mod){ int n = a.length; int m = a[0].length; int p = b[0].length; long c[][] = new long[n][p]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ for(int k=0;k<p;k++){ c[i][k] += a[i][j]*b[j][k]; c[i][k] %= mod; } } } return c; } static long[][] exp(long mat[][], long b, long mod){ if(b==0){ int n = mat.length; long res[][] = new long[n][n]; for(int i=0;i<n;i++){ res[i][i] = 1; } return res; } long half[][] = exp(mat, b/2, mod); long res[][] = matrixMult(half, half, mod); if(b%2==1){ res = matrixMult(res, mat, mod); } return res; } static void countPrimeFactors(int num, int a[], HashMap<Integer,Integer> pos){ for(int i=2;i*i<num;i++){ if(num%i==0){ int y = pos.get(i); while(num%i==0){ a[y]++; num/=i; } } } if(num>1){ int y = pos.get(num); a[y]++; } } static void assignAnc(ArrayList<Integer> ar[], int depth[], int sz[], int par[][] ,int curr, int parent, int d){ depth[curr] = d; sz[curr] = 1; par[curr][0] = parent; for(int v:ar[curr]){ if(parent==v) continue; assignAnc(ar, depth, sz, par, v, curr, d+1); sz[curr] += sz[v]; } } static int findLCA(int a, int b, int par[][], int depth[]){ if(depth[a]>depth[b]){ a = a^b; b = a^b; a = a^b; } int diff = depth[b] - depth[a]; for(int i=19;i>=0;i--){ if((diff&(1<<i))>0){ b = par[b][i]; } } if(a==b) return a; for(int i=19;i>=0;i--){ if(par[b][i]!=par[a][i]){ b = par[b][i]; a = par[a][i]; } } return par[a][0]; } static void formArrayForBinaryLifting(int n, int par[][]){ for(int j=1;j<20;j++){ for(int i=0;i<n;i++){ if(par[i][j-1]==-1) continue; par[i][j] = par[par[i][j-1]][j-1]; } } } static long lcm(int a, int b){ return a*b/gcd(a,b); } static class CustomPair { long a[]; CustomPair(long a[]) { this.a = a; } } static class Pair1 implements Comparable<Pair1> { long a; long b; Pair1(long a, long b) { this.a = a; this.b = b; } public int compareTo(Pair1 p) { if(a!=p.a) return (a<p.a?-1:1); return (b<p.b?-1:1); } } static class Pair implements Comparable<Pair> { int a; int b; int c; Pair(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair p) { if(b!=p.b) return (b-p.b); return (a-p.a); } } static class Pair2 implements Comparable<Pair2> { int a; int b; int c; Pair2(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public int compareTo(Pair2 p) { return a-p.a; } } static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 9992768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a888e068c21f7445b66b335c4ca73beb
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class CF1627D extends PrintWriter { CF1627D() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1627D o = new CF1627D(); o.main(); o.flush(); } static final int A = 1000000; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } void main() { int n = sc.nextInt(); boolean[] used = new boolean[A + 1]; for (int i = 0; i < n; i++) { int a = sc.nextInt(); used[a] = true; } int ans = 0; for (int a = A; a >= 1; a--) { if (used[a]) continue; int d = 0; for (int b = a; b <= A; b += a) if (used[b]) d = gcd(d, b); if (d == a) { used[a] = true; ans++; } } println(ans); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a0a13f4bfe6e9fdf74f3df10c91ff00b
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; int MAX = 1000000; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // npe, particularly in maps // // Big numbers arithmetic bugs: // int overflow // if (x : long) and (y : int), [y = x] does not compile, but [y += x] does // sorting, or taking max, after MOD void solve() throws IOException { int n = ri(); int[] a = ril(n); // 10^6 sort(a); boolean[] have = new boolean[MAX+1]; for (int ai : a) have[ai] = true; for (int i = 1; i <= MAX; i++) { if (have[i]) continue; int g = -1; for (int j = i + i; j <= MAX; j += i) { if (have[j]) { if (g == -1) g = j; else g = gcd(g, j); if (g == i) { have[i] = true; break; } } } } int count = 0; for (int i = 1; i <= MAX; i++) if (have[i]) count++; pw.println(count - n); } // IMPORTANT // DID YOU CHECK THE COMMON MISTAKES ABOVE? public static int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int c = br.read(); int x = 0; while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int c = br.read(); int x = 0; while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
b35a851731a103c891ff8771d5378fb3
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.math.*; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class Solution{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 10015; static final int MOD= 998244353; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } void sieveOfEratosthenes(int n) { // Create a boolean array // "prime[0..n]" and // initialize all entries // it as true. A value in // prime[i] will finally be // false if i is Not a // prime, else true. prime= new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int add(int a, int b){ a+=b; while(a>=MOD) a-=MOD; while(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; if(n<k) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } public int rand(){ int min=0, max= MAXN; int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); return random_int; } public void suffleSort(int[] arr){ shuffleArray(arr); Arrays.sort(arr); } public void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } InputReader in; PrintWriter out; Scanner sc= new Scanner(System.in); CustomFileReader cin; int[] xor= new int[3*100000+5]; int[] pow2= new int[1000000+1]; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; // sieve(); // pow2[0]=1; // for(int i=1;i<pow2.length;i++){ // pow2[i]= mul(pow2[i-1],2); // } int t=1; preprocess(); // int t=in.nextInt(); // int t= cin.nextIntArrLine()[0]; for(int i=1;i<=t;i++) solveD(i); } final double pi= Math.acos(-1); static Point base; void hack(int t){ for(int n=1;n<=1000000000;n++){ if(test3(n)!=test2(n)) System.out.println(n); } } int test1(int n){ return (int)Math.sqrt(n) + (int)Math.cbrt(n) - (int)Math.pow(n, (double)1.0/6); } int test2(int n){ int temp = (int)Math.cbrt(n); return (int)Math.sqrt(n) + temp - (int)(Math.sqrt(temp)); } int test3(int n) { Set<Integer> res= new HashSet<>(); for(int i=1;i*i<=n;i++) res.add(i*i); for(int i=1;i*i*i<=n;i++) res.add(i*i*i); return res.size(); } void solveA(int t) { String s= in.nextToken(); if (s.length() % 2 == 1) { out.println("NO"); return; } int m = s.length() / 2; boolean ok = (s.substring(0, m).equals(s.substring(m,s.length()))); if(ok) out.println("YES"); else out.println("NO"); } void solveB(int t) { int n= in.nextInt(); int temp = (int)Math.cbrt(n); out.println((int)Math.sqrt(n) + temp - (int)(Math.sqrt(temp))); } void solveC(int t){ char[] a= in.nextToken().toCharArray(), s= in.nextToken().toCharArray(); int i= s.length-1; String b=""; for(int j=a.length-1;j>=0;j--){ if(i<0){out.println(-1); return;} if(s[i]>=a[j]) b= ""+(s[i]-a[j])+b; else{ i--; if(i<0 || i+1>=s.length) {out.println(-1); return;} int num= Integer.parseInt(""+s[i]+s[i+1]); int num2= Integer.parseInt(""+a[j]); if(num-num2>9 || num-num2<0){out.println(-1); return;} b= ""+(num-num2)+b; // System.out.println(b); } i--; } while(i>=0) { b= ""+s[i]+b; i--; } if(b.length()==0) out.println(-1); else { out.println(Long.parseLong(b)); } } void solveD(int t) { int N= (int)1000000; boolean[] vis= new boolean[(int)1e6+1]; int n= in.nextInt(); for (int i = 0; i <n ;i++){ vis[in.nextInt()]= true; } int cnt = 0; for (int i = 1; i <= N; i++){ int g = 0; if(!vis[i]){ for (int j = i*2; j <= N; j+=i){ if (vis[j]){ g = (int)_gcd(j, g); if (g==i){ cnt++; break; } } } } } out.println(cnt); } void solveE(int t){ int n= in.nextInt(), m= in.nextInt(); int[] a= in.nextIntArr(n); List<Pair>[] s= new List[m]; int cnt=1; int size=0; for(int i=0;i<m;i++){ int k= in.nextInt(); size+=k; s[i]= new ArrayList<>(); for(int j=0;j<k;j++){ s[i].add(new Pair(in.nextInt(), cnt++)); } } suffleSort(a); List<Pair> average= new ArrayList<>(); for(int i=0;i<m;i++){ long sum=0; for(Pair p: s[i]){ sum += p.x; } average.add(new Pair((double)sum/s[i].size(), i)); } Collections.sort(average, Collections.reverseOrder()); List<Integer> p= new ArrayList<>(); for(int i=0;i<m;i++) p.add(a[n-1-i]); int[] larger= new int[m]; for(int i=0;i<m;i++){ larger[i]= search(p, average.get(i).x); } List<Integer> wrong= new ArrayList<>(); for(int i=0;i<m;i++){ if(average.get(i).x>p.get(i)) wrong.add(i); } int max= 0; for(int i: wrong){ max= Math.max(max, i-larger[i]); } int[] res= new int[size+1]; for(int i=0;i<m;i++){ int idx= average.get(i).y; for(int j=0;j<s[idx].size();j++){ double newAvg= (average.get(i).x*s[idx].size()-s[idx].get(j).x)/(s[idx].size()-1); int newIdx= search(p, newAvg); if(newIdx==-1){ res[s[idx].get(j).y]=0; continue; } if(max<=1 && newIdx >= wrong.get(wrong.size()-1)) res[s[idx].get(j).y]=1; else res[s[idx].get(j).y]=0; } } for(int i=1;i<=size;i++) out.print(i); out.println(); } private int search(List<Integer> values, double key){ int l=0, r= values.size()-1; int res=-1; while(l<=r){ int mid= (l+r)/2; if(values.get(mid)< key){ r=mid-1; } else{ l= mid+1; res= l; } } return res; } static class ListNode{ int idx=-1; ListNode next= null; public ListNode(int idx){ this.idx= idx; } } // static class Node implements Comparable<Node>{ // char op; // int s; // public Node (char op, int s) { // this.op= op; // this.s= s; // } // @Override // public int compareTo(Node o) { // if (this.s==o.s) return (int)(this.op-o.op); // return this.s-o.s; // } // } // private long distance(Point p1, Point p2) { // long x= p1.x-p2.x, y= p1.y-p2.y; // return x*x+y*y; // } // private boolean eqPoint(Point p1, Point p2){ // return p1.x==p2.x && p1.y==p2.y; // } // private double polarAngle(Point p1, Point p2) { // // p1 -> p2 // if (p1.x==p2.x) return pi/2; // else if (p1.y==p2.y){ // if(p1.x<p2.x) return 0; // else return pi; // } // else { // double y= (double)p2.y-(double)p1.y; // double x= (double)p2.x-(double)p1.x; // BigDecimal alpha1= new BigDecimal(y); // BigDecimal alpha2= new BigDecimal(x); // BigDecimal val= alpha1.divide(alpha2); // double angle= Math.atan(val.doubleValue()); // if (angle<0) angle+= pi; // out.println("angle: "+angle); // return angle; // } // } // private boolean isRightTurn(Point p1, Point p2, Point p3){ // Vector v1= new Vector(p1,p2), v2= new Vector(p1,p3); // if(crossProd(v1,v2)<0) return true; // else return false; // } // private long crossProd(Vector v1, Vector v2){ // //x1*y2-x2*y1 // return v1.x*v2.y - v2.x*v1.y; // } // static class PointAngle implements Comparable<PointAngle>{ // Point p; // double angle; // long dis; // public PointAngle(Point p, double angle, long dis) { // this.p= p; // this.angle= angle; // this.dis= dis; // } // @Override // public int compareTo(PointAngle o) { // double dif= this.angle-o.angle; // if (dif <0) return -1; // else if(dif >0) return 1; // else { // long dif2r= this.dis-o.dis; // long dif2l= o.dis-this.dis; // if (base.x < this.p.x) return intDif(dif2r); // else return intDif(dif2l); // } // } // private int intDif(long a){ // if (a>0) return 1; // else if(a<0) return -1; // else return 0; // } // } public long _gcd(long a, long b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public long _lcm(long a, long b){ return (a*b)/_gcd(a,b); } } // static class SEG { // Pair[] segtree; // public SEG(int n){ // segtree= new Pair[4*n]; // Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE)); // } // // void buildTree(int l, int r, int index) { // // if (l == r) { // // segtree[index].y = a[l]; // // return; // // } // // int mid = (l + r) / 2; // // buildTree(l, mid, 2 * index + 1); // // buildTree(mid + 1, r, 2 * index + 2); // // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y); // // } // void update(int l, int r, int index, int pos, Pair val) { // if (l == r) { // segtree[index] = val; // return; // } // int mid = (l + r) / 2; // if (pos <= mid) update(l, mid, 2 * index + 1, pos, val); // else update(mid + 1, r, 2 * index + 2, pos, val); // if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){ // segtree[index]= segtree[2 * index + 1]; // } // else { // segtree[index]= segtree[2 * index + 2]; // } // } // // Pair query(int l, int r, int from, int to, int index) { // // if (from <= l && r <= to) // // return segtree[index]; // // if (r < from | to < l) // // return 0; // // int mid = (l + r) / 2; // // Pair left= query(l, mid, from, to, 2 * index + 1); // // Pair right= query(mid + 1, r, from, to, 2 * index + 2); // // if(left.y < right.y) return left; // // else return right; // // } // } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.z-o.z; } } static class Point implements Comparable<Point>{ public double x; public long y; public Point(double x, long y){ this.x= x; this.y= y; } @Override public int compareTo(Point o) { if(this.y!=o.y) return (int)(this.y-o.y); return (int)(this.x-o.x); } } // static class Vector { // public long x; // public long y; // // p1 -> p2 // public Vector(Point p1, Point p2){ // this.x= p2.x-p1.x; // this.y= p2.y-p1.y; // } // } static class Pair implements Comparable<Pair>{ public double x; public int y; public Pair(double x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { if(this.x!=o.x) return (int)(this.x-o.x); return (int)(this.y-o.y); } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } static class CustomFileReader{ String path=""; Scanner sc; public CustomFileReader(String path){ this.path=path; try{ sc= new Scanner(new File(path)); } catch(Exception e){} } public String nextLine(){ return sc.nextLine(); } public int[] nextIntArrLine(){ String line= sc.nextLine(); String[] part= line.split("[\\s+]"); int[] res= new int[part.length]; for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]); return res; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 11
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
1548e76dbfbda557e9953e7d432db64a
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.util.function.*; import java.io.*; // you can compare with output.txt and expected out public class Round766D { MyPrintWriter out; MyScanner in; // final static long FIXED_RANDOM; // static { // FIXED_RANDOM = System.currentTimeMillis(); // } final static String IMPOSSIBLE = "IMPOSSIBLE"; final static String POSSIBLE = "POSSIBLE"; final static String YES = "YES"; final static String NO = "NO"; private void initIO(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))); Round766D sol = new Round766D(); sol.run(); } private void run() { boolean isDebug = false; boolean isFileIO = true; boolean hasMultipleTests = false; initIO(isFileIO); int t = hasMultipleTests? in.nextInt() : 1; for (int i = 1; i <= t; ++i) { if(isDebug){ out.printf("Test %d\n", i); } getInput(); solve(); printOutput(); } in.close(); out.close(); } // use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ... int n; int[] a; void getInput() { n = in.nextInt(); a = in.nextIntArray(n); } void printOutput() { out.printlnAns(ans); } int ans; void solve(){ // there is no reason not to add gcd when possible // 6 10 15 // -> 6 10 15 / 2 5 3 1 // if there is 2x, 2y // then gcd(2x, 2y) = 2z, keep repeating that, we get 2 // if there is only one multiple of 2, no way to get 2 as gcd // for each a[i], mark its divisor // px, py // p*gcd(x, y) --> can't make p final int MAX = 1_000_000; //final int MAX = 100; boolean[] exists = new boolean[MAX+1]; for(int i=0; i<n; i++) exists[a[i]] = true; ans = 0; for(int i=1; i<=MAX; i++) { if(!exists[i]) { int g = -1; for(int j=i; j<=MAX; j+=i) { if(exists[j]) { if(g == -1) { g = j; } else { g = gcd(g, j); } } } if(g == i) ans++; } } } static int gcd(int a, int b){ if(a < b){ int temp = b; b = a; a = temp; } // a > b while (b > 0) { int r = a % b; a = b; b = r; } return a; } static class Pair implements Comparable<Pair>{ final static long FIXED_RANDOM = System.currentTimeMillis(); int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } @Override public int hashCode() { // http://xorshift.di.unimi.it/splitmix64.c long x = first; x <<= 32; x += second; x += FIXED_RANDOM; x += 0x9e3779b97f4a7c15l; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l; x = (x ^ (x >> 27)) * 0x94d049bb133111ebl; return (int)(x ^ (x >> 31)); } @Override public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; Pair other = (Pair) obj; return first == other.first && second == other.second; } @Override public String toString() { return "[" + first + "," + second + "]"; } @Override public int compareTo(Pair o) { int cmp = Integer.compare(first, o.first); return cmp != 0? cmp: Integer.compare(second, o.second); } } 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[][] nextMatrix(int n, int m) { return nextMatrix(n, m, 0); } int[][] nextMatrix(int n, int m, int offset) { int[][] mat = new int[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { mat[i][j] = nextInt()+offset; } } return mat; } 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; } String[] nextStringArray(int len) { String[] s = new String[len]; for(int i=0; i<len; i++) s[i] = next(); return s; } } public static class MyPrintWriter extends PrintWriter{ public MyPrintWriter(OutputStream os) { super(os); } public void printlnAns(long ans) { println(ans); } public void printlnAns(int ans) { println(ans); } public void printlnAns(boolean ans) { if(ans) println(YES); else println(NO); } public void printAns(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 printlnAns(long[] arr){ printAns(arr); println(); } public void printAns(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 printlnAns(int[] arr){ printAns(arr); println(); } public <T> void printAns(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 printlnAns(ArrayList<T> arr){ printAns(arr); println(); } public void printAns(int[] arr, int add){ if(arr != null && arr.length > 0){ print(arr[0]+add); for(int i=1; i<arr.length; i++){ print(" "); print(arr[i]+add); } } } public void printlnAns(int[] arr, int add){ printAns(arr, add); println(); } public void printAns(ArrayList<Integer> arr, int add) { if(arr != null && arr.size() > 0){ print(arr.get(0)+add); for(int i=1; i<arr.size(); i++){ print(" "); print(arr.get(i)+add); } } } public void printlnAns(ArrayList<Integer> arr, int add){ printAns(arr, add); println(); } public void printlnAnsSplit(long[] 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 void printlnAnsSplit(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 printlnAnsSplit(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 void permutateAndSort(long[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); long temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } static private void permutateAndSort(int[] a) { int n = a.length; Random R = new Random(System.currentTimeMillis()); for(int i=0; i<n; i++) { int t = R.nextInt(n-i); int temp = a[n-1-i]; a[n-1-i] = a[t]; a[t] = temp; } Arrays.sort(a); } 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]]; } for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; outNeighbors[u][--outDegree[u]] = v; inNeighbors[v][--inDegree[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]]; for(int i=0; i<e.length; i++) { int u = e[i][0]; int v = e[i][1]; neighbors[u][--degree[u]] = v; neighbors[v][--degree[v]] = u; } return neighbors; } static private void drawGraph(int[][] e) { makeDotUndirected(e); try { final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot") .redirectOutput(new File("graph.png")) .start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } 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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 17
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
bb41b7058e30d223c499162f3062687b
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (1e9 + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static long dp[][][]; static double cmp = 1e-7; static final double pi = 3.14159265359; static int[] ans; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter(f)); int test = 1;//input.nextInt(); loop: for (int co = 1; co <= test; co++) { int n = input.nextInt(); int res = 0; int fre[] = new int[(int) 1e6 + 9]; for (int i = 0; i < n; i++) { fre[input.nextInt()]++; } for (int i = 1; i <= 1e6; i++) { long gcd = 0; if (fre[i]==1) { continue; } for (int j = i + i; j <= 1e6; j += i) { if (fre[j]==1) { gcd = GCD(j, gcd); } } if (gcd == i) { res++; } } log.write(res + "\n"); } log.flush(); } static void dfs(int node, ArrayList<Integer> g[], boolean vi[], boolean ca, TreeMap<pair, Integer> edges) { vi[node] = true; for (Integer ch : g[node]) { if (!vi[ch]) { if (ca) { ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 2; } else { ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 5; } dfs(ch, g, vi, !ca, edges); ca = !ca; } } } static long f(long x) { return (long) ((x * (x + 1) / 2) % mod); } static long Sub(long x, long y) { long z = x - y; if (z < 0) { z += mod; } return z; } static long add(long a, long b) { a += b; if (a >= mod) { a -= mod; } return a; } static long mul(long a, long b) { return (long) ((long) a * b % mod); } static long powlog(long base, long power) { if (power == 0) { return 1; } long x = powlog(base, power / 2); x = mul(x, x); if ((power & 1) == 1) { x = mul(x, base); } return x; } static long modinv(long x) { return fast_pow(x, mod - 2, mod); } static long Div(long x, long y) { return mul(x, modinv(y)); } static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) { vi[r][c] = true; for (int i = 0; i < 4; i++) { int nr = grid[0][i] + r; int nc = grid[1][i] + c; if (isValid(nr, nc, a.length, a[0].length)) { if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) { floodFill(nr, nc, a, vi, w, d); } } } } static boolean isdigit(char ch) { return ch >= '0' && ch <= '9'; } static boolean lochar(char ch) { return ch >= 'a' && ch <= 'z'; } static boolean cachar(char ch) { return ch >= 'A' && ch <= 'Z'; } static class Pa { long x; long y; public Pa(long x, long y) { this.x = x; this.y = y; } } static long sqrt(long v) { long max = (long) 4e9; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static long cbrt(long v) { long max = (long) 3e6; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static void prefixSum2D(long arr[][]) { for (int i = 0; i < arr.length; i++) { prefixSum(arr[i]); } for (int i = 0; i < arr[0].length; i++) { for (int j = 1; j < arr.length; j++) { arr[j][i] += arr[j - 1][i]; } } } public static long baseToDecimal(String w, long base) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(base, l); r = r + x; l++; } return r; } static int bs(int v, ArrayList<Integer> a) { int max = a.size() - 1; int min = 0; int ans = 0; while (max >= min) { int mid = (max + min) / 2; if (a.get(mid) >= v) { ans = a.size() - mid; max = mid - 1; } else { min = mid + 1; } } return ans; } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair2() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { return 0; } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) { return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } // public static pair[] dijkstra(int node, ArrayList<pair> a[]) { // PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { // @Override // public int compare(tri o1, tri o2) { // if (o1.y > o2.y) { // return 1; // } else if (o1.y < o2.y) { // return -1; // } else { // return 0; // } // } // }); // q.add(new tri(node, 0, -1)); // pair distance[] = new pair[a.length]; // while (!q.isEmpty()) { // tri p = q.poll(); // int cost = p.y; // if (distance[p.x] != null) { // continue; // } // distance[p.x] = new pair(p.z, cost); // ArrayList<pair> nodes = a[p.x]; // for (pair node1 : nodes) { // if (distance[node1.x] == null) { // tri pa = new tri(node1.x, cost + node1.y, p.x); // q.add(pa); // } // } // } // return distance; // } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static long logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long p) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a); p /= 2; } else { res = (res * a); p--; } } return res; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) { boolean ca = true; while (n % 2 == 0) { if (ca) { if (h.get(2) == null) { h.put(2, new ArrayList<>()); } h.get(2).add(ind); ca = false; } n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { ca = true; while (n % i == 0) { if (ca) { if (h.get(i) == null) { h.put(i, new ArrayList<>()); } h.get(i).add(ind); ca = false; } n /= i; } if (n < i) { break; } } if (n > 2) { if (h.get(n) == null) { h.put(n, new ArrayList<>()); } h.get(n).add(ind); } } // end of solution public static BigInteger ff(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y; long z; public tri(int x, int y, long z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (long i = 3; i * i <= num; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(long[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalAnyBase(long n, long base) { String w = ""; while (n > 0) { w = n % base + w; n /= base; } return w; } 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(long[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName)); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(r.readLine()); } return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 17
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
10dd59109eb7be58940ebfecf019d769
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; public class Q4 { private static final int MAXN = 1000005; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] cnt = new int[MAXN]; int[] isPresent = new int[MAXN]; long[] numberOfWays = new long[MAXN]; for(int i=0;i<MAXN;i++) { cnt[i] = 0; isPresent[i] = 0; numberOfWays[i] = 0; } for(int i=0;i<n;i++) { int x = in.nextInt(); isPresent[x] = 1; cnt[x]++; } int ans = 0; for(int i=MAXN-5;i>=1;i--) { long count = 0; for(int j=i;j<MAXN-4;j+=i) { count += cnt[j]; } long ways = (count*(count-1))/Long.valueOf(2); long numberOfWaysToSubtract = 0; for(int j=2*i;j<MAXN-4;j+=i) { numberOfWaysToSubtract += numberOfWays[j]; } numberOfWays[i] = ways-numberOfWaysToSubtract; if(isPresent[i]==0 && numberOfWays[i]>0) { cnt[i] = 1; ans++; count++; ways = (count*(count-1))/2; numberOfWays[i] = ways-numberOfWaysToSubtract; } } System.out.println(ans); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4ceb93a54040f04c4008642b1fa30410
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_766_D2_D { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long inv(long x,long m){ return powerMod(x,m-2,m); } static class Composite implements Comparable<Composite>{ int d; int a; int b; public int compareTo(Composite X) { if (d!=X.d) return d-X.d; if (a!=X.a) return a-X.a; return b-X.b; } public Composite(int d, int a, int b) { this.d = d; this.a = a; this.b = b; } } static int[] stack; static int[] color; static int[] anc; static int pgcd(int a,int b){ if (a<b) return pgcd(b,a); while (b!=0){ int c=b; b=a%b; a=c; } return a; } static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); long startTime=System.currentTimeMillis(); long endTime=System.currentTimeMillis(); log(endTime-startTime); int n=reader.readInt(); int[] a=new int[n]; int MX=1000001; int[] mem=new int[MX]; int mx=0; int p=0; for (int i=0;i<n;i++) { a[i]=reader.readInt(); mem[a[i]]=1; mx=Math.max(mx,a[i]); p=pgcd(p,a[i]); } mx++; int ans=0; if (p==1 && mem[p]==0) ans++; for (int u=2;u<mx;u++) { if (mem[u]==0) { int v=u; p=0; while (v<mx) { if (mem[v]==1) { p=pgcd(p,v); if (p==u) break; } v+=u; } if (p==u) ans++; } } output(ans); try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
5dc2f43d41661b7280822ecec0b52331
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; public class Solution{ static class Graph{ public static class Vertex{ HashMap<Integer,Integer> nb= new HashMap<>(); // for neighbours of each vertex } public static HashMap<Integer,Vertex> vt; // for vertices(all) public Graph(){ vt= new HashMap<>(); } public static int numVer(){ return vt.size(); } public static boolean contVer(int ver){ return vt.containsKey(ver); } public static void addVer(int ver){ Vertex v= new Vertex(); vt.put(ver,v); } public static void addEdge(int ver1, int ver2, int weight){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } Vertex v1= vt.get(ver1); Vertex v2= vt.get(ver2); v1.nb.put(ver2,weight); // if previously there is an edge, then this replaces that edge v2.nb.put(ver1,weight); } public static void delEdge(int ver1, int ver2){ if(!vt.containsKey(ver1) || !vt.containsKey(ver2)){ return; } vt.get(ver1).nb.remove(ver2); vt.get(ver2).nb.remove(ver1); } public static void delVer(int ver){ if(!vt.containsKey(ver)){ return; } Vertex v1= vt.get(ver); ArrayList<Integer> arr= new ArrayList<>(v1.nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int s= arr.get(i); vt.get(s).nb.remove(ver); } vt.remove(ver); } static boolean done[]; static int parent[]; static ArrayList<Integer>vals= new ArrayList<>(); public static boolean isCycle(int i){ Stack<Integer>stk= new Stack<>(); stk.push(i); while(!stk.isEmpty()){ int x= stk.pop(); vals.add(x); // System.out.print("current="+x+" stackinit="+stk); if(!done[x]){ done[x]=true; } else if(done[x] ){ return true; } ArrayList<Integer>ar= new ArrayList<>(vt.get(x).nb.keySet()); for (int j = 0; j <ar.size() ; j++) { if(parent[x]!=ar.get(j)){ parent[ar.get(j)]=x; stk.push(ar.get(j)); } } // System.out.println(" stackfin="+stk); } return false; } static int[]level; static int[] curr; static int[] fin; public static void dfs(int src){ done[src]=true; level[src]=0; Queue<Integer>q= new LinkedList<>(); q.add(src); while(!q.isEmpty()){ int x= q.poll(); ArrayList<Integer>arr= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <arr.size() ; i++) { int v= arr.get(i); if(!done[v]){ level[v]=level[x]+1; done[v]=true; q.offer(v); } } } } static int oc[]; static int ec[]; public static void dfs1(int src){ Queue<Integer>q= new LinkedList<>(); q.add(src); done[src]= true; // int count=0; while(!q.isEmpty()){ int x= q.poll(); // System.out.println("x="+x); int even= ec[x]; int odd= oc[x]; if(level[x]%2==0){ int val= (curr[x]+even)%2; if(val!=fin[x]){ // System.out.println("bc"); even++; vals.add(x); } } else{ int val= (curr[x]+odd)%2; if(val!=fin[x]){ // System.out.println("bc"); odd++; vals.add(x); } } ArrayList<Integer>arr= new ArrayList<>(vt.get(x).nb.keySet()); // System.out.println(arr); for (int i = 0; i <arr.size() ; i++) { int v= arr.get(i); if(!done[v]){ done[v]=true; oc[v]=odd; ec[v]=even; q.add(v); } } } } static long popu[]; static long happy[]; static long count[]; // total people crossing that pos static long sum[]; // total sum of happy people including that. public static void bfs(int x){ done[x]=true; long total= popu[x]; // long smile= happy[x]; ArrayList<Integer>nbrs= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <nbrs.size() ; i++) { int r= nbrs.get(i); if(!done[r]){ bfs(r); total+=count[r]; // smile+=sum[r]; } } count[x]=total; // sum[x]=smile; } public static void bfs1(int x){ done[x]=true; // long total= popu[x]; long smile= 0; ArrayList<Integer>nbrs= new ArrayList<>(vt.get(x).nb.keySet()); for (int i = 0; i <nbrs.size() ; i++) { int r= nbrs.get(i); if(!done[r]){ bfs1(r); // total+=count[r]; smile+=happy[r]; } } // count[x]=total; sum[x]=smile; } } static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } static class disjointSet{ HashMap<Integer, Node> mp= new HashMap<>(); public static class Node{ int data; Node parent; int rank; } public void create(int val){ Node nn= new Node(); nn.data=val; nn.parent=nn; nn.rank=0; mp.put(val,nn); } public int findparent(int val){ return findparentn(mp.get(val)).data; } public Node findparentn(Node n){ if(n==n.parent){ return n; } Node rr= findparentn(n.parent); n.parent=rr; return rr; } public void union(int val1, int val2){ // can also be used to check cycles Node n1= findparentn(mp.get(val1)); Node n2= findparentn(mp.get(val2)); if(n1.data==n2.data) { return; } if(n1.rank<n2.rank){ n1.parent=n2; } else if(n2.rank<n1.rank){ n2.parent=n1; } else { n2.parent=n1; n1.rank++; } } } static class Pair implements Comparable<Pair>{ int x; int y; // smallest form only public Pair(int x, int y){ this.x=x; this.y=y; } @Override public int compareTo(Pair x){ if(this.x>x.x){ return 1; } else if(this.x==x.x){ if(this.y>x.y){ return 1; } else if(this.y==x.y){ return 0; } else{ return -1; } } return -1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return x == pair.x && y == pair.y; } @Override public int hashCode() { return Objects.hash(x, y); } public String toString(){ return x+" "+y; } } public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int n= Reader.nextInt(); Set<Integer>set= new HashSet<>(); int vals[]= new int[(int)1e6+1]; for (int i = 0; i <n ; i++) { vals[Reader.nextInt()]++; } int ans=0; for(int i=(int)1e6;i>0 ;i--) { int gcd = 0; for (int x = i; x <= (int) 1e6; x += i) { if(vals[x]>0) { gcd = (int) gcd(x, gcd); } } if (gcd == i) { ans++; } } out.append((ans-n)+"\n"); out.flush(); out.close(); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
58bcb6ecc8ab5fb9f7557cbef47a3335
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static int N = 1000010, M = 2 * N; static int MOD = (int)1e9 + 7; static double EPS = 1e-7; static int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; static int h[] = new int[N], to[] = new int[M], ne[] = new int[M], w[] = new int[M], idx; static boolean st[] = new boolean[N]; static int a[] = new int[N], res[] = new int[N]; static int n; static void add(int a, int b) { to[idx] = b; ne[idx] = h[a]; h[a] = idx ++ ; } public static void main(String[] args) throws IOException { InputReader sc = new InputReader(); int n = sc.nextInt(); for(int i = 0; i < n; i ++ ) { a[i] = sc.nextInt(); st[a[i]] = true; } int res = 0; for(int i = N / 2; i > 0; i -- ) { if(!st[i]) { int g = 0; for(int j = i; j <= 1000000; j += i) { if (st[j]) g = gcd(g, j); } if(g == i) { st[g] = true; res++; } } } System.out.println(res); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
6ffd0c16fc2898b77e1eebab06b12d00
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static int N = 1000010, M = 2 * N; static int MOD = (int)1e9 + 7; static double EPS = 1e-7; static int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; static int h[] = new int[N], to[] = new int[M], ne[] = new int[M], w[] = new int[M], idx; static boolean st[] = new boolean[N]; static int a[] = new int[N], res[] = new int[N]; static int n; static void add(int a, int b) { to[idx] = b; ne[idx] = h[a]; h[a] = idx ++ ; } public static void main(String[] args) throws IOException { InputReader sc = new InputReader(); int n = sc.nextInt(); for(int i = 0; i < n; i ++ ) { a[i] = sc.nextInt(); st[a[i]] = true; } int res = 0; for(int i = 1000000; i > 0; i -- ) { if(!st[i]) { int g = 0; for(int j = i; j <= 1000000; j += i) { if (st[j]) g = gcd(g, j); } if(g == i) { st[g] = true; res++; } } } System.out.println(res); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
bbd9de88a57bf0548aec1b441521a75b
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; ////*************************************************************************** /* 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 D_Not_Adding{ 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 size=(int)power(10,6)+30; long well[]= new long[size]; int n=s.nextInt(); long array[]= new long[n]; //HashMap<Long,Long> map = new HashMap<Long,Long>(); int present[]= new int[size]; for(int i=0;i<n;i++){ array[i]=s.nextLong(); // map.put(array[i],(long)1); present[(int)array[i]]=1; } // long g=0; // for(int i=0;i<n;i++){ // long num=array[i]; // if(i==0){ // g=num; // } // else{ // g=gcd(Math.max(g,num),Math.min(g,num)); // } // } // System.out.println("g "+g); long ans=0; for(int i=1;i<size;i++){ long count=0; long hh=1; if(present[i]==0){ long yo=-1; while((hh*i)<size){ long num=hh*i; if(present[(int)num]==1){ // count++; if(yo==-1){ yo=num; } else{ yo=gcd(Math.max(yo,num),Math.min(yo,num)); } } hh++; } if(yo==i){ ans++; } } well[i]=count; } // for(long i=g;i<size;i++){ // if(present[(int)i]==0){ // long hh=well[(int)i]; // if(hh>=2){ // ans++; // } // } // } res.append(ans+" \n"); System.out.println(res); } private static long gcd(long max, long min) { if(min==0){ return max; } return gcd(min,max%min); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } static long modpower(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // SIMPLE POWER FUNCTION=> static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
9d1e0928ca3f447679d04d7db2c81c39
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /** * @author Naitik * */ public class Main { static FastReader sc=new FastReader(); static int dp[]; static boolean v[]; // static int mod=998244353;; static int mod=1000000007; static int max; static int bit[]; //static long fact[]; // static long A[]; static HashMap<Integer,Integer> map; //static StringBuffer sb=new StringBuffer(""); //static HashMap<Integer,Integer> map; static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { // StringBuffer sb=new StringBuffer(""); int ttt=1; //ttt =i(); outer :while (ttt-- > 0) { int n=i(); int A[]=input(n); int F[]=new int[1000001]; for(int i : A) { F[i]++; } ArrayList<Integer> l=new ArrayList<Integer>(); ou:for(int i=1000000;i>0;i--) { if(F[i]>0) continue; int cnt=0; int pv=-1; l.clear(); for(int j=i;j<=1e6;j+=i) { if(F[j]>0) { l.add(j); // if(pv==-1) // pv=j; // else { // int gcd=gcd(pv, j); // if(gcd==i) { // F[i]++; // break; // } // pv=i; // } } } for(int j=0;j<l.size();j++) { for(int k=j+1;k<l.size();k++) { int gcd=gcd(l.get(j),l.get(k)); if(gcd==i) { F[i]++; continue ou; } } break; } } int ans=-n; for(int i : F) { if(i>0) ans++; } System.out.println(ans); } //System.out.println(sb.toString()); out.close(); //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 //CHECK FOR M=0 //CHECK FOR N=1 } static class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int x,int y){ this.x=x; this.y=y; // this.z=z; } @Override public int compareTo(Pair o) { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; else { if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else return 0; } } public int hashCode() { final int temp = 14; int ans = 1; ans =x*31+y*13; return ans; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Pair other = (Pair)o; if (this.x != other.x || this.y!=other.y) { return false; } return true; } // /* FOR TREE MAP PAIR USE */ // public int compareTo(Pair o) { // if (x > o.x) { // return 1; // } // if (x < o.x) { // return -1; // } // if (y > o.y) { // return 1; // } // if (y < o.y) { // return -1; // } // return 0; // } } static int find(int A[],int a) { if(A[a]==a) return a; return A[a]=find(A, A[a]); } //static int find(int A[],int a) { // if(A[a]==a) // return a; // return find(A, A[a]); //} //FENWICK TREE static void update(int i, int x){ for(; i < bit.length; i += (i&-i)) bit[i] += x; } static int sum(int i){ int ans = 0; for(; i > 0; i -= (i&-i)) ans += bit[i]; return ans; } //END static void add(int v) { if(!map.containsKey(v)) { map.put(v, 1); } else { map.put(v, map.get(v)+1); } } static void remove(int v) { if(map.containsKey(v)) { map.put(v, map.get(v)-1); if(map.get(v)==0) map.remove(v); } } public static int upper(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { ans=mid; l=mid+1; } else { u=mid-1; } } return ans; } public static int lower(int A[],int k,int si,int ei) { int l=si; int u=ei; int ans=-1; while(l<=u) { int mid=(l+u)/2; if(A[mid]<=k) { l=mid+1; } else { ans=mid; u=mid-1; } } return ans; } static int[] copy(int A[]) { int B[]=new int[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static long[] copy(long A[]) { long B[]=new long[A.length]; for(int i=0;i<A.length;i++) { B[i]=A[i]; } return B; } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static void reverse(long A[]) { int n=A.length; long B[]=new long[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void reverse(int A[]) { int n=A.length; int B[]=new int[n]; for(int i=0;i<n;i++) { B[i]=A[n-i-1]; } for(int i=0;i<n;i++) A[i]=B[i]; } static void input(int A[],int B[]) { for(int i=0;i<A.length;i++) { A[i]=sc.nextInt(); B[i]=sc.nextInt(); } } static int[][] input(int n,int m){ int A[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { A[i][j]=i(); } } return A; } static char[][] charinput(int n,int m){ char A[][]=new char[n][m]; for(int i=0;i<n;i++) { String s=s(); for(int j=0;j<m;j++) { A[i][j]=s.charAt(j); } } return A; } static int nextPowerOf2(int n) { n--; n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n++; return n; } static int highestPowerof2(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static long highestPowerof2(long x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x ^ (x >> 1); } static int max(int A[]) { int max=Integer.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static int min(int A[]) { int min=Integer.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long max(long A[]) { long max=Long.MIN_VALUE; for(int i=0;i<A.length;i++) { max=Math.max(max, A[i]); } return max; } static long min(long A[]) { long min=Long.MAX_VALUE; for(int i=0;i<A.length;i++) { min=Math.min(min, A[i]); } return min; } static long [] prefix(long A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] prefix(int A[]) { long p[]=new long[A.length]; p[0]=A[0]; for(int i=1;i<A.length;i++) p[i]=p[i-1]+A[i]; return p; } static long [] suffix(long A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static long [] suffix(int A[]) { long p[]=new long[A.length]; p[A.length-1]=A[A.length-1]; for(int i=A.length-2;i>=0;i--) p[i]=p[i+1]+A[i]; return p; } static void fill(int dp[]) { Arrays.fill(dp, -1); } static void fill(int dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(int dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(int dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static void fill(long dp[]) { Arrays.fill(dp, -1); } static void fill(long dp[][]) { for(int i=0;i<dp.length;i++) Arrays.fill(dp[i], -1); } static void fill(long dp[][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { Arrays.fill(dp[i][j],-1); } } } static void fill(long dp[][][][]) { for(int i=0;i<dp.length;i++) { for(int j=0;j<dp[0].length;j++) { for(int k=0;k<dp[0][0].length;k++) { Arrays.fill(dp[i][j][k],-1); } } } } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long power(long x, long y, long p) { if(y==0) return 1; if(x==0) return 0; long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x); y = y >> 1; x = (x * x); } return res; } static void print(int A[]) { for(int i : A) { out.print(i+" "); } out.println(); } static void print(long A[]) { for(long i : A) { System.out.print(i+" "); } System.out.println(); } static long mod(long x) { return ((x%mod + mod)%mod); } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static void sort(int[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ int tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static void sort(long[] A){ int n = A.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = A[i]; int randomPos = i + rnd.nextInt(n-i); A[i] = A[randomPos]; A[randomPos] = tmp; } Arrays.sort(A); } static String sort(String s) { Character ch[]=new Character[s.length()]; for(int i=0;i<s.length();i++) { ch[i]=s.charAt(i); } Arrays.sort(ch); StringBuffer st=new StringBuffer(""); for(int i=0;i<s.length();i++) { st.append(ch[i]); } return st.toString(); } static HashMap<Integer,Integer> hash(int A[]){ HashMap<Integer,Integer> map=new HashMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static HashMap<Long,Integer> hash(long A[]){ HashMap<Long,Integer> map=new HashMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Integer,Integer> tree(int A[]){ TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>(); for(int i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static TreeMap<Long,Integer> tree(long A[]){ TreeMap<Long,Integer> map=new TreeMap<Long, Integer>(); for(long i : A) { if(map.containsKey(i)) { map.put(i, map.get(i)+1); } else { map.put(i, 1); } } return map; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
6d8aafe9edaed773779e72d531925bc6
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { static int N = 1000010; public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); PrintWriter w = new PrintWriter(System.out); int n = f.nextInt(); long ans = 0; int[] cnt = new int[N]; for (int i = 0; i < n; i++) cnt[f.nextInt()] = 1; for (int i = 1; i < N; i++) { if (cnt[i] == 1) continue; int p = 0; for (int j = i + i; j < N; j += i) { if (cnt[j] == 0) continue; if (p == -1) p = j; else p = gcd(p, j); } if (p == i) ans++; } w.println(ans); w.flush(); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } private static class FastScanner { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; private FastScanner() throws IOException { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private short nextShort() throws IOException { short ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = (short) (ret * 10 + c - '0'); while ((c = read()) >= '0' && c <= '9'); if (neg) return (short) -ret; return ret; } private int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do ret = ret * 10 + c - '0'; while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } private char nextChar() throws IOException { byte c = read(); while (c <= ' ') c = read(); return (char) c; } private String nextString() throws IOException { StringBuilder ret = new StringBuilder(); byte c = read(); while (c <= ' ') c = read(); do { ret.append((char) c); } while ((c = read()) > ' '); return ret.toString(); } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
f7df64ba637bc25e61ca0dc5b3432096
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
/* * Everything is Hard * Before Easy * Jai Mata Dii */ import java.util.*; import java.io.*; 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 long mod = (long)(1e9+7); // static long mod = 998244353; // static Scanner sc = new Scanner(System.in); static FastReader sc = new FastReader(); static PrintWriter out = new PrintWriter(System.out); public static void main (String[] args) { int ttt = 1; // ttt = sc.nextInt(); z :for(int tc=1;tc<=ttt;tc++){ // sieve(); int n = sc.nextInt(); int a[] = new int[n]; int max = 0; boolean pos[] = new boolean[(int)(1e6+1)]; for(int i=0;i<n;i++) { a[i] = sc.nextInt(); pos[a[i]] = true; max = Math.max(max, a[i]); } sort(a); int ans = 0; for(int i=max;i>0;i--) { long gcd = -1; for(int j=i;j<=max;j+=i) { if(!pos[j]) continue; if(gcd == -1) gcd = j; else gcd = gcd(j, gcd); if(gcd == i) { ans++; break; } } } ans = ans - n; out.write(ans+"\n"); } out.close(); } static long pow(long a, long b){long ret = 1;while(b>0){if(b%2 == 0){a = (a*a)%mod;b /= 2;}else{ret = (ret*a)%mod;b--;}}return ret%mod;} static long gcd(long a,long b){if(b==0) return a; return gcd(b,a%b); } private static void sort(int[] a) {List<Integer> k = new ArrayList<>();for(int val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);} private static void ini(List<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} private static void init(List<int[]>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}} private static void sort(long[] a) {List<Long> k = new ArrayList<>();for(long val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);} }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
d53540efc18d7fcb1fcce0a6866316f0
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class a729 { public static void main(String[] args) throws IOException { // try { BufferedWriter out = new BufferedWriter( new OutputStreamWriter(System.out)); BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); PrintWriter pt = new PrintWriter(System.out); FastReader sc = new FastReader(); //int t = sc.nextInt(); //for(int o = 0 ; o<t;o++){ int n = sc.nextInt(); boolean[] arr = new boolean[1000001]; //HashSet<Integer> set = new HashSet<Integer>(); for(int i = 0 ; i<n;i++) { int x = sc.nextInt(); //set.add(arr[i]); arr[x] = true; } int ans = 0; int m = 1000000; for(int i = 1 ; i<=m;i++) { int g = -1; for(int j = i;j<=m;j+=i) { if(!arr[j]) { continue; } if(g==-1) { g = j; // continue; }else g = gcd(g, j); } if(g == i) { ans++; } } System.out.println(ans- n); //} } // }catch(Exception e) { // return; // } // } //------------------------------------------------------------------------------------------------------------------------------------------------ static int cntDivisors(int n){ int cnt = 0; for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { if (n/i == i) cnt++; else cnt+=2; } } return cnt; } static long power(long x, long y, long p){ long res = 1; x = x % p; if (x == 0) return 0; while (y > 0){ if ((y & 1) != 0) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } public static long ncr(long[] fac, int n , int r , long m) { return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m; } public static void build(int [][] seg,char []arr,int idx, int lo , int hi) { if(lo == hi) { // seg[idx] = arr[lo]; seg[idx][(int)arr[lo]-'a'] = 1; return; } int mid = (lo + hi)/2; build(seg,arr,2*idx+1, lo, mid); build(seg,arr,idx*2+2, mid +1, hi); //seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]); for(int i = 0 ; i<27;i++) { seg[idx][i] = seg[2*idx+1][i] + seg[2*idx + 2][i]; } } //for f/inding minimum in range public static void query(int[][]seg,int[]ans,int idx , int lo , int hi , int l , int r) { if(lo>=l && hi<=r) { for(int i = 0 ; i<27;i++) { ans[i]+= seg[idx][i]; } return ; } if(hi<l || lo>r) { return; } int mid = (lo + hi)/2; query(seg,ans,idx*2 +1, lo, mid, l, r); query(seg,ans,idx*2 + 2, mid + 1, hi, l, r); //return Math.min(left, right); } //// for sum // public static void update(int[][]seg,char[]arr,int idx, int lo , int hi , int node , char val) { if(lo == hi) { // seg[idx] += val; seg[idx][val-'a']++; seg[idx][arr[node]-'a']--; }else { int mid = (lo + hi )/2; if(node<=mid && node>=lo) { update(seg,arr, idx * 2 +1, lo, mid, node, val); }else { update(seg,arr, idx*2 + 2, mid + 1, hi, node, val); } //seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2]; for(int i = 0 ; i<27;i++) { seg[idx][i] = seg[2*idx+1][i] + seg[2*idx + 2][i]; } } } public static int lower_bound(int array[], int low, int high, int key){ // Base Case if (low > high) { return low; } // Find the middle index int mid = low + (high - low) / 2; // If key is lesser than or equal to // array[mid] , then search // in left subarray if (key <= array[mid]) { return lower_bound(array, low, mid - 1, key); } // If key is greater than array[mid], // then find in right subarray return lower_bound(array, mid + 1, high, key); } public static int upper_bound(int arr[], int low, int high, int key){ // Base Case if (low > high || low == arr.length) return low; // Find the value of middle index int mid = low + (high - low) / 2; // If key is greater than or equal // to array[mid], then find in // right subarray if (key >= arr[mid]) { return upper_bound(arr, mid + 1, high, key); } // If key is less than array[mid], // then find in left subarray return upper_bound(arr, low, mid - 1, key); } // ----------------------------------------------------------------------------------------------------------------------------------------------- public static int gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a); } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public static long modInverse(long a, long m){ long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process // same as Euclid's algo m = a % m; a = t; t = y; // Update x and y y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } //----------------------------------------------------------------------------------------------------------------------------------- //segment tree //for finding minimum in range // public static void build(int [] seg,int []arr,int idx, int lo , int hi) { // if(lo == hi) { // seg[idx] = arr[lo]; // return; // } // int mid = (lo + hi)/2; // build(seg,arr,2*idx+1, lo, mid); // build(seg,arr,idx*2+2, mid +1, hi); // seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]); // } ////for finding minimum in range //public static int query(int[]seg,int idx , int lo , int hi , int l , int r) { // if(lo>=l && hi<=r) { // return seg[idx]; // } // if(hi<l || lo>r) { // return Integer.MAX_VALUE; // } // int mid = (lo + hi)/2; // int left = query(seg,idx*2 +1, lo, mid, l, r); // int right = query(seg,idx*2 + 2, mid + 1, hi, l, r); // return Math.min(left, right); //} // // for sum // //public static void update(int[]seg,int idx, int lo , int hi , int node , int val) { // if(lo == hi) { // seg[idx] += val; // }else { //int mid = (lo + hi )/2; //if(node<=mid && node>=lo) { // update(seg, idx * 2 +1, lo, mid, node, val); //}else { // update(seg, idx*2 + 2, mid + 1, hi, node, val); //} //seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2]; // //} //} //--------------------------------------------------------------------------------------------------------------------------------------- static void shuffleArray(int[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } //----------------------------------------------------------------------------------------------------------------------------------------------------------- } 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 SegmentTree{ int n; public SegmentTree(int[] arr,int n) { this.arr = arr; this.n = n; } int[] arr = new int[n]; // int n = arr.length; int[] seg = new int[4*n]; void build(int idx, int lo , int hi) { if(lo == hi) { seg[idx] = arr[lo]; return; } int mid = (lo + hi)/2; build(2*idx+1, lo, mid); build(idx*2+2, mid +1, hi); seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]); } int query(int idx , int lo , int hi , int l , int r) { if(lo<=l && hi>=r) { return seg[idx]; } if(hi<l || lo>r) { return Integer.MAX_VALUE; } int mid = (lo + hi)/2; int left = query(idx*2 +1, lo, mid, l, r); int right = query(idx*2 + 2, mid + 1, hi, l, r); return Math.min(left, right); } } //----------------------------------------------------------------------------------------------------------------------------------------------------------- class coup{ int a; int b; public coup(int a , int b) { this.a = a; this.b = b; } } class trip{ int a , b, c; public trip(int a , int b, int c) { this.a = a; this.b = b; this.c = c; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4d4c0c03638944354384d816e7c99f2a
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
//package codeforce.div2; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.HashSet; import static java.lang.System.gc; import static java.lang.System.out; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1627/problem/D" target="_top">https://codeforces.com/contest/1627/problem/D</a> * @since 15/01/22 9:56 PM */ public class D { static FastScanner sc = new FastScanner(System.in); public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = 1;//sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); boolean[] present = new boolean[1000000 + 1]; for (int i = 0; i < n; i++) { present[sc.nextInt()] = true; } int add = 0; for (int i = 1; i < present.length/2 + 1; i++) { if (!present[i]) { int gcd = 0; for (int j = i; j < 1000000 + 1; j += i) { if (present[j]) gcd = gcd(gcd, j); } if (gcd == i) { present[i] = true; //System.out.print(i + " "); add++; } } } System.out.println(add); } } } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f), 32768); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
9c1e35983a2f421838b5a216fdc73138
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
//package codeforce.div2; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.HashSet; import static java.lang.System.gc; import static java.lang.System.out; import static java.util.stream.Collectors.joining; /** * @author pribic (Priyank Doshi) * @see <a href="https://codeforces.com/contest/1627/problem/D" target="_top">https://codeforces.com/contest/1627/problem/D</a> * @since 15/01/22 9:56 PM */ public class D { static FastScanner sc = new FastScanner(System.in); public static void main(String[] args) { try (PrintWriter out = new PrintWriter(System.out)) { int T = 1;//sc.nextInt(); for (int tt = 1; tt <= T; tt++) { int n = sc.nextInt(); boolean[] present = new boolean[1000000 + 1]; for (int i = 0; i < n; i++) { present[sc.nextInt()] = true; } int add = 0; for (int i = 1; i < present.length; i++) { if (!present[i]) { int gcd = 0; for (int j = i; j < 1000000 + 1; j += i) { if (present[j]) gcd = gcd(gcd, j); } if (gcd == i) { present[i] = true; add++; } } } System.out.println(add); } } } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f), 32768); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
6934ce9c5f713fb3eb9531d3637b74cb
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; public class solution{ public static int gcd(int a, int b){ if(b == 0){ return a; } return gcd(b,a%b); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); boolean[] visited = new boolean[1000002]; for(int i = 1;i <= n;i++){ int x = sc.nextInt(); visited[x] = true; } int ans = 0; for(int i = 1;i <= 1000001;i++){ int g = -1; for(int mult = i;mult <= 1000001;mult += i){ if(visited[mult]){ if(g == -1){ g = mult; }else{ g = gcd(g,mult); } } } if(g == i){ ans++; } } System.out.println(ans - n); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
c811f84409bd7ed27cae6b4a2e6f25e3
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (1e9 + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static long dp[][][]; static double cmp = 1e-7; static final double pi = 3.14159265359; static int[] ans; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter(f)); int test = 1;//input.nextInt(); loop: for (int co = 1; co <= test; co++) { int n = input.nextInt(); int res = 0; int fre[] = new int[(int) 1e6 + 9]; for (int i = 0; i < n; i++) { fre[input.nextInt()]++; } for (int i = 1; i <= 1e6; i++) { long gcd = 0; if (fre[i]==1) { continue; } for (int j = i + i; j <= 1e6; j += i) { if (fre[j]==1) { gcd = GCD(j, gcd); } } if (gcd == i) { res++; } } log.write(res + "\n"); } log.flush(); } static void dfs(int node, ArrayList<Integer> g[], boolean vi[], boolean ca, TreeMap<pair, Integer> edges) { vi[node] = true; for (Integer ch : g[node]) { if (!vi[ch]) { if (ca) { ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 2; } else { ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 5; } dfs(ch, g, vi, !ca, edges); ca = !ca; } } } static long f(long x) { return (long) ((x * (x + 1) / 2) % mod); } static long Sub(long x, long y) { long z = x - y; if (z < 0) { z += mod; } return z; } static long add(long a, long b) { a += b; if (a >= mod) { a -= mod; } return a; } static long mul(long a, long b) { return (long) ((long) a * b % mod); } static long powlog(long base, long power) { if (power == 0) { return 1; } long x = powlog(base, power / 2); x = mul(x, x); if ((power & 1) == 1) { x = mul(x, base); } return x; } static long modinv(long x) { return fast_pow(x, mod - 2, mod); } static long Div(long x, long y) { return mul(x, modinv(y)); } static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) { vi[r][c] = true; for (int i = 0; i < 4; i++) { int nr = grid[0][i] + r; int nc = grid[1][i] + c; if (isValid(nr, nc, a.length, a[0].length)) { if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) { floodFill(nr, nc, a, vi, w, d); } } } } static boolean isdigit(char ch) { return ch >= '0' && ch <= '9'; } static boolean lochar(char ch) { return ch >= 'a' && ch <= 'z'; } static boolean cachar(char ch) { return ch >= 'A' && ch <= 'Z'; } static class Pa { long x; long y; public Pa(long x, long y) { this.x = x; this.y = y; } } static long sqrt(long v) { long max = (long) 4e9; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static long cbrt(long v) { long max = (long) 3e6; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static void prefixSum2D(long arr[][]) { for (int i = 0; i < arr.length; i++) { prefixSum(arr[i]); } for (int i = 0; i < arr[0].length; i++) { for (int j = 1; j < arr.length; j++) { arr[j][i] += arr[j - 1][i]; } } } public static long baseToDecimal(String w, long base) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(base, l); r = r + x; l++; } return r; } static int bs(int v, ArrayList<Integer> a) { int max = a.size() - 1; int min = 0; int ans = 0; while (max >= min) { int mid = (max + min) / 2; if (a.get(mid) >= v) { ans = a.size() - mid; max = mid - 1; } else { min = mid + 1; } } return ans; } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair2() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { return 0; } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) { return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } // public static pair[] dijkstra(int node, ArrayList<pair> a[]) { // PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { // @Override // public int compare(tri o1, tri o2) { // if (o1.y > o2.y) { // return 1; // } else if (o1.y < o2.y) { // return -1; // } else { // return 0; // } // } // }); // q.add(new tri(node, 0, -1)); // pair distance[] = new pair[a.length]; // while (!q.isEmpty()) { // tri p = q.poll(); // int cost = p.y; // if (distance[p.x] != null) { // continue; // } // distance[p.x] = new pair(p.z, cost); // ArrayList<pair> nodes = a[p.x]; // for (pair node1 : nodes) { // if (distance[node1.x] == null) { // tri pa = new tri(node1.x, cost + node1.y, p.x); // q.add(pa); // } // } // } // return distance; // } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static long logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long p) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a); p /= 2; } else { res = (res * a); p--; } } return res; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) { boolean ca = true; while (n % 2 == 0) { if (ca) { if (h.get(2) == null) { h.put(2, new ArrayList<>()); } h.get(2).add(ind); ca = false; } n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { ca = true; while (n % i == 0) { if (ca) { if (h.get(i) == null) { h.put(i, new ArrayList<>()); } h.get(i).add(ind); ca = false; } n /= i; } if (n < i) { break; } } if (n > 2) { if (h.get(n) == null) { h.put(n, new ArrayList<>()); } h.get(n).add(ind); } } // end of solution public static BigInteger ff(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static class tri { int x, y; long z; public tri(int x, int y, long z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (long i = 3; i * i <= num; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(long[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalAnyBase(long n, long base) { String w = ""; while (n > 0) { w = n % base + w; n /= base; } return w; } 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(long[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName)); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(r.readLine()); } return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
ffec7bb3f84ada6fda9d399ef047309d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { int n=input.nextInt(); int max=1000000; boolean arr[]=new boolean[max+1]; for(int i=0;i<n;i++) { arr[input.nextInt()]=true; } for(int i=max;i>=1;i--) { int g=0; for(int j=i;j<=max;j+=i) { if(arr[j]) { g=gcd(g,j); } } if(i==g) { arr[i]=true; } } int c=0; for(int i=1;i<=max;i++) { if(arr[i]) c++; } out.println(c-n); } out.close(); } public static int gcd(int a, int b) { if(a==0) { return b; } else { return gcd(b%a,a); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
d53c08ad65fa7f0acca9097434c910e1
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Main { static int i, j, k, n, m, t, y, x, sum = 0; static long mod = 998244353; static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static String str; static long ans; public static void main(String[] args) { t =1; while(t-- >0){ n = fs.nextInt(); Set<Integer> ele = new HashSet<>(); for(i=0;i<n;i++){ x = fs.nextInt(); ele.add(x); } for(i=1;i<1000001;i++){ if(ele.contains(i)) continue; int g = 0; for(j=i;j<1000001;j+=i){ if(ele.contains(j)) { if(g==0) g=j; else g = gcd(g,j); } } if(g == i) ans++; } out.println(ans); } out.close(); } /** * Returns the gretaest index of closest element less than x in arr * returns -1 if all elemets are greater * */ public static int lowerBound(int x, List<Integer> arr, int l, int r){ if(arr.get(l)>=x) return -1; if(arr.get(r)<x) return r; int mid = (l+r)/2; if(arr.get(mid)<x && arr.get(mid+1)>x) return mid; if(arr.get(mid)>=x) return lowerBound(x,arr,l,mid-1); return lowerBound(x,arr,mid+1,r); } /** * Returns the lowest index of closest element greater than or equal to x in arr * returns -1 if all elements are lesser * */ public static int upperBound(int x, List<Integer> arr, int l, int r){ if(arr.get(r) <=x) return -1; if(arr.get(l)>x) return l; int mid = (l+r)/2; if(arr.get(mid)>x && arr.get(mid-1)<=x) return mid; if(arr.get(mid)<=x) return upperBound(x,arr,mid+1,r); return upperBound(x,arr,l,mid-1); } /** * Returns the index of element if present else -1. * */ public static int binSearch(int x, List<Integer> arr){ int y = Collections.binarySearch(arr, x); if(y<0) return -1; return y; } /*static long nck(int n , int k){ long a = fact[n]; long b = modInv(fact[k]); b*= modInv(fact[n-k]); b%=mod; return (a*b)%mod; } static void populateFact(){ fact[0]=1; fact[1] = 1; for(i=2;i<300005;i++){ fact[i]=i*fact[i-1]; fact[i]%=mod; } } */ static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long exp(long base, long pow) { if (pow == 0) return 1; long half = exp(base, pow / 2); if (pow % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long mul(long a, long b) { return ((a % mod) * (b % mod)) % mod; } static long add(long a, long b) { return ((a % mod) + (b % mod)) % mod; } static long modInv(long x) { return exp(x, mod - 2); } static void ruffleSort(int[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } //then sort Arrays.sort(a); } static void ruffleSort(long[] a) { //ruffle 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; } Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static class Pair implements Comparable<Pair> { public int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (x == o.x) return Integer.compare(y, o.y); return Integer.compare(x, o.x); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
f53d44ca0b84cb439115e0abdd6b34ee
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import javax.management.Query; import java.io.*; public class Contest1 { public static void main(String[] args) throws Exception { //Scanner sc=new Scanner(System.in); // int t=sc.nextInt(); // while(t-->0) {} int n=sc.nextInt(); int [] a=new int [1000006]; int [] b=new int [1000006]; for (int i = 0; i < n; i++) { a[sc.nextInt()]++; } for (int i = 1; i < b.length; i++) { for (int j = i; j < b.length; j+=i) { b[i]+=a[j]; } } int ans=-n; // for (int i = 0; i <35; i++) { // //pw.print(b[i]+" "); // } boolean flag=false; for (int i = 0; i < b.length; i++) { if(b[i]==0) continue; //pw.print("ddfv"+i); for (int j = i+i; j < b.length; j+=i) { if(b[i]==b[j]) flag=true; } if(!flag) { ans+=1; //pw.print(" b[i]= "+i); } flag=false; } pw.print(ans); pw.close(); } public static int gcd(int a, int b) { if(b==0) return a; else return gcd(b,a%b); } 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; } } } 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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
dbeb8eaa01db1d800ec2ac5a8f5f178d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class D { public static void process() throws IOException { int n = sc.nextInt(); HashSet<Integer> set = new HashSet<Integer>(); int arr[] = sc.readArray(n); for(int e : arr)set.add(e); int MaxN = 1_000_005; int ans = 0; for(int i = 1; i<MaxN; i++) { if(set.contains(i)) { ans++; continue; } long gcd = 0; for(int j = i+i; j<MaxN; j+=i) { if(!set.contains(j))continue; gcd = gcd(gcd, j); } if(gcd == i)ans++; } out.println(ans-n); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; // t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
9fbe1aa0d93d7c6d084b3d499f8ae89b
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; /** * * @Har_Har_Mahadev */ /** * Main , Solution , Remove Public */ public class D { public static void process() throws IOException { int n = sc.nextInt(); HashSet<Integer> set = new HashSet<Integer>(); int arr[] = sc.readArray(n); for(int e : arr)set.add(e); int MaxN = 1_000_005; int ans = 0; for(int i = 1; i<MaxN; i++) { if(set.contains(i)) { ans++; continue; } long gcd = 0; for(int j = i+i; j<MaxN; j+=i) { if(!set.contains(j))continue; gcd = gcd(gcd, j); } if(gcd == i)ans++; } System.out.println(ans-n); } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; // t = sc.nextInt(); int TTT = 1; while (t-- > 0) { // google(TTT++); process(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if (!oj) System.err.println(Arrays.deepToString(o)); } static class Pair implements Comparable<Pair> { int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { return Integer.compare(this.x, o.x); } /* @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pair)) return false; Pair key = (Pair) o; return x == key.x && y == key.y; } @Override public int hashCode() { int result = x; result = 31 * result + y; return result; } */ } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long gcd(long a, long b) { if (a > b) a = (a + b) - (b = a); if (a == 0L) return b; return gcd(b % a, a); } public static long lcm(long a, long b) { return (a * b) / gcd(a, b); } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } static void ruffleSort(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void ruffleSort(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } Arrays.sort(a); } static void reverseArray(int[] a) { int n = a.length; int arr[] = new int[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } static void reverseArray(long[] a) { int n = a.length; long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = a[n - i - 1]; for (int i = 0; i < n; i++) a[i] = arr[i]; } //custom multiset (replace with HashMap if needed) public static void push(TreeMap<Integer, Integer> map, int k, int v) { //map[k] += v; if (!map.containsKey(k)) map.put(k, v); else map.put(k, map.get(k) + v); } public static void pull(TreeMap<Integer, Integer> map, int k, int v) { //assumes map[k] >= v //map[k] -= v int lol = map.get(k); if (lol == v) map.remove(k); else map.put(k, lol - v); } // compress Big value to Time Limit public static int[] compress(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int boof = 1; //min value for (int x : ls) if (!map.containsKey(x)) map.put(x, boof++); int[] brr = new int[arr.length]; for (int i = 0; i < arr.length; i++) brr[i] = map.get(arr[i]); return brr; } // Fast Writer public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } // Fast Inputs static class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
5bc2b81c99dd24151b85e6dfc88c90be
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; /** * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools */ public class Main { static InputReader sc=new InputReader(System.in); static int gcd(int a,int b){ if(b==0)return a; int tmp=a%b; a=b; b=tmp; return gcd(a,b); } public static void main(String[] args) { // Write your solution here int n=sc.nextInt(); int maxn=1000005; int A=-1; boolean has[]=new boolean[maxn]; for(int i=0;i<n;i++){ int a=sc.nextInt(); has[a]=true; A=Math.max(A,a); } int count=0; for(int i=A;i>0;i--){ int g=0; for(int x=i;x<=A;x+=i){ if(has[x]){ g=gcd(x,g); } } if(g==i){ has[i]=true; count++; } } System.out.println(count-n); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } 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 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; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a51754cb3fdeed075c79f76f6afebc28
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class A { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); // int t = sc.ni();while(t-->0) long start = System.nanoTime(); solve(); long end = System.nanoTime(); // System.out.println((end - start) * (1E-9)); w.close(); } static void solve() throws IOException { int n = sc.ni(); int[] arr = sc.na(n); int[] hash = new int[1000005]; for(int i = 0; i < n; i++) { hash[arr[i]]++; } int ct = 0; for(int i = 1; i < 1000005; i++) { if(hash[i]==1) continue; long gcd = 0; for(int j = i+i; j < 1000005; j+=i) { if(hash[j] == 1) gcd = gcd(gcd, j); } if(gcd == i) ct++; } w.p(ct); } static long gcd(long a, long b) { return b == 0 ? (a < 0L ? -a: a) : gcd(b, a%b); } static long lcm(long a, long b) { return a/gcd(a, b)*b; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
1e7be18b90fe40df5baa589a6d2184f8
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
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.*; //import sun.jvm.hotspot.runtime.linux_aarch64.LinuxAARCH64JavaThreadPDAccess; public class B { static int mod= 998244353; public static void main(String[] args) throws Exception { PrintWriter out=new PrintWriter(System.out); FastScanner fs=new FastScanner(); int t=1; outer:while(t-->0) { int n=fs.nextInt(); int arr[]=fs.readArray(n); Set<Integer> set=new HashSet<>(); int ans=0; for(int ele:arr) set.add(ele); for(int i=1;i<1000001;i++) { int g=0; if(set.contains(i)) continue; for(int j=i*2;j<1000001;j+=i) { if(set.contains(j)) g=gcd(g,j); } if(g==i) ans++; } out.println(ans); } out.close(); } 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 int gcd(int a,int 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); } // 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(); } int nextInt() { return Integer.parseInt(next()); } long[] lreadArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
cb523ebda2e26b0a639672e33d2c7260
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
//package challenges.codeforces756; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.List; public class Main { static InputReader in=new InputReader(System.in); static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) { int t=1; for (int i = 0; i <t ; i++) { solve(); out.flush(); } } static void solve(){ int n=in.nextInt(); boolean []isElementPresent=new boolean[(int)1e6+1]; for (int i = 0; i <n ; i++) { isElementPresent[in.nextInt()]=true; } int max=isElementPresent.length-1; int ctr=0; for (int i = max; i >=1 ; i--) { if(isElementPresent[i]) continue; int gcd=0; for (int j = i; j <=max ; j+=i) { if(isElementPresent[j]) gcd=gcd(gcd,j); } if(gcd==i){ isElementPresent[gcd]=true; ctr++; } } out.println(ctr); } static int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b); } static public class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not to use == //remember Arrays.sort for primitive data has worst time case complexity of 0(n^2) bcoz it uses quick sort //again silly mistakes ,yr kb tk krta rhega ye mistakes //try to write simple codes ,break it into simple things //knowledge>rating /* public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"Main",1<<26).start(); } public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC();//chenge the name of task solver.solve(1, in, out); out.close(); } */ if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong(){ int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public float getNextFloat(){ String num=readString(); return Float.parseFloat(num); } public double getNextDouble(){ String num=readString(); return Double.parseDouble(num); } /** * returns an array of arrayList of size n+1; * @param n * @return */ public List<Integer>[] initList(int n) { List<Integer>[] arrayLists=new ArrayList[n+1]; for(int i=0;i<=n;i++){ arrayLists[i]=new ArrayList<Integer>(); } return arrayLists; } public int[] getArray(int n){ int[] ar =new int[n]; for (int i = 0; i <n ; i++) { ar[i]=nextInt(); } return ar; } public long[] getLongArray(int n){ long[] ar=new long[n]; for (int i = 0; i <n ; i++) { ar[i]=nextLong(); } return ar; } public String readString() { 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 String next() { return readString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
f85b8b9acddf917b18d04bace718c14c
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public final class D { public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = fs.nextInt(); int[] arr = fs.readArray(N); int max = 0; int cnt= 0; for(int i: arr) max = Math.max(max,i); boolean[] present = new boolean[max + 1]; for(int i: arr) present[i] = true; for(int i = max; i > 0; --i){ int g= 0; for(int j = i; j <= max; j += i){ if(present[j]) g = gcd(g,j); } if(i == g){ present[i] = true; cnt++; } } out.println(cnt - N); out.flush(); } static int gcd(int x, int y) { int temp; while (y > 0) { x %= y; temp = x; x = y; y = temp; } return x; } static final Random random = new Random(); static final int mod = 1_000_000_007; static long add(long a, long b) { return (a + b) % mod; } static long sub(long a, long b) { return ((a - b) % mod + mod) % mod; } static 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 long mul(long a, long b) { return (a * b) % mod; } static long exp(long base, long exp) { if (exp == 0) return 1; long half = exp(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials = new long[2_000_001]; static long[] invFactorials = new long[2_000_001]; static void precompFacts() { factorials[0] = invFactorials[0] = 1; for (int i = 1; i < factorials.length; i++) factorials[i] = mul(factorials[i - 1], i); invFactorials[factorials.length - 1] = exp(factorials[factorials.length - 1], mod - 2); for (int i = invFactorials.length - 2; i >= 0; i--) invFactorials[i] = mul(invFactorials[i + 1], i + 1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n - k])); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
91ff270c6b3966be9d137a937a767b58
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //reading /writing file //Scanner in=new Scanner(System.in); //Scanner in=new Scanner(new File("input.txt")); //PrintWriter pr=new PrintWriter("output.txt"); int T=1; for(int t=0;t<T;t++){ Solution sol1=new Solution(out,fs); sol1.solution(T,t); } out.flush(); } public static int[] Arr(int n){ int A[]=new int[n]; for(int i=0;i<n;i++)A[i]=Int(); return A; } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution { PrintWriter out; int INF = Integer.MAX_VALUE; int NINF = Integer.MIN_VALUE; int MOD = 998244353; int mod = 1000000007; Main.FastScanner fs; public Solution(PrintWriter out, Main.FastScanner fs) { this.out = out; this.fs = fs; } public void solution(int all, int testcase) { int n = fs.Int(); int A[] = new int[n]; boolean seen[] = new boolean[1000000 + 10]; for(int i = 0; i < n; i++){ A[i] = fs.Int(); if(!seen[A[i]]){ seen[A[i]] = true; } } int mx = 1000000; for(int g = mx ; g>= 1; g--){ List<Integer>list = new ArrayList<>(); for(int j = g + g; j <= mx; j += g){ if(seen[j]){ list.add(j); } } if(list.size() > 0){ int first = list.get(0); for(int i = 1; i < list.size(); i++) { int x = list.get(i); if(x % first!=0){ seen[g] = true; break; } } } } int sum = 0; for(boolean b : seen){ if(b)sum++; } out.println(sum - n); } public int gcd(int num1, int num2) { if (num2 != 0) { return gcd(num2, num1 % num2); } else { return num1; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
552ef932d1681ef95e1aa57e52e7038a
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import javax.swing.*; import java.lang.reflect.Array; import java.text.DecimalFormat; import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.stream.Stream; // Please name your class Main public class Main { static FastScanner fs=new FastScanner(); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int Int() { return Integer.parseInt(next()); } long Long() { return Long.parseLong(next()); } String Str(){ return next(); } } public static void main (String[] args) throws java.lang.Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //reading /writing file //Scanner in=new Scanner(System.in); //Scanner in=new Scanner(new File("input.txt")); //PrintWriter pr=new PrintWriter("output.txt"); int T=1; for(int t=0;t<T;t++){ Solution sol1=new Solution(out,fs); sol1.solution(T,t); } out.flush(); } public static int[] Arr(int n){ int A[]=new int[n]; for(int i=0;i<n;i++)A[i]=Int(); return A; } public static int Int(){ return fs.Int(); } public static long Long(){ return fs.Long(); } public static String Str(){ return fs.Str(); } } class Solution { PrintWriter out; int INF = Integer.MAX_VALUE; int NINF = Integer.MIN_VALUE; int MOD = 998244353; int mod = 1000000007; Main.FastScanner fs; public Solution(PrintWriter out, Main.FastScanner fs) { this.out = out; this.fs = fs; } public void solution(int all, int testcase) { int n = fs.Int(); int A[] = new int[n]; boolean seen[] = new boolean[1000000 + 10]; for(int i = 0; i < n; i++){ A[i] = fs.Int(); if(!seen[A[i]]){ seen[A[i]] = true; } } int mx = 1000000; for(int g = mx ; g>= 1; g--){ List<Integer>list = new ArrayList<>(); for(int j = g + g; j <= mx; j += g){ if(seen[j]){ list.add(j); } } if(list.size() > 0){ int gg = list.get(0); for(int i = 1; i < list.size(); i++) { gg = gcd(gg,list.get(i)); if(g == gg) { seen[g]=true; break; } } } } int sum = 0; for(boolean b : seen){ if(b)sum++; } out.println(sum - n); } public int gcd(int num1, int num2) { if (num2 != 0) { return gcd(num2, num1 % num2); } else { return num1; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
771c5756a5fec8232814ded33ebb2752
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
//package codeforces.round766div2; import java.io.*; import java.util.*; import static java.lang.Math.*; public class D { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int MAX_V = 1000000; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(); boolean[] exist = new boolean[MAX_V + 1]; for(int i = 0; i < n; i++) { int v = in.nextInt(); exist[v] = true; } //stores each unique number's prime factors Map<Integer, Set<Integer>> pfMap = new HashMap<>(); int ans = 0; for(int v = MAX_V; v >= 1; v--) { if(!exist[v]) { int currGcd = -1; for(int w = v * 2; w <= MAX_V; w += v) { if(exist[w]) { if(currGcd < 0) currGcd = w / v; else { currGcd = gcd(currGcd, w / v); if(currGcd == 1) { exist[v] = true; ans++; break; } } } } } } out.println(ans); } out.close(); } static int gcd(int x, int y) { if(y == 0) return x; return gcd(y, x % y); } static Set<Integer> computePf(int x) { Set<Integer> factor = new HashSet<>(); //If n is a composite number then there is at least 1 prime divisor of n <= Math.sqrt(n) //x is defined as int, so x * x may overflow, causing TLE //either define x as long, or replace x * x <= n with x <= Math.sqrt(n) to avoid overflow for(int i = 2; i * i <= x; i++) { while(x % i == 0) { factor.add(i); x /= i; } } if(x > 1) { factor.add(x); } return factor; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<Integer>[] readGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
3f980c9214c1c6c4b9303ec6d91153e0
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public final class Main { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)}; static int mod = (int) (1e9 + 7); static int mod2 = 998244353; public static void main(String[] args) { int tt = 1; while (tt-- > 0) { solve(); } out.flush(); } public static void solve() { int n = i(); Set<Integer> set = new HashSet<>(); int[] a = input(n); int max = a[0]; for (int i = 0; i < n; i++) { set.add(a[i]); max = Math.max(max, a[i]); } int ans = 0; for (int i = 1; i < max; i++) { if (set.contains(i)) { continue; } int j = 2; int x = -1; while (i * j <= max) { if (set.contains(i * j)) { if (x == -1) { x = i * j; } else { x = GCD(x, i * j); if (x == i) { ans++; break; } } } j++; } } out.println(ans); } static int[] primes; static int sizeofp = 0; static boolean[] isComposite; static int facts(int x) { int ans = 0; for (int p = 0; p < sizeofp; p++) { int i = primes[p]; while (x % i == 0) { x /= i; ans++; } } if (x > 1) { ans++; } return ans; } // O(N log log N) static void sieve(int N) { isComposite = new boolean[N + 1]; isComposite[0] = isComposite[1] = true; primes = new int[N]; for (int i = 2; i <= N; ++i) { if (!isComposite[i]) { primes[sizeofp++] = i; if ((long) i * i <= N) { for (int j = i * i; j <= N; j += i) { isComposite[j] = true; } } } } } static long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static long[] pre(int[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static long[] post(int[] a) { long[] post = new long[a.length + 1]; post[0] = 0; for (int i = 0; i < a.length; i++) { post[i + 1] = post[i] + a[a.length - 1 - i]; } return post; } static long[] pre(long[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static double d() { return in.nextDouble(); } static String s() { return in.nextLine(); } static String c() { return in.next(); } static int[][] inputWithIdx(int N) { int A[][] = new int[N][2]; for (int i = 0; i < N; i++) { A[i] = new int[]{i, in.nextInt()}; } return A; } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long LCM(int a, int b) { return (long) a / GCD(a, b) * b; } static long LCM(long a, long b) { return a / GCD(a, b) * b; } static void shuffle(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } } static void shuffleAndSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int[] temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr, comparator); } static void shuffleAndSort(long[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); long temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static boolean isPerfectSquare(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static void swap(char A[], int a, int b) { char t = A[a]; A[a] = A[b]; A[b] = t; } static long pow(long a, long b, int mod) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow *= x; } x = x * x; b /= 2; } return pow; } static long modInverse(long x, int mod) { return pow(x, mod - 2, mod); } static boolean isPrime(long N) { if (N <= 1) { return false; } if (N <= 3) { return true; } if (N % 2 == 0 || N % 3 == 0) { return false; } for (int i = 5; i * i <= N; i = i + 6) { if (N % i == 0 || N % (i + 2) == 0) { return false; } } return true; } public static String reverse(String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); } public static void reverse(int[] arr) { for (int i = 0; i < arr.length / 2; i++) { int tmp = arr[i]; arr[arr.length - 1 - i] = tmp; arr[i] = arr[arr.length - 1 - i]; } } public static String repeat(char ch, int repeat) { if (repeat <= 0) { return ""; } final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } public static int[] manacher(String s) { char[] chars = s.toCharArray(); int n = s.length(); int[] d1 = new int[n]; for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1); while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) { k++; } d1[i] = k--; if (i + k > r) { l = i - k; r = i + k; } } return d1; } public static int[] kmp(String s) { int n = s.length(); int[] res = new int[n]; for (int i = 1; i < n; ++i) { int j = res[i - 1]; while (j > 0 && s.charAt(i) != s.charAt(j)) { j = res[j - 1]; } if (s.charAt(i) == s.charAt(j)) { ++j; } res[i] = j; } return res; } } class Pair { int i; int j; Pair(int i, int j) { this.i = i; this.j = j; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return i == pair.i && j == pair.j; } @Override public int hashCode() { return Objects.hash(i, j); } } class ThreePair { int i; int j; int k; ThreePair(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ThreePair pair = (ThreePair) o; return i == pair.i && j == pair.j && k == pair.k; } @Override public int hashCode() { return Objects.hash(i, j); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Node { int val; public Node(int val) { this.val = val; } } class ST { int n; Node[] st; ST(int n) { this.n = n; st = new Node[4 * Integer.highestOneBit(n)]; } void build(Node[] nodes) { build(0, 0, n - 1, nodes); } private void build(int id, int l, int r, Node[] nodes) { if (l == r) { st[id] = nodes[l]; return; } int mid = (l + r) >> 1; build((id << 1) + 1, l, mid, nodes); build((id << 1) + 2, mid + 1, r, nodes); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } void update(int i, Node node) { update(0, 0, n - 1, i, node); } private void update(int id, int l, int r, int i, Node node) { if (i < l || r < i) { return; } if (l == r) { st[id] = node; return; } int mid = (l + r) >> 1; update((id << 1) + 1, l, mid, i, node); update((id << 1) + 2, mid + 1, r, i, node); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } Node get(int x, int y) { return get(0, 0, n - 1, x, y); } private Node get(int id, int l, int r, int x, int y) { if (x > r || y < l) { return new Node(0); } if (x <= l && r <= y) { return st[id]; } int mid = (l + r) >> 1; return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y)); } Node comb(Node a, Node b) { if (a == null) { return b; } if (b == null) { return a; } return new Node(a.val | b.val); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
8919c406251115a0f986cbdf95eefa86
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class NotAdding_766D { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int max = 0; int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine()); Set<Integer> seen = new HashSet<>(); for(int i = 0; i < n; i ++) { int num = Integer.parseInt(st.nextToken()); max = Math.max(max, num); seen.add(num); } for(int num = 1; num <= max / 2; num ++) { if(seen.contains(num)) continue; int prev = -1; for(int i = 2; i <= max; i ++) { int val = i * num; if(val > max) break; if(!seen.contains(val)) continue; if(prev == -1) { prev = val; } else { prev = getGCD(prev, val); } if(prev == num) { seen.add(num); break; } } } System.out.println(seen.size() - n); } private static int getGCD(int a, int b) { return b % a == 0? a : getGCD(b % a, a); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
5714febbe8afe7e3804c639ce652b4fc
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.StringTokenizer; /* */ public class D { public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int n =fs.nextInt(); int[] a=fs.readArray(n); boolean[] hit=new boolean[1_000_001]; for (int i:a) hit[i]=true; for (int i=1_000_000; i>0; i--) { int gcd=0; for (int times=2; i*times<hit.length; times++) { if (hit[i*times]) gcd=gcd(gcd, times); } hit[i]|=gcd==1; } int ans=0; for (boolean b:hit) if (b) ans++; out.println(ans-n); out.close(); } static int gcd(int a, int b) { if (b==0) return a; return gcd(b, a%b); } static final Random random=new Random(); static final int mod=998244353; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4a8d92598134b53b56af4e3ee733794e
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { private static final int size = 1000000; //private static final int size = 100; public static int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); } public static void main(String[] args) { Reader myReader = new Reader(); int n = myReader.nextInt(); boolean[] seen = new boolean[size + 1]; for (int i=0; i<n; i++) { seen[myReader.nextInt()] = true; } int res = 0; for (int i=1; i<=size; i++) { if (seen[i]) continue; int gcd = 0; for (int j=i; j<=size; j+=i) { if (seen[j]) gcd = gcd(gcd, j); } if (gcd==i) { seen[i] = true; res++; } } System.out.println(res); } private static class Reader { BufferedReader reader; StringTokenizer st; Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { try { if (st==null || !st.hasMoreTokens()) st = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
2402dc41b799a402626c6e427ab2711c
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class D_NotAdding_1900 { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); boolean[] isInArray = new boolean[1000001]; for(int i = 0; i < n; i++) { isInArray[sc.nextInt()] = true; } int ans = 0; int gcd = 0; for(int i = 1; i <= 1000000; i++) { if(isInArray[i]) continue; for(int j = i; j <= 1000000; j += i) { if(isInArray[j]) { gcd = GCD(gcd,j); } } if(gcd == i) { ans++; isInArray[i] = true; } gcd = 0; } System.out.println(ans); out.close(); } public static int GCD(int a, int b) { return b==0 ? a : GCD(b, a%b); } public static PrintWriter out; public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { public int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a7b652974d6e7bdfd969775b299be7df
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); //int a = 1; int t; //t = in.nextInt(); t = 1; while (t > 0) { //out.print("Case #"+(a++)+": "); solver.call(in,out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n, a, max = Integer.MIN_VALUE; n = in.nextInt(); boolean[] arr = new boolean[1000005]; for (int i = 0; i < n; i++) { a = in.nextInt(); max = Math.max(max, a); arr[a] = true; } int ans = 0, b; for(int i = 1; i <= max; i++){ if(arr[i]){ continue; } b = 0; for (int j = i; j <= max; j+=i) { if(arr[j]){ b = gcd(b, j); } } if(b==i){ arr[b] = true; ans++; } } out.println(ans); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answer implements Comparable<answer>{ int a, b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return Integer.compare(this.a, o.a); } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { return (o.a - this.a); } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (Long i:a) l.add(i); l.sort(Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(int[] a) { int n = a.length; for (int i=0; i<n; i++) { int oi= random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static 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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4a8086def5090ccecb7fa5edcd15d474
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class NotAdding { public static PrintWriter out; public static void main(String[] args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); out=new PrintWriter(System.out); int n=Integer.parseInt(st.nextToken()); boolean a[]=new boolean[1000001]; st=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { int x=Integer.parseInt(st.nextToken()); a[x]=true; } int ans=0; for(int i=1;i<=1000000;i++) { long g=0; for(int j=i;j<=1000000;j+=i) { if(a[j]) { g=gcd(j, g); } } if((int)g==i&&!a[i]) { ans++; } } out.println(ans); out.close(); } public static long gcd(long a, long b) { while (b != 0) { a %= b; long temp = a; a = b; b = temp; } return a; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
6ab99c7d7955b0fbeb4851090c9e5cb4
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; // cd C:\Users\Lenovo\Desktop\New //ArrayList<Integer> a=new ArrayList<>(); //List<Integer> lis=new ArrayList<>(); //StringBuilder ans = new StringBuilder(); //HashMap<Integer,Integer> map=new HashMap<>(); public class cf { static FastReader in=new FastReader(); static final Random random=new Random(); static long mod=1000000007L; public static void main(String args[]) throws IOException { FastReader sc=new FastReader(); //Scanner s=new Scanner(System.in); //int t=sc.nextInt(); int tt=1; while(tt-->0){ //StringBuilder ar = new StringBuilder(); //System.out.println(t); int n=sc.nextInt(); int arr[]=new int[n]; int max=0; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); if(arr[i]>max){ max=arr[i]; } } boolean present[]=new boolean[max+1]; for(int i=0;i<n;i++){ present[arr[i]]=true; } int count=0; for(int i=max-1;i>=1;i--){ int gcd=0; if(present[i]==false){ for(int j=i;j<=max;j=j+i){ if(present[j]){ gcd=gcd(j,gcd); } } if(gcd==i){ present[i]=true; count++; } } } System.out.println(count); } } static long find(ArrayList<Integer> a,int k){ long ans=0l; if(a.size()==1){ return k-1; } ans+=a.get(1)-2; for(int i=1;i<a.size()-1;i++){ ans+=a.get(i+1)-a.get(i-1)-2; } ans+=k-a.get(a.size()-2)-1; return ans; } static boolean check(int[][]arr,int n,int m){ for(int i=0;i<n;i++){ for(int j=1;j<m;j++){ if(arr[i][j]<=arr[i][j-1]){ return false; } } } for(int j=0;j<m;j++){ for(int i=1;i<n;i++){ if(arr[i][j]<=arr[i-1][j]){ return false; } } } return true; } static void dfs(int [][]arr,int row,int col,boolean [][]seen,int n){ if(row<0 || col<0 || row==n || col==n){ return; } if(arr[row][col]==1){ return; } if(seen[row][col]==true){ return; } seen[row][col]=true; dfs(arr,row+1,col,seen,n); dfs(arr,row,col+1,seen,n); dfs(arr,row-1,col,seen,n); dfs(arr,row,col-1,seen,n); } static int msb(int x){ int ans=0; while(x!=0){ x=x/2; ans++; } return ans; } static void ruffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), 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 boolean checkprime(int n1) { if(n1%2==0||n1%3==0) return false; else { for(int i=5;i*i<=n1;i+=6) { if(n1%i==0||n1%(i+2)==0) return false; } return true; } } */ /* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, Integer> entry = iterator.next(); int value = entry.getValue(); if(value==1){ iterator.remove(); } else{ entry.setValue(value-1); } } */ static class Pair implements Comparable { int a,b; public String toString() { return a+" " + b; } public Pair(int x , int y) { a=x;b=y; } @Override public int compareTo(Object o) { Pair p = (Pair)o; if(p.b!=b){ return b-p.b; } else{ return a-p.a;//increasing } } } /* public static boolean checkAP(List<Integer> lis){ for(int i=1;i<lis.size()-1;i++){ if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){ return false; } } return true; } public static int minBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]>=val){ r=mid; } else{ l=mid; } } return r; } public static int maxBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]<=val){ l=mid; } else{ r=mid; } } return l; } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; }*/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
ef5e18feae966e9a486174d5f61b8fb4
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.BitSet; public class HelloWorld { public static void main(String[] args) { FastScanner fs = new FastScanner(); int n = fs.nextInt(); int N = 1000001; BitSet a = new BitSet(N); for (int i = 0; i < n; i++) { int x = fs.nextInt(); a.set(x); } for (int i = N - 1; i >= 1; i--) { int g = 0; for (int j = 2 * i; j < N; j += i) { if (a.get(j)) g = gcd(g, j); } if (g == i) a.set(i); } System.out.print(a.cardinality() - n); } static int gcd(int a, int b) { return b == 0 ? a : 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()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
09f9cf0e014a10ec469446819262085d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.CollationElementIterator; import java.util.*; public class CFD { static CFD.Reader sc = new CFD.Reader(); static BufferedWriter bw; static int team1; static int team2; static int minkicks; public CFD() { } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int[] ar=new int[n]; int max=Integer.MIN_VALUE; for(int i=0;i<n;i++){ ar[i]=sc.nextInt(); max=Math.max(ar[i],max); } boolean[] check=new boolean[max+1]; for(int i=0;i<n;i++){ // ar[i]=sc.nextInt(); check[ar[i]]=true; } int ans=0; for(int i=max;i>=1;i--){ long gcd=0; if(!check[i]){ for(int j=i;j<=max;j+=i){ if(check[j]){ gcd=gcd(gcd,j); } } if(gcd==i){ ans++; check[i]=true; } } } System.out.println(ans); bw.flush(); bw.close(); } public static int checker(int a) { if (a % 2 == 0) { return 1; } else { byte b; do { b = 2; } while (a + b != (a ^ b)); return b; } } public static boolean checkPrime(int n) { if (n != 0 && n != 1) { for (int j = 2; j * j <= n; ++j) { if (n % j == 0) { return false; } } return true; } else { return false; } } public static void dfs1(List<List<Integer>> g, boolean[] visited, Stack<Integer> stack, int num) { visited[num] = true; Iterator var4 = ((List) g.get(num)).iterator(); while (var4.hasNext()) { Integer integer = (Integer) var4.next(); if (!visited[integer]) { dfs1(g, visited, stack, integer); } } stack.push(num); } public static void dfs2(List<List<Integer>> g, boolean[] visited, List<Integer> list, int num, int c, int[] raj) { visited[num] = true; Iterator var6 = ((List) g.get(num)).iterator(); while (var6.hasNext()) { Integer integer = (Integer) var6.next(); if (!visited[integer]) { dfs2(g, visited, list, integer, c, raj); } } raj[num] = c; list.add(num); } public static int inputInt() throws IOException { return sc.nextInt(); } public static long inputLong() throws IOException { return sc.nextLong(); } public static double inputDouble() throws IOException { return sc.nextDouble(); } public static String inputString() throws IOException { return sc.readLine(); } public static void print(String a) throws IOException { bw.write(a); } public static void printSp(String a) throws IOException { bw.write(a + " "); } public static void println(String a) throws IOException { bw.write(a + "\n"); } public static long getAns(int[] ar, int c, long[][] dp, int i, int sign) { if (i < 0) { return 1L; } else if (c <= 0) { return 1L; } else { dp[i][c] = Math.max(dp[i][c], Math.max((long) ar[i] * getAns(ar, c - 1, dp, i - 1, sign), getAns(ar, c, dp, i - 1, 1))); return dp[i][c]; } } public static long power(long a, long b, long c) { long ans; for (ans = 1L; b != 0L; b /= 2L) { if (b % 2L == 1L) { ans *= a; ans %= c; } a *= a; a %= c; } return ans; } public static long power1(long a, long b, long c) { long ans; for (ans = 1L; b != 0L; b /= 2L) { if (b % 2L == 1L) { ans = multiply(ans, a, c); } a = multiply(a, a, c); } return ans; } public static long multiply(long a, long b, long c) { long res = 0L; for (a %= c; b > 0L; b /= 2L) { if (b % 2L == 1L) { res = (res + a) % c; } a = (a + a) % c; } return res % c; } public static long totient(long n) { long result = n; for (long i = 2L; i * i <= n; ++i) { if (n % i == 0L) { while (n % i == 0L) { n /= i; } result -= result / i; } } if (n > 1L) { result -= result / n; } return result; } public static long gcd(long a, long b) { return b == 0L ? a : gcd(b, a % b); } public static boolean[] primes(int n) { boolean[] p = new boolean[n + 1]; p[0] = false; p[1] = false; int i; for (i = 2; i <= n; ++i) { p[i] = true; } for (i = 2; i * i <= n; ++i) { if (p[i]) { for (int j = i * i; j <= n; j += i) { p[j] = false; } } } return p; } public String LargestEven(String S) { int[] count = new int[10]; int num; for (num = 0; num < S.length(); ++num) { ++count[S.charAt(num) - 48]; } num = -1; for (int i = 0; i <= 8; i += 2) { if (count[i] > 0) { num = i; break; } } StringBuilder ans = new StringBuilder(); for (int i = 9; i >= 0; --i) { int j; if (i != num) { for (j = 1; j <= count[i]; ++j) { ans.append(i); } } else { for (j = 1; j <= count[num] - 1; ++j) { ans.append(num); } } } if (num != -1 && count[num] > 0) { ans.append(num); } return ans.toString(); } static { bw = new BufferedWriter(new OutputStreamWriter(System.out)); team1 = 0; team2 = 0; minkicks = 10; } public static class Score { int l; String s; public Score(int l, String s) { this.l = l; this.s = s; } } public static class Ath { int r1; int r2; int r3; int r4; int r5; int index; public Ath(int r1, int r2, int r3, int r4, int r5, int index) { this.r1 = r1; this.r2 = r2; this.r3 = r3; this.r4 = r4; this.r5 = r5; this.index = index; } } static class Reader { private final int BUFFER_SIZE = 65536; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public Reader() { this.din = new DataInputStream(System.in); this.buffer = new byte[65536]; this.bufferPointer = this.bytesRead = 0; } public Reader(String file_name) throws IOException { this.din = new DataInputStream(new FileInputStream(file_name)); this.buffer = new byte[65536]; this.bufferPointer = this.bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt; byte c; for (cnt = 0; (c = this.read()) != -1 && c != 10; buf[cnt++] = (byte) c) { } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c; for (c = this.read(); c <= 32; c = this.read()) { } boolean neg = c == 45; if (neg) { c = this.read(); } do { ret = ret * 10 + c - 48; } while ((c = this.read()) >= 48 && c <= 57); return neg ? -ret : ret; } public long nextLong() throws IOException { long ret = 0L; byte c; for (c = this.read(); c <= 32; c = this.read()) { } boolean neg = c == 45; if (neg) { c = this.read(); } do { ret = ret * 10L + (long) c - 48L; } while ((c = this.read()) >= 48 && c <= 57); return neg ? -ret : ret; } public double nextDouble() throws IOException { double ret = 0.0D; double div = 1.0D; byte c; for (c = this.read(); c <= 32; c = this.read()) { } boolean neg = c == 45; if (neg) { c = this.read(); } do { ret = ret * 10.0D + (double) c - 48.0D; } while ((c = this.read()) >= 48 && c <= 57); if (c == 46) { while ((c = this.read()) >= 48 && c <= 57) { ret += (double) (c - 48) / (div *= 10.0D); } } return neg ? -ret : ret; } private void fillBuffer() throws IOException { this.bytesRead = this.din.read(this.buffer, this.bufferPointer = 0, 65536); if (this.bytesRead == -1) { this.buffer[0] = -1; } } private byte read() throws IOException { if (this.bufferPointer == this.bytesRead) { this.fillBuffer(); } return this.buffer[this.bufferPointer++]; } public void close() throws IOException { if (this.din != null) { this.din.close(); } } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
c8ae09b2f6494565ec91f13a58d2c3e9
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class ferrisWheel { static PrintWriter pw = new PrintWriter(System.out); static Scanner sc = new Scanner(System.in); public static int gcd(int x,int y) { return x==0?y:gcd(y%x, x); } public static void main(String[] args) throws IOException, InterruptedException { int n=sc.nextInt(); int maxN=(int)1e6; int []occ=new int[maxN+1]; for(int i=0;i<n;i++) occ[sc.nextInt()]++; int ans=-n; for(int i=1;i<=maxN;i++) { int g=0; for(int j=i;j<=maxN;j+=i) { if(occ[j]>0) { g=gcd(g, j); } } if(g==i) ans++; } pw.println(ans); pw.flush(); } static class pair implements Comparable<pair> { // long x,y; int x,y; public pair(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new 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; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws IOException { br = new BufferedReader(new FileReader(file)); } 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 String readAllLines(BufferedReader reader) throws IOException { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line); content.append(System.lineSeparator()); } return content.toString(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
802cc9cd8511cae101d30b114c182098
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collectors; public class D { static int SIZE = 1000001; public static void main(String[] args) { FastScanner sc = new FastScanner(System.in); FastPrintStream out = new FastPrintStream(System.out); int n = sc.nextInt(); boolean[] has = new boolean[SIZE]; for (int i = 0; i < n; i++) { int a = sc.nextInt(); has[a] = true; } int count = 0; for (int i = 1; i < SIZE; i++) { if (has[i]) { continue; } int gcd = i; int k = 2; int found = 0; while (k * i < SIZE) { if (has[k * i]) { found++; if (found == 1) { gcd = k * i; } else { gcd = gcd(gcd, k * i); } } k++; } if (found > 0 && gcd == i) { count++; } } out.println(count); out.flush(); } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } static int[] readIntArray(int n, FastScanner sc) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } return a; } static int[] sorted(int[] array) { ArrayList<Integer> list = new ArrayList<>(array.length); for (int val : array) { list.add(val); } list.sort(Comparator.naturalOrder()); return list.stream().mapToInt(val -> val).toArray(); } static int[] sortedReverse(int[] array) { ArrayList<Integer> list = new ArrayList<>(array.length); for (int val : array) { list.add(val); } list.sort(Comparator.reverseOrder()); return list.stream().mapToInt(val -> val).toArray(); } static long[] sort(long[] array) { ArrayList<Long> list = new ArrayList<>(array.length); for (long val : array) { list.add(val); } list.sort(Comparator.naturalOrder()); return list.stream().mapToLong(val -> val).toArray(); } static long[] sortedReverse(long[] array) { ArrayList<Long> list = new ArrayList<>(array.length); for (long val : array) { list.add(val); } list.sort(Comparator.reverseOrder()); return list.stream().mapToLong(val -> val).toArray(); } private static class FastPrintStream { private final BufferedWriter writer; public FastPrintStream(PrintStream out) { writer = new BufferedWriter(new OutputStreamWriter(out)); } public void print(char c) { try { writer.write(Character.toString(c)); } catch (IOException e) { e.printStackTrace(); } } public void print(int val) { try { writer.write(Integer.toString(val)); } catch (IOException e) { e.printStackTrace(); } } public void print(long val) { try { writer.write(Long.toString(val)); } catch (IOException e) { e.printStackTrace(); } } public void print(double val) { try { writer.write(Double.toString(val)); } catch (IOException e) { e.printStackTrace(); } } public void print(String val) { try { writer.write(val); } catch (IOException e) { e.printStackTrace(); } } public void println(char c) { print(c + "\n"); } public void println(int val) { print(val + "\n"); } public void println(long val) { print(val + "\n"); } public void println(double val) { print(val + "\n"); } public void println(String str) { print(str + "\n"); } public void println() { print("\n"); } public void flush() { try { writer.flush(); } catch (IOException e) { e.printStackTrace(); } } } private static class FastScanner { private final BufferedReader br; private StringTokenizer st; public FastScanner(InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); } 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 byte nextByte() { return Byte.parseByte(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
ce066f5cf403edadfa941dee46077d72
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class A { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<Integer> g[]; static long mod=(long) 998244353,INF=Long.MAX_VALUE; static boolean set[]; static int par[],col[],D[]; static long A[]; static int seg[]; static int dp[][]; public static void main(String args[])throws IOException { /* * star,rope,TPST * BS,LST,MS,MQ */ int N=i(); int A[]=input(N); int max=(int)2e6+1; boolean prime[]=new boolean[max]; for(int a:A)prime[a]=true; int c=0; for(int i=max-1; i>=1; i--) { if(prime[i]==false) { int g=0; for(int j=i+i; j<max; j+=i) { if(prime[j])g=(int)GCD(g,j); } if(g==i) { c++; prime[i]=true; } } } out.println(c); out.println(ans); out.close(); } static void f(int n,int last,int A[][],int f[]) { // print(f); for(int i:g[n]) { int b=A[i][0]^A[i][1]^n; // System.out.println(b+" "+n); if(f[i]==0) { //call for b f[i]=7-f[last]; f(b,i,A,f); } } } static int f(int N,int M,int x,int y) { N-=1; M-=1; N=Math.abs(N-x); M=Math.abs(M-y); int a=x+y; a=Math.min(a, x+M); a=Math.min(a, y+N); a=Math.min(a, N+M); return a; } static TreeNode start; public static void f(TreeNode root,TreeNode p,int r) { if(root==null)return; if(p!=null) { root.par=p; } if(root.val==r)start=root; f(root.left,root,r); f(root.right,root,r); } public static HashSet<Integer> st; public static int i=0; public static HashMap<Integer,Integer> mp=new HashMap<>(); public static TreeNode buildTree(int[] preorder, int[] inorder) { for(int i=0; i<preorder.length; i++)mp.put(inorder[i],i); TreeNode head=new TreeNode(); f(preorder,inorder,0,inorder.length-1,head); return head; } public static void f(int pre[],int in[],int l,int r,TreeNode root) { // System.out.println(pre[i]); root.val=pre[i]; int it=mp.get(pre[i++]);// // System.out.println(it); if(it-1>=l) { TreeNode left=new TreeNode(); root.left=left; f(pre,in,l,it-1,left); } if(it+1<=r) { TreeNode right=new TreeNode(); root.right=right; f(pre,in,it+1,r,right); } } static int right(int A[],int Limit,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<Limit)l=m; else r=m; } return l; } static int left(int A[],int a,int l,int r) { while(r-l>1) { int m=(l+r)/2; if(A[m]<a)l=m; else r=m; } return l; } static int f(int k,int x,int N) { int l=x-1,r=N; while(r-l>1) { int m=(l+r)/2; int a=ask(1,0,N-1,x,m); if(a<k) { l=m; } else r=m; } //System.out.println("-------"); if(r==N)return -1; return r; } static void build(int v,int tl,int tr,int A[]) { if(tl==tr) { seg[v]=A[tl]; return; } int tm=(tl+tr)/2; build(v*2,tl,tm,A); build(v*2+1,tm+1,tr,A); seg[v]=Math.max(seg[v*2],seg[v*2+1]); } static void update(int v,int tl,int tr,int index,int a) { if(index==tl && tl==tr) seg[v]=a; else { int tm=(tl+tr)/2; if(index<=tm)update(2*v,tl,tm,index,a); else update(2*v+1,tm+1,tr,index,a); seg[v]=Math.max(seg[v*2],seg[v*2+1]); } } static int ask(int v,int tl,int tr,int l,int r) { if(l>r)return -1; if(l==tl && tr==r)return seg[v]; int tm=(tl+tr)/2; return Math.max(ask(v*2,tl,tm,l,Math.min(tm, r)),ask(2*v+1,tm+1,tr,Math.max(tm+1, l),r)); } // static int query(long a,TreeNode root) // { // long p=1L<<30; // TreeNode temp=root; // while(p!=0) // { // System.out.println(a+" "+p); // if((a&p)!=0) // { // temp=temp.right; // // } // else temp=temp.left; // p>>=1; // } // return temp.index; // } // static void delete(long a,TreeNode root) // { // long p=1L<<30; // TreeNode temp=root; // while(p!=0) // { // if((a&p)!=0) // { // temp.right.cnt--; // temp=temp.right; // } // else // { // temp.left.cnt--; // temp=temp.left; // } // p>>=1; // } // } // static void insert(long a,TreeNode root,int i) // { // long p=1L<<30; // TreeNode temp=root; // while(p!=0) // { // if((a&p)!=0) // { // temp.right.cnt++; // temp=temp.right; // } // else // { // temp.left.cnt++; // temp=temp.left; // } // p>>=1; // } // temp.index=i; // } // static TreeNode create(int p) // { // // TreeNode root=new TreeNode(0); // if(p!=0) // { // root.left=create(p-1); // root.right=create(p-1); // } // return root; // } static boolean f(long A[],long m,int N) { long B[]=new long[N]; for(int i=0; i<N; i++) { B[i]=A[i]; } for(int i=N-1; i>=0; i--) { if(B[i]<m)return false; if(i>=2) { long extra=Math.min(B[i]-m, A[i]); long x=extra/3L; B[i-2]+=2L*x; B[i-1]+=x; } } return true; } static int f(int l,int r,long A[],long x) { while(r-l>1) { int m=(l+r)/2; if(A[m]>=x)l=m; else r=m; } return r; } static boolean f(long m,long H,long A[],int N) { long s=m; for(int i=0; i<N-1;i++) { s+=Math.min(m, A[i+1]-A[i]); } return s>=H; } static boolean f(int i,int j,long last,boolean win[]) { if(i>j)return false; if(A[i]<=last && A[j]<=last)return false; long a=A[i],b=A[j]; //System.out.println(a+" "+b); if(a==b) { return win[i] | win[j]; } else if(a>b) { boolean f=false; if(b>last)f=!f(i,j-1,b,win); return win[i] | f; } else { boolean f=false; if(a>last)f=!f(i+1,j,a,win); return win[j] | f; } } static long ask(long l,long r) { System.out.println("? "+l+" "+r); return l(); } static long f(long N,long M) { long s=0; if(N%3==0) { N/=3; s=N*M; } else { long b=N%3; N/=3; N++; s=N*M; N--; long a=N*M; if(M%3==0) { M/=3; a+=(b*M); } else { M/=3; M++; a+=(b*M); } s=Math.min(s, a); } return s; } static int ask(StringBuilder sb,int a) { System.out.println(sb+""+a); return i(); } static void swap(char X[],int i,int j) { char x=X[i]; X[i]=X[j]; X[j]=x; } static int min(int a,int b,int c) { return Math.min(Math.min(a, b), c); } static long and(int i,int j) { System.out.println("and "+i+" "+j); return l(); } static long or(int i,int j) { System.out.println("or "+i+" "+j); return l(); } static int len=0,number=0; static void f(char X[],int i,int num,int l) { if(i==X.length) { if(num==0)return; //update our num if(isPrime(num))return; if(l<len) { len=l; number=num; } return; } int a=X[i]-'0'; f(X,i+1,num*10+a,l+1); f(X,i+1,num,l); } static boolean is_Sorted(int A[]) { int N=A.length; for(int i=1; i<=N; i++)if(A[i-1]!=i)return false; return true; } static boolean f(StringBuilder sb,String Y,String order) { StringBuilder res=new StringBuilder(sb.toString()); HashSet<Character> set=new HashSet<>(); for(char ch:order.toCharArray()) { set.add(ch); for(int i=0; i<sb.length(); i++) { char x=sb.charAt(i); if(set.contains(x))continue; res.append(x); } } String str=res.toString(); return str.equals(Y); } static boolean all_Zero(int f[]) { for(int a:f)if(a!=0)return false; return true; } static long form(int a,int l) { long x=0; while(l-->0) { x*=10; x+=a; } return x; } static int count(String X) { HashSet<Integer> set=new HashSet<>(); for(char x:X.toCharArray())set.add(x-'0'); return set.size(); } static int f(long K) { long l=0,r=K; while(r-l>1) { long m=(l+r)/2; if(m*m<K)l=m; else r=m; } return (int)l; } // static void build(int v,int tl,int tr,long A[]) // { // if(tl==tr) // { // seg[v]=A[tl]; // } // else // { // int tm=(tl+tr)/2; // build(v*2,tl,tm,A); // build(v*2+1,tm+1,tr,A); // seg[v]=Math.min(seg[v*2], seg[v*2+1]); // } // } static int [] sub(int A[],int B[]) { int N=A.length; int f[]=new int[N]; for(int i=N-1; i>=0; i--) { if(B[i]<A[i]) { B[i]+=26; B[i-1]-=1; } f[i]=B[i]-A[i]; } for(int i=0; i<N; i++) { if(f[i]%2!=0)f[i+1]+=26; f[i]/=2; } return f; } static int[] f(int N) { char X[]=in.next().toCharArray(); int A[]=new int[N]; for(int i=0; i<N; i++)A[i]=X[i]-'a'; return A; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { if(par[a]>par[b]) //this means size of a is less than that of b { int t=b; b=a; a=t; } par[a]+=par[b]; par[b]=a; } } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } static void setGraph(int N) { par=new int[N+1]; D=new int[N+1]; g=new ArrayList[N+1]; set=new boolean[N+1]; col=new int[N+1]; for(int i=0; i<=N; i++) { col[i]=-1; g[i]=new ArrayList<>(); // D[i]=Integer.MAX_VALUE; } } static long pow(long a,long b) { //long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static int kadane(int A[]) { int lsum=A[0],gsum=A[0]; for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(boolean A[][]) { for(boolean a[]:A)print(a); } static void print(long A[][]) { for(long a[]:A)print(a); } static void print(int A[][]) { for(int a[]:A)print(a); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } } class segNode { long pref,suff,sum,max; segNode(long a,long b,long c,long d) { pref=a; suff=b; sum=c; max=d; } } //class TreeNode //{ // int cnt,index; // TreeNode left,right; // TreeNode(int c) // { // cnt=c; // index=-1; // } // TreeNode(int c,int index) // { // cnt=c; // this.index=index; // } //} class post implements Comparable<post> { long x,y,d,t; post(long a,long b,long c) { x=a; y=b; d=c; } public int compareTo(post X) { if(X.t==this.t) { return 0; } else { long xt=this.t-X.t; if(xt>0)return 1; return -1; } } } class TreeNode { int val; TreeNode left, right,par; TreeNode() {} TreeNode(int item) { val = item; left =null; right = null; par=null; } } class edge { int a,wt; edge(int a,int w) { this.a=a; wt=w; } } //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
bc0496fc823fa08f6626416311627a1f
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class code{ public static int GCD(int a, int b) { if (b == 0) return a; return GCD(b, a % b); } //@SuppressWarnings("unchecked") public static void main(String[] arg) throws IOException{ //Reader in=new Reader(); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(System.in); int t=1; int max=(int)1e6+1; boolean[] flag=new boolean[max]; while(t-- > 0){ int n=in.nextInt(); int count=0; for(int i=0;i<n;i++){ int k=in.nextInt(); flag[k]=true; } for(int i=max-1;i>0;i--){ int g=0; for(int j=i;j<max;j+=i){ if(flag[j]){ g=GCD(g,j); } } if(i==g){ flag[i]=true; count++; } } out.println(count-n); } out.flush(); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
d2fa0693baf5055c2e31a86d041e2402
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Random; import java.util.Scanner; import java.io.BufferedReader; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.*; import java.io.*; public class Problem_D { public static void main(String[] dummy) { MyScanner ms = new MyScanner(); PrintStream out = new PrintStream(System.out); int N = ms.nextInt(); int[] A = ms.readArray(N); int max_ele = 0; for (int i : A) max_ele = max(max_ele, i); boolean[] present = new boolean[max_ele + 1]; int[] G = new int[max_ele + 1]; int total = 0; for (int a : A) present[a] = true; for (int factor = 1; factor <= max_ele; factor++) { for (int multiple = factor; multiple <= max_ele; multiple += factor) if (present[multiple]) G[factor] = gcd(G[factor], multiple); total += G[factor] == factor ? 1 : 0; } out.println(total - N); out.flush(); out.close(); } private static int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } public static void Sort(int[] A) { // TODO : Collections.sort always uses Merge sort ArrayList<Integer> sorted = new ArrayList<>(); for (int x : A) sorted.add(x); Collections.sort(sorted); for (int i = 0; i < A.length; i++) A[i] = sorted.get(i); } public static void reverseSort(int[] A) { ArrayList<Integer> sorted = new ArrayList<>(); for (int x : A) sorted.add(x); Collections.sort(sorted, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { /* TODO :: Both are same actually :3 */ return b < a ? -1 : b == a ? 0 : 1; // return b - a; } }); for (int i = 0; i < A.length; i++) A[i] = sorted.get(i); } static class MyScanner { 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()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
581b62d1f2967df9b3ed1aaea300c45d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
// Main Code at the Bottom import java.util.*; import java.io.*; import java.sql.Time; public class Main implements Runnable{ //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; //env=true; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else 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 long MOD=(long)1e9+7; //debug static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Global variables and functions int gcd(int x, int y) { if(y == 0) return x; return gcd(y, x%y); } //Main function(The main code starts from here) public void run() { int test=1; //test=sc.nextInt(); while(test-->0) { int n = sc.nextInt(); int a[] = new int[n]; HashSet<Integer> set = new HashSet<>(); for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); set.add(a[i]); } int ans = 0; for(int i = 1000000; i >= 1; i--) { if(set.contains(i)) continue; int g = 0; for(int j = i; j <= 1000000; j+= i) { if(!set.contains(j)) continue; g = gcd(g, j); } if(g == i) ans++; } out.println(ans); } out.flush(); out.close(); } public static void main (String[] args) throws java.lang.Exception { new Thread(null, new Main(), "anything", (1<<28)).start(); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
8fdb8e0adf112391181ac36b63776d43
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.beans.DesignMode; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.CompletableFuture.AsynchronousCompletionTask; import org.xml.sax.ErrorHandler; import java.io.PrintStream; import java.io.PrintWriter; import java.io.DataInputStream; public class Solution { //TEMPLATE ------------------------------------------------------------------------------------- public static boolean Local(){ try{ return System.getenv("LOCAL_SYS")!=null; }catch(Exception e){ return false; } } public static boolean LOCAL; static class FastScanner { BufferedReader br; StringTokenizer st ; FastScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } FastScanner(String file) { try{ br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); st = new StringTokenizer(""); }catch(FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("file not found"); e.printStackTrace(); } } String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String readLine() throws IOException{ return br.readLine(); } } static class Pair<T,X> { T first; X second; Pair(T first,X second){ this.first = first; this.second = second; } @Override public int hashCode(){ return Objects.hash(first,second); } @Override public boolean equals(Object obj){ return obj.hashCode() == this.hashCode(); } } static class TreeNode{ TreeNode left; TreeNode right; int min; int index; int l; int r; TreeNode(int l,int r){ this.l = l; this.r = r; } TreeNode(int l,int r,int min,int index){ this.l = l; this.r = r; this.min = min; this.index = index; } } static PrintStream debug = null; static long mod = (long)(Math.pow(10,9) + 7); //TEMPLATE -------------------------------------------------------------------------------------END// public static void main(String[] args) throws Exception { FastScanner s = new FastScanner(); LOCAL = Local(); //PrintWriter pw = new PrintWriter(System.out); if(LOCAL){ s = new FastScanner("src/input.txt"); PrintStream o = new PrintStream("src/sampleout.txt"); debug = new PrintStream("src/debug.txt"); System.setOut(o); // pw = new PrintWriter(o); } long mod = 1000000007; int tcr = 1;//s.nextInt(); StringBuilder sb = new StringBuilder(); for(int tc=0;tc<tcr;tc++){ int n = s.nextInt(); int arr[] = new int[n]; int present[] = new int[1000001]; for(int i=0;i<n;i++){ arr[i] = s.nextInt(); present[arr[i]] = 1; } int cnt = 0; for(int i=1;i<1000001;i++){ int gcd = 0; if(present[i]==1){continue;} for(int j=i;j<1000001;j+=i){ if(present[j]==1){ gcd = gcd(gcd,j); } } if(gcd == i){ cnt++; } } sb.append(cnt+"\n"); } print(sb.toString()); } public static List<int[]> print_prime_factors(int n){ List<int[]> list = new ArrayList<>(); for(int i=2;i<=(int)(Math.sqrt(n));i++){ if(n % i == 0){ int cnt = 0; while( (n % i) == 0){ n = n/i; cnt++; } list.add(new int[]{i,cnt}); } } if(n!=1){ list.add(new int[]{n,1}); } return list; } public static List<int[]> prime_factors(int n,List<Integer> sieve){ List<int[]> list = new ArrayList<>(); int index = 0; while(n > 1 && sieve.get(index) <= Math.sqrt(n)){ int curr = sieve.get(index); int cnt = 0; while((n % curr) == 0){ n = n/curr; cnt++; } if(cnt >= 1){ list.add(new int[]{curr,cnt}); } index++; } if(n > 1){ list.add(new int[]{n,1}); } return list; } public static boolean inRange(long r1,long r2,long val){ return ((val >= r1) && (val <= r2)); } static int len(long num){ return Long.toString(num).length(); } static long mulmod(long a, long b,long mod) { long ans = 0l; while(b > 0){ long curr = (b & 1l); if(curr == 1l){ ans = ((ans % mod) + a) % mod; } a = (a + a) % mod; b = b >> 1; } return ans; } public static void dbg(PrintStream ps,Object... o) throws Exception{ if(ps == null){ return; } Debug.dbg(ps,o); } public static long modpow(long num,long pow,long mod){ long val = num; long ans = 1l; while(pow > 0l){ long bit = pow & 1l; if(bit == 1){ ans = (ans * (val%mod))%mod; } val = (val * val) % mod; pow = pow >> 1; } return ans; } public static long pow(long num,long pow){ long val = num; long ans = 1l; while(pow > 0l){ long bit = pow & 1l; if(bit == 1){ ans = (ans * (val)); } val = (val * val); pow = pow >> 1; } return ans; } public static char get(int n){ return (char)('a' + n); } public static long[] sort(long arr[]){ List<Long> list = new ArrayList<>(); for(long n : arr){list.add(n);} Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i] = list.get(i); } return arr; } public static int[] sort(int arr[]){ List<Integer> list = new ArrayList<>(); for(int n : arr){list.add(n);} Collections.sort(list); for(int i=0;i<arr.length;i++){ arr[i] = list.get(i); } return arr; } // return the (index + 1) // where index is the pos of just smaller element // i.e count of elemets strictly less than num public static int justSmaller(long arr[],long num){ // System.out.println(num+"@"); int st = 0; int e = arr.length - 1; int ans = -1; while(st <= e){ int mid = (st + e)/2; if(arr[mid] >= num){ e = mid - 1; }else{ ans = mid; st = mid + 1; } } return ans + 1; } public static int justSmaller(int arr[],int num){ // System.out.println(num+"@"); int st = 0; int e = arr.length - 1; int ans = -1; while(st <= e){ int mid = (st + e)/2; if(arr[mid] >= num){ e = mid - 1; }else{ ans = mid; st = mid + 1; } } return ans + 1; } //return (index of just greater element) //count of elements smaller than or equal to num public static int justGreater(long arr[],long num){ int st = 0; int e = arr.length - 1; int ans = arr.length; while(st <= e){ int mid = (st + e)/2; if(arr[mid] <= num){ st = mid + 1; }else{ ans = mid; e = mid - 1; } } return ans; } public static int justGreater(int arr[],int num){ int st = 0; int e = arr.length - 1; int ans = arr.length; while(st <= e){ int mid = (st + e)/2; if(arr[mid] <= num){ st = mid + 1; }else{ ans = mid; e = mid - 1; } } return ans; } public static void println(Object obj){ System.out.println(obj.toString()); } public static void print(Object obj){ System.out.print(obj.toString()); } public static int gcd(int a,int b){ if(b == 0){return a;} return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0l){ return a; } return gcd(b,a%b); } public static int find(int parent[],int v){ if(parent[v] == v){ return v; } return parent[v] = find(parent, parent[v]); } public static List<Integer> sieve(){ List<Integer> prime = new ArrayList<>(); int arr[] = new int[100001]; Arrays.fill(arr,1); arr[1] = 0; arr[2] = 1; for(int i=2;i<100001;i++){ if(arr[i] == 1){ prime.add(i); for(long j = (i*1l*i);j<100001;j+=i){ arr[(int)j] = 0; } } } return prime; } static boolean isPower(long n,long a){ long log = (long)(Math.log(n)/Math.log(a)); long power = (long)Math.pow(a,log); if(power == n){return true;} return false; } private static int mergeAndCount(int[] arr, int l,int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } // Merge sort function private static int mergeSortAndCount(int[] arr, int l,int r) { // Keeps track of the inversion count at a // particular node of the recursion tree int count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left subarray count // + right subarray count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } static class Debug{ //change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable<T>) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}\n"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}\n"); return ret.toString(); } public static void dbg(PrintStream ps,Object... o) throws Exception { if(LOCAL) { System.setErr(ps); System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [\n"); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a428ec8065431ebf368da182689e4d82
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class Solution { public static class DSU { private int[] parent; private int totalGroup; public DSU(int n) { parent = new int[n]; totalGroup = n; for (int i = 0; i < n; i++) { parent[i] = i; } } public boolean union(int a, int b) { int parentA = findParent(a); int parentB = findParent(b); if (parentA == parentB) { return false; } totalGroup--; if (parentA < parentB) { this.parent[parentB] = parentA; } else { this.parent[parentA] = parentB; } return true; } public int findParent(int a) { if (parent[a] != a) { parent[a] = findParent(parent[a]); } return parent[a]; } public int getTotalGroup() { return totalGroup; } } public static void main(String[] args) throws Exception { int tc = 1; for (int i = 0; i < tc; i++) { solve(); } io.close(); } public static long gcd(long a, long b) { while (b != 0) { a %= b; long temp = a; a = b; b = temp; } return a; } private static void solve() throws Exception { int n = io.nextInt(); int LIMIT = (int) (1e6 + 1); boolean[] present = new boolean[LIMIT]; for (int i = 0; i < n; i++) { present[io.nextInt()] = true; } int ops = 0; for (int i = 1; i < LIMIT; i++) { int g = 0; for (int mul = i; mul < LIMIT; mul += i) { if (present[mul]) { g = (int) gcd(g, mul); } } if (!present[g] && g == i) { ops++; } } io.println(ops); } static boolean dfs(int parent, int curr, Map<Integer, List<Integer>> map, Map<String, Integer> path) { if (map.get(curr).size() > 2) return false; if (parent != -1) { int parentPath = path.getOrDefault(parent + " " + curr, 2); for (int child : map.get(curr)) { if (child == parent) continue; path.put(curr + " " + child, parentPath == 2 ? 5 : 2); path.put(child + " " + curr, parentPath == 2 ? 5 : 2); if (!dfs(curr, child, map, path)) { return false; } } } else { List<Integer> childs = map.get(curr); path.put(curr + " " + childs.get(0), 2); path.put(childs.get(0) + " " + curr, 2); if (!dfs(curr, childs.get(0), map, path)) { return false; } if (childs.size() == 2) { path.put(curr + " " + childs.get(1), 5); path.put(childs.get(1) + " " + curr, 5); if (!dfs(curr, childs.get(1), map, path)) { return false; } } } return true; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(a.length); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //-----------PrintWriter for faster output--------------------------------- public static FastIO io = new FastIO(); //-----------MyScanner class for faster input---------- static class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar, numChars; // standard input public FastIO() { this(System.in, System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } // to read in entire lines, replace c <= ' ' // with a function that checks whether c is a line break public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public String nextLine() { int c; do { c = nextByte(); } while (c < '\n'); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n'); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10 * res + c - '0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } } //-------------------------------------------------------- }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
b4d6d06a6edbb0e351725f5901d9cd27
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= (long)Math.pow(10,9); public void solve() throws IOException { int n = readInt(); boolean match[]= new boolean[1000001]; for(int i =0;i<n;i++) { int a = readInt(); match[a]= true; } int count =0; int gcd=0; for(int i =1000000;i>=1;i--) { if(match[i]) continue; gcd=0; for(int j =2*i;j<=1000000;j=j+i) { if(match[j]) gcd = gcd(gcd,j); } if(gcd==i) { // out.println(i); match[i]= true; count++; } } out.println(count); } public int gcd(int a , int b ) { if(a<b) { int t =a; a=b; b=t; } if(a==0) return b; if(b==0) return a; if(a%b==0) return b ; return gcd(b,a%b); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v ; int val; edge(int u1, int v1 , int val1) { this.u=u1; this.v=v1; this.val=val1; } public int compareTo(edge e) { return this.val-e.val; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4fbac2e86aa2ba72f214e48c69fb31f2
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
// package codeforces; import java.io.*; import java.util.*; public class practice { static FastScanner fs = new FastScanner(); public static final int N = 1000005; public static void main(String[] args) { int t = 1; // t = fs.nextInt(); for(int i=1;i<=t;i++) { solve(t); } } public static int gcd(int a,int b) { while(b > 0) { a %= b; int temp = a; a = b; b = temp; } return a; } @SuppressWarnings("unused") public static void solve(int tt) { int n = fs.nextInt(); int a[] = fs.readArray(n); boolean present[] = new boolean[N]; for(int i = 0; i < N; i++)present[i] = false; int ans = 0; for (int i = 0; i < n; i++) { present[a[i]] = true; } for (int i = N - 1; i > 0; i--) { int g = 0; for (int j = i; j < N; j += i) { if(present[j]) { g = gcd(j,g); } } if (g == i && !present[i]) { present[i] =true; ans++; } } System.out.println(ans); return; } public static int [] sortarray(int a[]) { ArrayList<Integer> L = new ArrayList<Integer>(); for(int i:a) { L.add(i); } Collections.sort(L); for(int i=0;i<L.size();i++)a[i]=L.get(i); return a; } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } ArrayList<Integer> readList(int n) { ArrayList<Integer> a = new ArrayList<Integer>(); int x; for(int i=0;i<n;i++) { x=fs.nextInt(); a.add(x); } return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
950d4f78ea04f6a69474fa1263ca2e79
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args)throws IOException { FastScanner scan = new FastScanner(); PrintWriter output = new PrintWriter(System.out); int n = scan.nextInt(); int arr[] = scan.readArray(n); int present[] = new int[1000002]; for(int i : arr) present[i] = 1; int count = 0; for(int i = 1;i<=1000000;i++) { int gcd = 0; for(int j = i;j<=1000000;j+=i) { if(present[j] == 1) gcd = gcd(gcd, j); } if(gcd == i) count++; } output.println(count-n); output.flush(); } public static int[] sort(int arr[]) { List<Integer> list = new ArrayList<>(); for(int i:arr) list.add(i); Collections.sort(list); for(int i = 0;i<list.size();i++) arr[i] = list.get(i); return arr; } public static int gcd(int a, int b) { if(a == 0) return b; return gcd(b%a, a); } public static void printArray(int arr[]) { for(int i:arr) System.out.print(i+" "); System.out.println(); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
57cd0a1a746cca02b7813fb4e6d6d31d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class Contest_yandexA{ static final int MAXN = (int)1e6; public static void main(String[] args) { Scanner input = new Scanner(System.in); /*int n = input.nextInt(); int k = input.nextInt(); k = k%4; int[] a = new int[n]; for(int i = 0;i<n;i++){ a[i] = input.nextInt(); } int[] count = new int[n]; int sum = 0; for(int tt = 0;tt<k;tt++){ for(int i = 0;i<n;i++){ count[a[i]-1]++; } for(int i = 0;i<n;i++){ sum+= count[i]; } for(int i = 0;i<n;i++){ a[i] = sum; sum-= count[i]; } } for(int i = 0;i<n;i++){ System.out.print(a[i] + " "); }*/ PrintWriter pw = new PrintWriter(System.out); int n = input.nextInt(); int[] count = new int[MAXN+1]; for(int i = 0;i<n;i++){ count[input.nextInt()]++; } int ans = 0; for(int i = 1;i<=MAXN;i++){ int gcd = 0; for(int j = i;j<=MAXN;j+=i){ if(count[j] > 0){ gcd = gcd(gcd,j); } } if(gcd == i){ ans++; } } pw.println(ans-n); pw.close(); } public static int gcd(int a,int b){ if(b == 0){ return a; } return gcd(b,a%b); } public static int lcm(int a,int b){ return (a / gcd(a, b)) * b; } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
c062579eb02ab45b6369bdbf127141a2
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 2e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = 998244353; static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static void solve() { int n = in.nextInt(); final int N = (int) 1e6 + 5; boolean[] a = new boolean[N]; for (int i = 0; i < n; i++) { a[in.nextInt()] = true; } int ans = 0; for (int i = 1; i < N; i++) { if (a[i]) continue; int g = 0; for (int j = i; j < N; j += i) { if (a[j]) g = gcd(g, j); } if (g == i) ans++; } out.println(ans); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int t = 1; // t = in.nextInt(); while (t-- > 0) { solve(); } out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
1390edc4968de19bdbdd83c3e807077c
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DNotAdding solver = new DNotAdding(); solver.solve(1, in, out); out.close(); } static class DNotAdding { int gcd(int a, int b) { if (b == 0) return a; return (gcd(b, a % b)); } public void solve(int testNumber, InputReader s, PrintWriter w) { int n = s.nextInt(); int m = (int) 1e6; int[] a = new int[m + 1]; for (int i = 0; i < n; i++) a[s.nextInt()] = 1; int res = 0; for (int i = m; i >= 1; i--) { if (a[i] == 1) continue; int v = -1; for (int j = 2; i * j <= m; j++) { if (a[i * j] == 0) continue; if (v == -1) v = j; else v = gcd(v, j); } if (v == 1) a[i] = 1; res += a[i]; } w.println(res); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
3197f12b854683d876c4118fa1d13003
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class D1627{ static FastScanner fs = null; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = fs.nextInt(); int N = 1000005; int a[] = new int[n]; boolean vis[] = new boolean[N]; for(int i=0;i<n;i++){ a[i] = fs.nextInt(); vis[a[i]] = true; } int ans = 0; for(int i=N-1;i>0;i--){ int g = 0; for(int j=i;j<N;j+=i){ if(vis[j]) g = gc(g,j); } if(g==i){ // out.println(i+" -- "); vis[i] = true; ans+=1; } } int x = ans-n; out.println(x); out.close(); } static int gc(int a,int b){ if(a==0){ return b; } return gc(b%a,a); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
f386ba78603e665552edb96831920437
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class tr1 { static PrintWriter out; static StringBuilder sb; static long mod = 998244353; static Boolean[] memo; static int n, m, id, c; static ArrayList<int[]>[] ad; static HashMap<Integer, Integer>[] going; static long inf = Long.MAX_VALUE; static char[][] g; static boolean[][] vis; static int[] ans, arr[], per; static int h, w; static HashMap<Integer, int[]> hmC, hmG; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int n = sc.nextInt(); boolean[] h = new boolean[1000001]; for (int i = 0; i < n; i++) h[sc.nextInt()] = true; int ans = 0; // seive(1000001); for (int i = h.length - 1; i >= 1; i--) { if (!h[i]) { ArrayList<Integer> ar = new ArrayList<>(); for (int j = i + i; j < h.length; j += i) { if (h[j]) { ar.add(j / i); } } int num = 0; int l = -1; for (int x : ar) { if (l != -1) { if (gcd(x, l) == 1) { h[i] = true; ans++; break; } } l = x; } } } System.out.println(ans); out.flush(); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int[] si; static ArrayList<Integer> primes; static void seive(int N) { si = new int[N]; primes = new ArrayList<>(); si[1] = 1; for (int i = 2; i < N; i++) { if (si[i] == 0) { si[i] = i; primes.add(i); } for (int j = 0; j < primes.size() && primes.get(j) <= si[i] && (i * primes.get(j)) < N; j++) si[primes.get(j) * i] = primes.get(j); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
3b0e2129c6b9446b7fec0af7154d2320
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class problemD { public static void main(String[] args)throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); boolean[] exist = new boolean[1000001]; StringTokenizer st = new StringTokenizer(br.readLine()); int cnt = 0; for(int i=0; i<n; i++) { exist[Integer.parseInt(st.nextToken())] = true; cnt++; } for(int i =500000; i>0; i--) { if(!exist[i]) { ArrayList<Integer> list = new ArrayList<>(); for(int j=2*i; j<=1000000; j+=i) { if(exist[j]) { for(int k=0; k<list.size(); k++) { int x = j/i; int y = list.get(k); while(x>0&&y>0) { if(x<y) y-=x*(y/x); else x-=y*(x/y); } if(Math.max(x, y)==1) { exist[i]= true; cnt++; break; } } list.add(j/i); if(exist[i]) break; } } } } out.write(cnt-n+"\n"); out.flush(); out.close(); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4ae8592724329b6e49c3b20abdfbd46f
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CF1627D { private static int gcd(int x, int y) { if (y == 0) { return x; } return gcd(y, x % y); } public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] buffer; buffer = reader.readLine().split(" "); int n = Integer.parseInt(buffer[0]); int[] a = new int[n]; boolean[] b; int max = 0; buffer = reader.readLine().split(" "); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(buffer[i]); max = Math.max(max, a[i]); } b = new boolean[max + 1]; for (int i = 0; i < n; i++) { b[a[i]] = true; } int ans = 0; for (int i = max; i > 0; i--) { if (b[i]) { continue; } int g = 0; for (int j = 2; i * j <= max; j++) { if (b[i * j]) { g = gcd(j, g); } } if (g == 1) { b[i] = true; ans++; } } System.out.println(ans); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
7a6ebfa664fbea59844d9c987ce3d7d0
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.util.Map.*; import static java.util.Arrays.*; import static java.util.Collections.*; import static java.lang.System.*; public class Main { public void tq() throws Exception { st=new StringTokenizer(bq.readLine()); int tq=1; //sb=new StringBuilder(2000000); o: while(tq-->0) { int n=i(); int ar[]=ari(n); boolean f[]=new boolean[1000001]; for(int x:ar)f[x]=true; int c=0; for(int x=1000000;x>0;x--) { if(!f[x]) { int g=-1; for(int y=2*x;y<=1000000;y+=x) { if(f[y]) { if(g==-1)g=y; else { g=gcd(y,g); if(g==x) { c++; f[x]=true; break; } } } } } } pl(c); } //p(sb); } long mod=1000000007l; int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;long maxl=Long.MAX_VALUE,minl=Long.MIN_VALUE; BufferedReader bq = new BufferedReader(new InputStreamReader(in));StringTokenizer st;StringBuilder sb; public static void main(String[] a)throws Exception{new Main().tq();} int di[][]={{-1,0},{1,0},{0,-1},{0,1}}; int de[][]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}}; void f(){out.flush();} int p(int i,int p[]){return p[i]<0?i:(p[i]=p(p[i],p));} boolean c(int x,int y,int n,int m){return x>=0&&x<n&&y>=0&&y<m;} int[] so(int ar[]) { Integer r[] = new Integer[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } long[] so(long ar[]) { Long r[] = new Long[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } char[] so(char ar[]) { Character r[] = new Character[ar.length]; for (int x = 0; x < ar.length; x++) r[x] = ar[x]; sort(r); for (int x = 0; x < ar.length; x++) ar[x] = r[x]; return ar; } void p(Object p) {out.print(p);}void pl(Object p) {out.println(p);}void pl() {out.println();} void s(String s) {sb.append(s);} void s(int s) {sb.append(s);} void s(long s) {sb.append(s);} void s(char s) {sb.append(s);} void s(double s) {sb.append(s);} void ss() {sb.append(' ');} void sl(String s) {s(s);sb.append("\n");} void sl(int s) {s(s);sb.append("\n");} void sl(long s) {s(s);sb.append("\n");} void sl(char s) {s(s);sb.append("\n");} void sl(double s) {s(s);sb.append("\n");} void sl() {sb.append("\n");} int l(int v) {return 31 - Integer.numberOfLeadingZeros(v);} long l(long v) {return 63 - Long.numberOfLeadingZeros(v);} int sq(int a) {return (int) sqrt(a);} long sq(long a) {return (long) sqrt(a);} int gcd(int a, int b) { while (b > 0) { int c = a % b; a = b; b = c; } return a; } long gcd(long a, long b) { while (b > 0l) { long c = a % b; a = b; b = c; } return a; } boolean p(String s, int i, int j) { while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false; return true; } boolean[] si(int n) { boolean bo[] = new boolean[n + 1]; bo[0] = bo[1] = true; for (int x = 4; x <= n; x += 2) bo[x] = true; for (int x = 3; x * x <= n; x += 2) { if (!bo[x]) { int vv = (x << 1); for (int y = x * x; y <= n; y += vv) bo[y] = true; } } return bo; } long mul(long a, long b, long m) { long r = 1l; a %= m; while (b > 0) { if ((b & 1) == 1) r = (r * a) % m; b >>= 1; a = (a * a) % m; } return r; } int i() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Integer.parseInt(st.nextToken()); } long l() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Long.parseLong(st.nextToken()); } String s() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return st.nextToken(); } double d() throws IOException { if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); return Double.parseDouble(st.nextToken()); } void s(int a[]) { for (int e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(long a[]) { for (long e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(char a[]) { for (char e : a){sb.append(e);sb.append(' ');} sb.append("\n"); } void s(int ar[][]) {for (int a[] : ar) s(a);} void s(long ar[][]) {for (long a[] : ar) s(a);} void s(char ar[][]) {for (char a[] : ar) s(a);} int[] ari(int n) throws IOException { int ar[] = new int[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Integer.parseInt(st.nextToken()); return ar; } long[] arl(int n) throws IOException { long ar[] = new long[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Long.parseLong(st.nextToken()); return ar; } char[] arc(int n) throws IOException { char ar[] = new char[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = st.nextToken().charAt(0); return ar; } double[] ard(int n) throws IOException { double ar[] = new double[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = Double.parseDouble(st.nextToken()); return ar; } String[] ars(int n) throws IOException { String ar[] = new String[n]; if (!st.hasMoreTokens()) st = new StringTokenizer(bq.readLine()); for (int x = 0; x < n; x++) ar[x] = st.nextToken(); return ar; } int[][] ari(int n, int m) throws IOException { int ar[][] = new int[n][m]; for (int x = 0; x < n; x++)ar[x]=ari(m); return ar; } long[][] arl(int n, int m) throws IOException { long ar[][] = new long[n][m]; for (int x = 0; x < n; x++)ar[x]=arl(m); return ar; } char[][] arc(int n, int m) throws IOException { char ar[][] = new char[n][m]; for (int x = 0; x < n; x++)ar[x]=arc(m); return ar; } double[][] ard(int n, int m) throws IOException { double ar[][] = new double[n][m]; for (int x = 0; x < n; x++)ar[x]=ard(m); return ar; } void p(int ar[]) { sb = new StringBuilder(11 * ar.length); for (int a : ar) {sb.append(a);sb.append(' ');} out.println(sb); } void p(long ar[]) { StringBuilder sb = new StringBuilder(20 * ar.length); for (long a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(double ar[]) { StringBuilder sb = new StringBuilder(22 * ar.length); for (double a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(char ar[]) { StringBuilder sb = new StringBuilder(2 * ar.length); for (char aa : ar){sb.append(aa);sb.append(' ');} out.println(sb); } void p(String ar[]) { int c = 0; for (String s : ar) c += s.length() + 1; StringBuilder sb = new StringBuilder(c); for (String a : ar){sb.append(a);sb.append(' ');} out.println(sb); } void p(int ar[][]) { StringBuilder sb = new StringBuilder(11 * ar.length * ar[0].length); for (int a[] : ar) { for (int aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(long ar[][]) { StringBuilder sb = new StringBuilder(20 * ar.length * ar[0].length); for (long a[] : ar) { for (long aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(double ar[][]) { StringBuilder sb = new StringBuilder(22 * ar.length * ar[0].length); for (double a[] : ar) { for (double aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void p(char ar[][]) { StringBuilder sb = new StringBuilder(2 * ar.length * ar[0].length); for (char a[] : ar) { for (char aa : a){sb.append(aa);sb.append(' ');} sb.append("\n"); } p(sb); } void pl(Object... ar) {for (Object e : ar) p(e + " ");pl();} }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
d4c16929beca4df5694ef9f2e3b837cd
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Solution { // VM options: -Xmx1024m -Xss1024m private void solve() throws IOException { int n = nextInt(); int SZ = 1000013; boolean[] b = new boolean[SZ]; for (int i = 0; i < n; i++) { b[nextInt()] = true; } int res = 0; for (int i = SZ - 1; i > 0; i--) { if (!b[i]) { int g = 0; for (int j = i * 2; j < SZ; j += i) { if (b[j]) { g = gcd(g, j); } } if (g == i) { b[i] = true; res++; } } } out.println(res); } private int gcd(int a, int b) { while (a != 0 && b != 0) { if (a > b) { a %= b; } else { b %= a; } } return a + b; } private static final String inputFilename = "input.txt"; private static final String outputFilename = "output.txt"; private BufferedReader in; private StringTokenizer line; private PrintWriter out; private final boolean isDebug; private Solution(boolean isDebug) { this.isDebug = isDebug; } public static void main(String[] args) throws IOException { new Solution(Arrays.asList(args).contains("DEBUG_MODE")).run(args); } private void run(String[] args) throws IOException { if (isDebug) { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilename))); // in = new BufferedReader(new InputStreamReader(System.in)); } else { in = new BufferedReader(new InputStreamReader(System.in)); } out = new PrintWriter(System.out); // out = new PrintWriter(outputFilename); int t = isDebug ? nextInt() : 1; // int t = 1; // int t = nextInt(); for (int i = 0; i < t; i++) { // out.print("Case #" + (i + 1) + ": "); solve(); out.flush(); } in.close(); out.flush(); out.close(); } private void println(Object... objects) { boolean isFirst = true; for (Object o : objects) { if (!isFirst) { out.print(" "); } else { isFirst = false; } out.print(o.toString()); } out.println(); } private int[] nextIntArray(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } private long[] nextLongArray(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (line == null || !line.hasMoreTokens()) { line = new StringTokenizer(in.readLine()); } return line.nextToken(); } private static void assertPredicate(boolean p) { if (!p) { throw new RuntimeException(); } } private static void assertPredicate(boolean p, String message) { if (!p) { throw new RuntimeException(message); } } private static void assertNotEqual(int unexpected, int actual) { if (actual == unexpected) { throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual); } } private static void assertEqual(int expected, int actual) { if (expected != actual) { throw new RuntimeException("assertEqual: " + expected + " != " + actual); } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
7d4d14a88b627a8a95e35acff6df91f9
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { new MainClass().main(); } } class MainClass { Scanner in = new Scanner(System.in); PrintStream out = System.out; long ways[] = new long[1000007]; boolean[] poss = new boolean[1000007]; public void main() { int n = in.nextInt(); for (int ind = 0; ind < n; ind++) { int x = in.nextInt(); poss[x] = true; } int x = 1000000; int result = 0; while (x >= 1) { long tot = 0; int y = x + x; while (y <= 1000000) { if (poss[y]) { tot = tot + 1; ways[x] = ways[x] - ways[y]; } y += x; } ways[x] = ways[x] + tot * (tot - 1) / 2; if (poss[x] == true) { ways[x] = ways[x] + tot; result = result + 1; } else if (ways[x] > 0) { poss[x] = true; ways[x] = ways[x] + tot; result = result + 1; } x -= 1; } System.out.println(result - n); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
9ac6394754bfd96e00264175988b00be
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { new MainClass().main(); } } class MainClass { Scanner in = new Scanner(System.in); PrintStream out = System.out; final int N = 1000000; long cnt[] = new long[N + 1]; boolean[] can = new boolean[N + 1]; public void main() { int n = in.nextInt(); for (int i = 0; i < n; i++) { int x = in.nextInt(); can[x] = true; } int ans = 0; for (int x = N; x >= 1; x--) { long c = 0; for (int y = x * 2; y <= N; y += x) { if (can[y]) { c++; cnt[x] -= cnt[y]; } } cnt[x] += c * (c - 1) / 2; if (cnt[x] > 0 || can[x]) { can[x] = true; cnt[x] += c; } if (can[x]) { ans++; } } out.println(ans - n); } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
08084a515cbb106ef4e6f83059485810
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
/** * check out my youtube channel sh0rkyboy * https://tinyurl.com/zdxe2y4z * I do screencasts, solutions, and other fun stuff in the future */ import java.util.*; import java.io.*; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.Math.max; public class EdD { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner sc; public static PrintWriter out; public static void main(String[] largewang) throws Exception{ // TODO Auto-generated method stub sc = new MyScanner(); out = new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = readArrayInt(n); int[] seen = new int[1000001]; for (int j : arr) { seen[j] = 1; } int count = 0; for (int j = 1000000;j>=1;j--){ if (seen[j] == 1) continue; int gcd = 0; for (int k = 2*j;k<=1000000;k+=j) { if (seen[k] == 1) gcd = gcd(k, gcd); } if (gcd == j) { count++; seen[j] = 1; } } out.println(count); out.close(); }public static int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b); } public static void sort(int[] array){ ArrayList<Integer> copy = new ArrayList<>(); for (int i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = sc.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = sc.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = sc.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = sc.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } public static int power(long x, long y, long mod){ long ans = 1; while(y>0){ if (y%2==1) ans = (ans*x)%mod; x = (x*x)%mod; y/=2; } return (int)(ans); } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } 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; } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
4e2c78208c803c84c74faae8e67709bb
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; import java.math.*; public class Main { static void deal(int n,int[] arr) { int max = 0; for(int i=0;i<n;i++) { max = Math.max(arr[i]+1,max); } boolean[] used = new boolean[max]; for(int i=0;i<n;i++) { used[arr[i]] = true; } int cnt = 0; for(int i=1;i<=max/3;i++) { if(used[i]) continue; int g = 0; int j =2; while(j*i<max && g != 1) { if(used[j*i]) { g = gcd(g,j); } j++; } if(g==1) cnt++; } out.println(cnt); } static int gcd(int a,int b) { while(b>0) { int c = a % b; a = b; b = c; } return a; } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) { arr[i] = sc.nextInt(); } deal(n,arr); out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int 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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
0689f491715dab06038c6164c82aefd8
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class codeforces { public static void main(String[] args) throws Exception { int n=sc.nextInt(); int[]a=new int[1000009]; for(int i=0;i<n;i++) { a[sc.nextInt()]++; } int[]b=new int[1000009]; for(int i=1;i<1000009;i++) { for(int j=i;j<1000009;j+=i) { b[i]+=a[j]; } } int ans=-n; Process:for(int i=1;i<1000009;i++) { for(int j=2*i;j<1000009;j+=i) { if(b[j]==b[i])continue Process; } ans+=b[i]!=0?1:0; } pw.println(ans); pw.close(); } 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; } } } 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\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
7611efa066da5c23ce2abc23e777539d
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.util.*; import java.io.*; public class D1627 { static final int MAXN = (int) 1e6; public static int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] cnt = new int[MAXN + 1]; for (int i = 0; i < n; i++) { cnt[sc.nextInt()]++; } int ans = 0; for (int i = 1; i <= MAXN; i++) { int gcd = 0; for (int j = i; j <= MAXN; j += i) { if (cnt[j] > 0) { gcd = gcd(gcd, j); } } if(gcd == i) ans++; } pw.println(ans - n); pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
f20d1cdcfc04e4856f18f2aad53f4206
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
/* Setting up my ambitions Check 'em one at a time, yeah, I made it Now it's time for ignition I'm the start, heat it up They follow, burning up a chain reaction, oh-oh-oh Go fire it up, oh, oh, no Assemble the crowd now, now Line 'em up on the ground No leaving anyone behind */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1627D { static final int MAX = 1000000; public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int N = infile.nextInt(); int[] arr = infile.nextInts(N); boolean[] seen = new boolean[MAX+1]; for(int x: arr) seen[x] = true; int res = 0; for(int v=MAX; v >= 1; v--) if(!seen[v]) { int gcd = 0; for(int x=v+v; x <= MAX; x+=v) if(seen[x]) gcd = gcd(gcd, x/v); if(gcd == 1) { seen[v] = true; res++; } } System.out.println(res); } public static int gcd(int a, int b) { if(a > b) a = (a+b)-(b=a); if(a == 0) return b; return gcd(b%a, a); } } /* ab, bc, ca gcd(bc,ca) = c gcd(ab, c) = 1 */ 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
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
b9c6ff809ef0c6a24fe084a8b422bfb3
train_109.jsonl
1642257300
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
256 megabytes
import java.io.*; import java.util.*; public class A { static int Max = (int) 1e6 + 1; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); boolean[] active = new boolean[Max + 1]; long[] ps = new long[Max + 1]; for (int i = 0; i < n; i++) { active[sc.nextInt()] = true; } int ans = 0; for (int i = Max; i >= 1; i--) { long c = 0; long sub = 0; for (int j = i; j <= Max; j += i) { if (active[j]) c++; sub += ps[j]; } ps[i] = (c * (c - 1)) / 2 - sub; if (ps[i] > 0) { if (!active[i]) { active[i] = true; ps[i] += c; } } if (active[i]) ans++; } pw.println(ans - n); pw.flush(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["5\n4 20 1 25 30", "3\n6 10 15"]
2 seconds
["3", "4"]
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
Java 8
standard input
[ "brute force", "dp", "math", "number theory" ]
1a37e42263fdd1cb62e2a18313eed989
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
1,900
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
standard output
PASSED
a51f5d1be9a432ca9a80b47485b2ca96
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.*; import java.util.*; public final class Main { //int 2e8 - long 9e18 static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)}; static int mod = (int) (1e9 + 7); static int mod2 = 998244353; public static void main(String[] args) { int tt = i(); while (tt-- > 0) { solve(); } out.flush(); } public static void solve() { int n = i(); int m = i(); int k = i(); int[] x = input(n); TreeSet<Integer>[] p = new TreeSet[n]; for (int i = 0; i < n; i++) { p[i] = new TreeSet<>(); } p[0].add(0); p[n - 1].add(m - 1); List<int[]>[] lad = new List[n]; for (int i = 0; i < n; i++) { lad[i] = new ArrayList<>(); } for (int i = 0; i < k; i++) { int[] l = new int[]{i() - 1, i() - 1, i() - 1, i() - 1, i()}; lad[l[0]].add(l); p[l[0]].add(l[1]); p[l[2]].add(l[3]); } int[][] pp = new int[n][]; long[][] dp = new long[n][]; for (int i = 0; i < n; i++) { int size = p[i].size(); pp[i] = new int[size]; dp[i] = new long[size]; Arrays.fill(dp[i], (long) 1e18); for (int j = 0; j < size; j++) { pp[i][j] = p[i].pollFirst(); } } dp[0][0] = 0; for (int i = 0; i < n; i++) { int len = dp[i].length; for (int j = 0; j + 1 < len; j++) { dp[i][j + 1] = Math.min(dp[i][j + 1], dp[i][j] + (long) x[i] * (pp[i][j + 1] - pp[i][j])); } for (int j = len - 1; j - 1 >= 0; j--) { dp[i][j - 1] = Math.min(dp[i][j - 1], dp[i][j] + (long) x[i] * (pp[i][j] - pp[i][j - 1])); } for (int[] l : lad[i]) { int z = lowerbound(pp[l[0]], l[1]); int y = lowerbound(pp[l[2]], l[3]); dp[l[2]][y] = Math.min(dp[l[2]][y], dp[l[0]][z] - l[4]); } } long ans = dp[n - 1][dp[n - 1].length - 1]; if (ans < 1e17) { out.println(ans); } else { out.println("NO ESCAPE"); } } static int lowerbound(int[] a, int x) { int l = 0; int r = a.length - 1; while (l < r) { int m = (l + r + 1) / 2; if (a[m] <= x) { l = m; } else { r = m - 1; } } return l; } static long sum(int[] a) { long sum = 0; for (int x : a) { sum += x; } return sum; } static long[] pre(int[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static long[] post(int[] a) { long[] post = new long[a.length + 1]; post[0] = 0; for (int i = 0; i < a.length; i++) { post[i + 1] = post[i] + a[a.length - 1 - i]; } return post; } static long[] pre(long[] a) { long[] pre = new long[a.length + 1]; pre[0] = 0; for (int i = 0; i < a.length; i++) { pre[i + 1] = pre[i] + a[i]; } return pre; } static void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static double d() { return in.nextDouble(); } static String s() { return in.nextLine(); } static String c() { return in.next(); } static int[][] inputWithIdx(int N) { int A[][] = new int[N][2]; for (int i = 0; i < N; i++) { A[i] = new int[]{i, in.nextInt()}; } return A; } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long LCM(int a, int b) { return (long) a / GCD(a, b) * b; } static long LCM(long a, long b) { return a / GCD(a, b) * b; } static void uniqueAndSort(int[] arr) { TreeSet<Integer> treeSet = new TreeSet<>(); for (int x : arr) { treeSet.add(x); } arr = new int[treeSet.size()]; int id = 0; while (treeSet.size() > 0) { arr[id++] = treeSet.pollFirst(); } } static void shuffle(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } } static void shuffleAndSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int[] temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr, comparator); } static void shuffleAndSort(long[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); long temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static boolean isPerfectSquare(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static void swap(char A[], int a, int b) { char t = A[a]; A[a] = A[b]; A[b] = t; } static long pow(long a, long b, int mod) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } static long pow(long a, long b) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow *= x; } x = x * x; b /= 2; } return pow; } static long modInverse(long x, int mod) { return pow(x, mod - 2, mod); } static boolean isPrime(long N) { if (N <= 1) { return false; } if (N <= 3) { return true; } if (N % 2 == 0 || N % 3 == 0) { return false; } for (int i = 5; i * i <= N; i = i + 6) { if (N % i == 0 || N % (i + 2) == 0) { return false; } } return true; } public static String reverse(String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); } public static void reverse(int[] arr) { for (int i = 0; i < arr.length / 2; i++) { int tmp = arr[i]; arr[arr.length - 1 - i] = tmp; arr[i] = arr[arr.length - 1 - i]; } } public static String repeat(char ch, int repeat) { if (repeat <= 0) { return ""; } final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } public static int[] manacher(String s) { char[] chars = s.toCharArray(); int n = s.length(); int[] d1 = new int[n]; for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1); while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) { k++; } d1[i] = k--; if (i + k > r) { l = i - k; r = i + k; } } return d1; } public static int[] kmp(String s) { int n = s.length(); int[] res = new int[n]; for (int i = 1; i < n; ++i) { int j = res[i - 1]; while (j > 0 && s.charAt(i) != s.charAt(j)) { j = res[j - 1]; } if (s.charAt(i) == s.charAt(j)) { ++j; } res[i] = j; } return res; } } class Pair { int i; int j; Pair(int i, int j) { this.i = i; this.j = j; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return i == pair.i && j == pair.j; } @Override public int hashCode() { return Objects.hash(i, j); } } class ThreePair { int i; int j; int k; ThreePair(int i, int j, int k) { this.i = i; this.j = j; this.k = k; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ThreePair pair = (ThreePair) o; return i == pair.i && j == pair.j && k == pair.k; } @Override public int hashCode() { return Objects.hash(i, j); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class Node { int val; public Node(int val) { this.val = val; } } class ST { int n; Node[] st; ST(int n) { this.n = n; st = new Node[4 * Integer.highestOneBit(n)]; } void build(Node[] nodes) { build(0, 0, n - 1, nodes); } private void build(int id, int l, int r, Node[] nodes) { if (l == r) { st[id] = nodes[l]; return; } int mid = (l + r) >> 1; build((id << 1) + 1, l, mid, nodes); build((id << 1) + 2, mid + 1, r, nodes); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } void update(int i, Node node) { update(0, 0, n - 1, i, node); } private void update(int id, int l, int r, int i, Node node) { if (i < l || r < i) { return; } if (l == r) { st[id] = node; return; } int mid = (l + r) >> 1; update((id << 1) + 1, l, mid, i, node); update((id << 1) + 2, mid + 1, r, i, node); st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]); } Node get(int x, int y) { return get(0, 0, n - 1, x, y); } private Node get(int id, int l, int r, int x, int y) { if (x > r || y < l) { return new Node(0); } if (x <= l && r <= y) { return st[id]; } int mid = (l + r) >> 1; return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y)); } Node comb(Node a, Node b) { if (a == null) { return b; } if (b == null) { return a; } return new Node(a.val | b.val); } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
50a7a1df48f2e0731a52137b46bdb3d9
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_766_D2_E { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long inv(long x,long m){ return powerMod(x,m-2,m); } static int pgcd(int a,int b){ if (a<b) return pgcd(b,a); while (b!=0){ int c=b; b=a%b; a=c; } return a; } static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); int T=reader.readInt(); for (int t=0;t<T;t++) { int n=reader.readInt(); int m=reader.readInt(); int k=reader.readInt(); long[] x=new long[n]; for (int i=0;i<n;i++) x[i]=reader.readInt(); int[] a=new int[k]; int[] b=new int[k]; int[] c=new int[k]; int[] d=new int[k]; int[] h=new int[k]; //ArrayList<Integer>[] register=new ArrayList[n]; //for (int u=0;u<n;u++) // register[u]=new ArrayList<Integer>(); TreeSet<Integer>[] poi=new TreeSet[n]; HashMap<Integer,ArrayList<Integer>>[] target=new HashMap[n]; for (int e=0;e<n;e++) { target[e]=new HashMap<Integer,ArrayList<Integer>>(); poi[e]=new TreeSet<Integer>(); } for (int i=0;i<k;i++) { a[i]=reader.readInt()-1; b[i]=reader.readInt()-1; c[i]=reader.readInt()-1; d[i]=reader.readInt()-1; h[i]=reader.readInt(); //register[a[i]].add(i); poi[a[i]].add(b[i]); poi[c[i]].add(d[i]); ArrayList<Integer> list=target[a[i]].get(b[i]); if (list==null) { list=new ArrayList<Integer>(); target[a[i]].put(b[i],list); } list.add(i); } poi[0].add(0); int[][] lst=new int[n][]; for (int e=0;e<n;e++) { lst[e]=new int[poi[e].size()]; int st=0; for (int y:poi[e]) { lst[e][st++]=y; } } HashMap<Integer,Long>[] cost=new HashMap[n]; for (int u=0;u<n;u++) cost[u]=new HashMap<Integer,Long>(); cost[0].put(0,0L); long MX=Long.MAX_VALUE; long ans=MX; for (int e=0;e<n;e++) { if (cost[e].size()!=0) { long cur=MX; int last=0; //log("=========================== processing e:"+e+" cur:"+cur); for (int it=0;it<lst[e].length;it++) { int p=lst[e][it]; //log("retrieving p:"+p); // first update cur if (cur!=MX) cur=cur+(p-last)*x[e]; Long cst=cost[e].get(p); if (cst!=null) { //log("p:"+p+" cst:"+cst); if (cur>cst) { cur=cst; } } last=p; //log("cur:"+cur); if (cur!=MX) { if (e==n-1 && cur!=MX) { //log("updating answer for cur:"+cur); ans=Math.min(ans, cur+(m-1-p)*x[e]); } ArrayList<Integer> list=target[e].get(p); if (list!=null) { for (int i:list) { int f=c[i]; int np=d[i]; Long z=cost[f].get(np); //log("considering jump at p:"+p+" cur:"+cur+" h:"+h[i]); if (z==null ||(z!=null && z>cur-h[i])) { cost[f].put(np, cur-h[i]); } } } } } cur=MX; last=m-1; for (int it=lst[e].length-1;it>=0;it--) { int p=lst[e][it]; //log("retrieving p:"+p); // first update cur if (cur!=MX) cur=cur+(last-p)*x[e]; last=p; Long cst=cost[e].get(p); if (cst!=null) { //log("p:"+p+" cst:"+cst); if (cur>cst) { cur=cst; } } //log("cur:"+cur); if (cur!=MX) { ArrayList<Integer> list=target[e].get(p); if (list!=null) { for (int i:list) { int f=c[i]; int np=d[i]; Long z=cost[f].get(np); //log("considering jump at p:"+p+" cur:"+cur+" h:"+h[i]); if (z==null ||(z!=null && z>cur-h[i])) { cost[f].put(np, cur-h[i]); } } } } } } } if (ans==MX) { output("NO ESCAPE"); } else output(ans); } try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
6c89442c6de36a82c3e4d0657ad4529a
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.*; import java.util.*; public class A { static long INF = (long) 1e17; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); ArrayList<int[]>[] adj = new ArrayList[2 * n + 2 * k]; for (int i = 0; i < adj.length; i++) adj[i] = new ArrayList(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } TreeSet<Integer>[] all = new TreeSet[n]; TreeMap<int[], Integer> map = new TreeMap<int[], Integer>( (x, y) -> x[0] == y[0] ? x[1] - y[1] : x[0] - y[0]); for (int i = 0; i < n; i++) { all[i] = new TreeSet<Integer>(); all[i].add(0); map.put(new int[] { i, 0 }, map.size()); all[i].add(m - 1); map.put(new int[] { i, m - 1 }, map.size()); } for (int i = 0; i < k; i++) { int ai = sc.nextInt() - 1; int bi = sc.nextInt() - 1; int ci = sc.nextInt() - 1; int di = sc.nextInt() - 1; int h = sc.nextInt(); int[] first = { ai, bi }; int[] second = { ci, di }; if (!map.containsKey(first)) map.put(first, map.size()); if (!map.containsKey(second)) map.put(second, map.size()); all[ai].add(bi); all[ci].add(di); int u = map.get(first); int v = map.get(second); adj[u].add(new int[] { v, h }); } long[][] dp = new long[2][2 * n + 2 * k]; for (long[] x : dp) Arrays.fill(x, INF); for (int i = n - 1; i >= 0; i--) { ArrayList<Integer> cur = new ArrayList<Integer>(); while (!all[i].isEmpty()) cur.add(all[i].pollFirst()); if (i == n - 1) { for (int j = 0; j < cur.size(); j++) { int col = cur.get(j); int idx = map.get(new int[] { i, col }); dp[0][idx] = dp[1][idx] = (m - col - 1) * a[i]; } } else { long min = INF; int pre = -1; for (int j = 0; j < cur.size(); j++) { int col = cur.get(j); int idx = map.get(new int[] { i, col }); long ans = (pre == -1 ? (INF) : (min + Math.abs(pre - col) * a[i])); ans = Math.min(ans, INF); for (int[] nxt : adj[idx]) { int other = nxt[0]; int h = nxt[1]; ans = Math.min(ans, Math.min(dp[0][other], dp[1][other]) - h); } dp[0][idx] = ans; min = ans; pre = col; } min = INF; pre = -1; for (int j = cur.size() - 1; j >= 0; j--) { int col = cur.get(j); int idx = map.get(new int[] { i, col }); long ans = (pre == -1 ? (INF) : (min + Math.abs(pre - col) * a[i])); ans = Math.min(ans, INF); for (int[] nxt : adj[idx]) { int other = nxt[0]; int h = nxt[1]; ans = Math.min(ans, Math.min(dp[0][other], dp[1][other]) - h); } dp[1][idx] = ans; min = ans; pre = col; } } } // for (int[] x : map.keySet()) { // int v = map.get(x); // System.err.println( // Arrays.toString(x) + " " + map.get(x) + " " + // Math.min(dp[0][map.get(x)], dp[1][map.get(x)])); // // for (int[] nxt : adj[v]) // System.err.println(Arrays.toString(nxt)); // System.err.println("EDGES"); // } int id = map.get(new int[] { 0, 0 }); long ans = Math.min(dp[0][id], dp[1][id]); pw.println(ans > 1e16 ? "NO ESCAPE" : ans); } pw.flush(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
e173b715eeec121fd179a36e7ab9c7f7
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
/* Setting up my ambitions Check 'em one at a time, yeah, I made it Now it's time for ignition I'm the start, heat it up They follow, burning up a chain reaction, oh-oh-oh Go fire it up, oh, oh, no Assemble the crowd now, now Line 'em up on the ground No leaving anyone behind */ import static java.lang.Math.*; import java.util.*; import java.io.*; import java.math.*; public class x1627E { static final long INF = Long.MAX_VALUE/2; public static void main(String hi[]) throws Exception { FastScanner infile = new FastScanner(); int T = infile.nextInt(); StringBuilder sb = new StringBuilder(); while(T-->0) { int N = infile.nextInt(); int M = infile.nextInt(); int K = infile.nextInt(); int[] cost = infile.nextInts(N); ArrayList<Ladder>[] ladders = new ArrayList[N]; ArrayList<Node>[] dp = new ArrayList[N]; for(int r=0; r < N; r++) { ladders[r] = new ArrayList<Ladder>(); dp[r] = new ArrayList<Node>(); } for(int i=0; i < K; i++) { int a = infile.nextInt()-1; int b = infile.nextInt()-1; int c = infile.nextInt()-1; int d = infile.nextInt()-1; int h = infile.nextInt(); ladders[a].add(new Ladder(b, c, d, h)); } dp[0].add(new Node(0, 0L)); for(int row=0; row < N; row++) { /* System.out.println("row "+row); for(Node d: dp[row]) System.out.println(d.col+" "+d.cost); System.out.println("........"); */ Collections.sort(dp[row], (x,y) -> { return x.col-y.col; }); Collections.sort(ladders[row], (x,y) -> { return x.currC-y.currC; }); long prefix = -INF; int lastPosition = -1; //of the node spot int dex = 0; for(Ladder d: ladders[row]) { while(dex < dp[row].size() && dp[row].get(dex).col <= d.currC) { //update prefix cost if(lastPosition == -1) { prefix = dp[row].get(dex).cost; lastPosition = dp[row].get(dex).col; } else { long newPrefix = prefix+(long)(dp[row].get(dex).col-lastPosition)*cost[row]; prefix = min(dp[row].get(dex).cost, newPrefix); lastPosition = dp[row].get(dex).col; } dex++; } if(lastPosition != -1) dp[d.nextR].add(new Node(d.nextC, prefix+(long)(d.currC-lastPosition)*cost[row]-d.health)); } //reverse direction long suffix = -INF; lastPosition = -1; dex = dp[row].size()-1; Collections.reverse(ladders[row]); for(Ladder d: ladders[row]) { while(dex >= 0 && dp[row].get(dex).col > d.currC) { //update prefix cost if(lastPosition == -1) { suffix = dp[row].get(dex).cost; lastPosition = dp[row].get(dex).col; } else { long newSuffix = suffix+(long)(lastPosition-dp[row].get(dex).col)*cost[row]; suffix = min(dp[row].get(dex).cost, newSuffix); lastPosition = dp[row].get(dex).col; } dex--; } if(lastPosition != -1) dp[d.nextR].add(new Node(d.nextC, suffix+(long)(lastPosition-d.currC)*cost[row]-d.health)); } } if(dp[N-1].size() == 0) sb.append("NO ESCAPE\n"); else { long res = INF; for(Node x: dp[N-1]) res = min(res, x.cost+(long)(M-1-x.col)*cost[N-1]); sb.append(res+"\n"); } } System.out.print(sb); } } /* dp[r][c] = min health lost to go from (0, 0) to (r, c) dp[r][c] = min(dp[r][c-1]+x_r, dp[r][c+1]+x_r) if ladder (a,b) -> (r, c) exists dp[r][c] = min(dp[r][c], dp[a][b]-ladder_health) for each row, maintain two lists: ladders list = {(b, c, d), ...} list of all ladders that start at this row positions list {c1, c2, ...} list of all column positions that we can start on ci = {column, cost} 1 5 3 3 5 17 8 1 4 1 3 3 3 4 3 1 5 2 5 3 2 5 1 6 1 4 3 4 6 100 100 1 1 1 2 1 1 2 1 3 1 1 3 1 4 1 1 1 3 4 3 10 */ class Ladder { public int currC; public int nextR; public int nextC; public int health; public Ladder(int a, int b, int c, int h) { currC = a; nextR = b; nextC = c; health = h; } } class Node { public int col; public long cost; public Node(int a, long c) { col = a; cost = c; } } class FastScanner { //I don't understand how this works lmao private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
fc7d37c9af5566213a14fac02ec60703
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.util.*; import java.io.*; ////*************************************************************************** /* public class E_Gardener_and_Tree implements Runnable{ public static void main(String[] args) throws Exception { new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start(); } public void run(){ WRITE YOUR CODE HERE!!!! JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!! } } */ /////************************************************************************** public class E_Not_Escaping{ public static void main(String[] args) { FastScanner s= new FastScanner(); //PrintWriter out=new PrintWriter(System.out); //end of program //out.println(answer); //out.close(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); int m=s.nextInt(); int k=s.nextInt(); long array[]= new long[n+1]; for(int i=1;i<=n;i++){ array[i]=s.nextLong(); } yoyo1 obj5 = new yoyo1(); yoyo2 obj7 = new yoyo2(); PriorityQueue<ladder> well1 = new PriorityQueue<ladder>(obj5);//sorts on the basis of end points PriorityQueue<ladder> well2 = new PriorityQueue<ladder>(obj7);// start points for(int i=0;i<k;i++){ long a=s.nextLong(); long b=s.nextLong(); long c=s.nextLong(); long d=s.nextLong(); long h=s.nextLong(); ladder obj2 = new ladder(a,b,c,d,h); well1.add(obj2); well2.add(obj2); } ArrayList<ArrayList<ladder>> start = new ArrayList<ArrayList<ladder>>(n+2);//stores start ones ArrayList<ArrayList<ladder>> end = new ArrayList<ArrayList<ladder>>(n+2);//stores end ones for(int i=0;i<=n;i++){ ArrayList<ladder> obj3 = new ArrayList<ladder>(); ArrayList<ladder> obj4 = new ArrayList<ladder>(); start.add(obj3); end.add(obj4); } while(well1.size()>0){//end points ladder obj1 = well1.poll(); long a=obj1.c; int a1=(int)a; end.get(a1).add(obj1); } while(well2.size()>0){//start points ladder obj1 = well2.poll(); long a=obj1.a; int a1=(int)a; start.get(a1).add(obj1); } // if health is lost then taking negative and vice versa HashMap<ArrayList<Long>,Long> map = new HashMap<ArrayList<Long>,Long>(); ArrayList<ladder> yo =end.get(n); long x=array[n]; for(int i=0;i<yo.size();i++){//setting the base case ladder obj1 =yo.get(i); long d=obj1.d; long e=(Math.abs(m-d))*x; long f=e-(2*e); ArrayList<Long> hh = new ArrayList<Long>(); hh.add(obj1.a); hh.add(obj1.b); hh.add(obj1.c); hh.add(obj1.d); map.put(hh,f); } long ans=Long.MIN_VALUE; for(int i=n-1;i>=1;i--){// iteraying over the floors ArrayList<ladder> list1 = start.get(i); int size=list1.size(); long x1=array[i]; ArrayList<ladder> list2 = end.get(i); if(size==0){// no ladder is going up from this floor for(int j=0;j<list2.size();j++){ // iterating over the ladders ending at this floor ladder obj69 = list2.get(j); ArrayList<Long> hh = new ArrayList<Long>(); hh.add(obj69.a); hh.add(obj69.b); hh.add(obj69.c); hh.add(obj69.d); map.put(hh,Long.MIN_VALUE); } } else{ long array1[]= new long[size]; long best1[]= new long[size]; for(int j=0;j<size;j++){ ladder obj1= list1.get(j); long b=obj1.b; long c=b*x1; c=c-(2*c); long h=obj1.h; c=(c+h); ArrayList<Long> hh = new ArrayList<Long>(); hh.add(obj1.a); hh.add(obj1.b); hh.add(obj1.c); hh.add(obj1.d); long kk=map.get(hh); if(kk==Long.MIN_VALUE){ array1[j]=kk; } else{ c+=kk; array1[j]=c; } } long max1=Long.MIN_VALUE; for(int j=size-1;j>=0;j--){ max1=Math.max(max1,array1[j]); best1[j]=max1; } long array2[]= new long[size]; long best2[]= new long[size]; for(int j=0;j<size;j++){ ladder obj1= list1.get(j); long b=obj1.b; long c=(Math.abs(m-b))*x1; c=c-(2*c); long h=obj1.h; c=(c+h); ArrayList<Long> hh = new ArrayList<Long>(); hh.add(obj1.a); hh.add(obj1.b); hh.add(obj1.c); hh.add(obj1.d); long kk=map.get(hh); if(kk==Long.MIN_VALUE){ array2[j]=kk; } else{ c+=kk; array2[j]=c; } } long max2=Long.MIN_VALUE; for(int j=0;j<size;j++){ max2=Math.max(max2,array2[j]); best2[j]=max2; } if(i==1){ long nn=best1[0]; if(nn!=Long.MIN_VALUE){ long add=x1; nn+=add; ans=nn; } break; } for(int j=0;j<list2.size();j++){ // iterating over the ladders ending at this floor ladder obj69 = list2.get(j); ArrayList<Long> hh = new ArrayList<Long>(); hh.add(obj69.a); hh.add(obj69.b); hh.add(obj69.c); hh.add(obj69.d); long column=obj69.d; long index=search(list1,column); long mm=Long.MIN_VALUE; if(index==0){ long aa=best1[(int)index]; if(aa==mm){ map.put(hh,mm); } else{ long add=column*x1; aa+=add; map.put(hh,aa); } } else if(index==-1){ long index2=size-1; long aa=best2[(int)index2]; if(aa==mm){ map.put(hh,mm); } else{ long add=(Math.abs(m-column))*x1; aa+=add; map.put(hh,aa); } } else{// considering both cases long aa=best1[(int)index]; long index2=index-1; long aa1=best2[(int)index2]; if(aa==mm && aa1==mm){ map.put(hh,mm); continue; } long add=column*x1; aa+=add; long add1=(Math.abs(m-column))*x1; aa1+=add1; long lol=Math.max(aa,aa1); // if(aa==mm && aa1==mm){ // map.put(hh,mm); // } // else{ map.put(hh,lol); // } } } } } // long ub=power(10,17)+Long.MIN_VALUE; // System.out.println("ub "+ub); if(ans==Long.MIN_VALUE){ res.append("NO ESCAPE \n" ); } else{ long ans2=ans-(2*ans); res.append(ans2+" \n"); } p++; } System.out.println(res); } private static long search(ArrayList<ladder> list1, long column) { int size=list1.size(); if(list1.get(0).b>=column){ return 0; } if(list1.get(size-1).b<column){ return -1; } int start=0; int end=size-1; int mid=0; while(start<end){ mid=(start+end)/2; if(start+1==end){ break; } if(list1.get(mid).b>=column){ end=mid; } else{ start=mid; } } return end; } static class ladder{ long a; long b; long c; long d; long h; ladder(long i, long j, long k, long l, long m){ a=i; b=j; c=k; d=l; h=m; } } 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; } static class yoyo1 implements Comparator<ladder>{ //sort on the baisi of end points public int compare(ladder o1, ladder o2) { // TODO Auto-generated method stub if(o1.c<o2.c){ return -1; } else if(o2.c<o1.c){ return 1; } else{ if(o1.d<o2.d){ return -1; } else { return 1; } } } } static class yoyo2 implements Comparator<ladder>{ //sort on the basis of start points public int compare(ladder o1, ladder o2) { // TODO Auto-generated method stub if(o1.a<o2.a){ return -1; } else if(o2.a<o1.a){ return 1; } else{ if(o1.b<o2.b){ return -1; } else { return 1; } } } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
844a892d9457bc0780084c481db387e8
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.*; import java.util.*; /* polyakoff */ public class Main { static FastReader in; static PrintWriter out; static Random rand = new Random(); static final int oo = (int) 2e9 + 10; static final long OO = (long) 2e18 + 10; static final int MOD = 998244353; static class Ladder { int r, i; boolean begin; Ladder(int r, int i, boolean begin) { this.r = r; this.i = i; this.begin = begin; } } static void solve() { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); long[] x = new long[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } ArrayList<Ladder>[] floors = new ArrayList[n]; Arrays.setAll(floors, i -> new ArrayList<>()); long[] h = new long[k]; boolean[] hasBegins = new boolean[n]; boolean[] hasEnds = new boolean[n]; for (int i = 0; i < k; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; int c = in.nextInt() - 1; int d = in.nextInt() - 1; floors[a].add(new Ladder(b, i, true)); floors[c].add(new Ladder(d, i, false)); h[i] = in.nextInt(); hasBegins[a] = true; hasEnds[c] = true; } floors[n - 1].add(new Ladder(m - 1, k, true)); hasBegins[n - 1] = true; for (int i = 0; i < n; i++) { floors[i].sort((l1, l2) -> Integer.compare(l1.r, l2.r)); } long[] d = new long[k + 1]; Arrays.fill(d, -OO); for (Ladder l : floors[0]) { d[l.i] = -x[0] * l.r; } for (int i = 1; i < n; i++) { if (!hasBegins[i] || !hasEnds[i]) continue; ArrayList<Ladder> floor = floors[i]; int sz = floor.size(); long[] sufMax = new long[sz]; sufMax[sz - 1] = d[floor.get(sz - 1).i] == -OO ? -OO : d[floor.get(sz - 1).i] + h[floor.get(sz - 1).i]; for (int j = sz - 2; j >= 0; j--) { sufMax[j] = -OO; if (sufMax[j + 1] != -OO) sufMax[j] = sufMax[j + 1] - x[i] * (floor.get(j + 1).r - floor.get(j).r); if (d[floor.get(j).i] != -OO) sufMax[j] = Math.max(sufMax[j], d[floor.get(j).i] + h[floor.get(j).i]); } long prefMax = -OO; for (int j = 0; j < sz; j++) { if (prefMax != -OO) prefMax -= x[i] * (floor.get(j).r - floor.get(j - 1).r); if (floor.get(j).begin) d[floor.get(j).i] = Math.max(prefMax, sufMax[j]); else if (d[floor.get(j).i] != -OO) prefMax = Math.max(prefMax, d[floor.get(j).i] + h[floor.get(j).i]); } } out.println(d[k] == -OO ? "NO ESCAPE" : -d[k]); } public static void main(String[] args) { in = new FastReader(); out = new PrintWriter(System.out); int t = 1; t = in.nextInt(); while (t-- > 0) { solve(); } out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { this(System.in); } FastReader(String file) throws FileNotFoundException { this(new FileInputStream(file)); } FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String line; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
a00c5a205224d0755dabbecba4113ba5
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
//make sure to make new file! import java.io.*; import java.util.*; public class E766{ public static void main(String[] args)throws IOException{ FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); for(int q = 1; q <= t; q++){ int n = fs.nextInt(); int m = fs.nextInt(); int l = fs.nextInt(); long[] x = fs.nextLongs(n); //1-indexed Ladder[] ladders = new Ladder[l]; ArrayList<ArrayList<Integer>> ladderstart = new ArrayList<ArrayList<Integer>>(n+1); ArrayList<ArrayList<Integer>> ladderend = new ArrayList<ArrayList<Integer>>(n+1); for(int k = 0; k <= n; k++){ ladderstart.add(new ArrayList<Integer>()); ladderend.add(new ArrayList<Integer>()); } for(int k = 0; k < l; k++){ ladders[k] = new Ladder(fs.nextInt(),fs.nextInt(),fs.nextInt(),fs.nextInt(),fs.nextLong(),k); ladderstart.get(ladders[k].a).add(k); ladderend.get(ladders[k].c).add(k); } long[] dist = new long[l]; Arrays.fill(dist,Long.MAX_VALUE); for(int i : ladderstart.get(1)){ dist[i] = x[1] * (long)(ladders[i].b-1) - ladders[i].h; } for(int k = 2; k < n; k++){ int endsize = ladderend.get(k).size(); int startsize = ladderstart.get(k).size(); if(startsize == 0 || endsize == 0) continue; //sort by horizontal coord Collections.sort(ladderstart.get(k), (a, b) -> (ladders[a].b-ladders[b].b)); Collections.sort(ladderend.get(k), (a, b) -> (ladders[a].d-ladders[b].d)); //check left int bestleft = ladderend.get(k).get(0); int endi = 0; int starti = 0; while(starti < startsize && ladders[ladderstart.get(k).get(starti)].b < ladders[bestleft].d) starti++; while(endi < endsize || starti < startsize){ if(starti >= startsize) break; Ladder startladder = ladders[ladderstart.get(k).get(starti)]; if(endi >= endsize){ //use bestleft if(dist[bestleft] != Long.MAX_VALUE) dist[startladder.index] = Math.min(dist[startladder.index], dist[bestleft] + x[k] * (long)(startladder.b-ladders[bestleft].d) - startladder.h); starti++; continue; } Ladder endladder = ladders[ladderend.get(k).get(endi)]; if(endladder.d <= startladder.b){ //update bestleft if(dist[bestleft] == Long.MAX_VALUE || (dist[bestleft] + x[k] * (long)(endladder.d-ladders[bestleft].d) > dist[endladder.index])){ bestleft = endladder.index; } endi++; } else { //use bestleft if(dist[bestleft] != Long.MAX_VALUE) dist[startladder.index] = Math.min(dist[startladder.index], dist[bestleft] + x[k] * (long)(startladder.b-ladders[bestleft].d) - startladder.h); starti++; } } //check right int bestright = ladderend.get(k).get(endsize-1); endi = endsize-1; starti = startsize-1; while(starti >= 0 && ladders[ladderstart.get(k).get(starti)].b > ladders[bestright].d) starti--; while(endi >= 0 || starti >= 0){ if(starti < 0) break; Ladder startladder = ladders[ladderstart.get(k).get(starti)]; if(endi < 0){ //use bestright if(dist[bestright] != Long.MAX_VALUE) dist[startladder.index] = Math.min(dist[startladder.index], dist[bestright] + x[k] * (long)(ladders[bestright].d-startladder.b) - startladder.h); starti--; continue; } Ladder endladder = ladders[ladderend.get(k).get(endi)]; if(endladder.d >= startladder.b){ //update bestright if(dist[bestright] == Long.MAX_VALUE || (dist[bestright] + x[k] * (long)(ladders[bestright].d-endladder.d) > dist[endladder.index])){ bestright = endladder.index; } endi--; } else { //use bestright if(dist[bestright] != Long.MAX_VALUE) dist[startladder.index] = Math.min(dist[startladder.index], dist[bestright] + x[k] * (long)(ladders[bestright].d-startladder.b) - startladder.h); starti--; } } } long answer = Long.MAX_VALUE; for(int endi : ladderend.get(n)){ if(dist[endi] == Long.MAX_VALUE) continue; answer = Math.min(answer,dist[endi] + x[n]*(long)(m-ladders[endi].d)); } if(answer == Long.MAX_VALUE){ out.println("NO ESCAPE"); } else { out.println(answer); } } out.close(); } public static class Ladder{ int a; int b; int c; int d; long h; int index; public Ladder(int q, int w, int e, int r, long t, int i){ a = q; b = w; c = e; d = r; h = t; index = i; } } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N+1]; for (int i = 1; i <= N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
1e46adee3b3b796a06d72bb42dece365
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run() { for(int q=ni();q>0;q--){ work(); } out.flush(); } long mod=998244353; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } long inf=Long.MAX_VALUE/3; void work() { int n=ni(),m=ni(),k=ni(); long[] A=na(n); HashSet<Integer>[] rec1=new HashSet[n]; HashSet<Integer>[] rec2=new HashSet[n]; HashMap<Integer,Long>[] rec3=new HashMap[n]; HashMap<Integer,List<int[]>>[] rec4=new HashMap[n]; for(int i=0;i<n;i++){ rec1[i]=new HashSet<>(); rec2[i]=new HashSet<>(); rec3[i]=new HashMap<>(); rec4[i]=new HashMap<>(); } for(int i=0;i<k;i++){ int sx=ni()-1,sy=ni()-1,ex=ni()-1,ey=ni()-1,v=ni(); rec1[ex].add(ey); rec2[sx].add(sy); if(rec4[ex].get(ey)==null){ rec4[ex].put(ey,new ArrayList<>()); } rec4[ex].get(ey).add(new int[]{sx,sy,v}); } for(int key:rec2[0]){ rec3[0].put(key,key*A[0]); } for(int i=1;i<n;i++){ List<long[]> list=new ArrayList<>(); for(int key:rec1[i]){ List<int[]> l1 = rec4[i].get(key); long r=inf; for(int[] arr:l1){ int sx=arr[0],sy=arr[1],v=arr[2]; Long v2 = rec3[sx].get(sy); if(v2!=null){ r=Math.min(r,v2-v); } } if(r!=inf)list.add(new long[]{key,r}); } if(list.size()==0){ continue; } if(i==n-1){ long ret=inf; for(long[] arr:list){ int idx=(int)arr[0]; long v=arr[1]; ret=Math.min(ret,(m-1-idx)*A[n-1]+v); } out.println(ret); return; } List<Integer> idxs=new ArrayList<>(rec2[i]); Collections.sort(idxs); long[] L=new long[idxs.size()]; long[] R=new long[idxs.size()]; Collections.sort(list,(a1,a2)->(int)(a1[0]-a2[0])); long cur=inf; for(int j=0,p=0;j<idxs.size();j++){ while(p<list.size()&&idxs.get(j)>=list.get(p)[0]){ long v2=(idxs.get(j)-list.get(p)[0])*A[i]+list.get(p)[1]; cur=Math.min(cur,v2); p++; } L[j]=cur; if(j<idxs.size()-1){ int next=idxs.get(j+1); cur+=(next-idxs.get(j))*A[i]; } } cur=inf; for(int j=idxs.size()-1,p=list.size()-1;j>=0;j--){ while(p>=0&&idxs.get(j)<=list.get(p)[0]){ long v2=(list.get(p)[0]-idxs.get(j))*A[i]+list.get(p)[1]; cur=Math.min(cur,v2); p--; } R[j]=cur; if(j>0){ int next=idxs.get(j-1); cur+=(idxs.get(j)-next)*A[i]; } } for(int j=0;j<idxs.size();j++){ rec3[i].put(idxs.get(j),Math.min(L[j],R[j])); } } out.println("NO ESCAPE"); } private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w}); graph[(int)e].add(new long[] {s,w}); } return graph; } private ArrayList<int[]>[] ngwi(int n, int m) { ArrayList<int[]>[] graph=(ArrayList<int[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=ni()-1,e=ni()-1,w=ni(); graph[s].add(new int[] {e,w}); graph[e].add(new int[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private double nd() { return in.nextDouble(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; InputStreamReader input;//no buffer public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public FastReader(boolean isBuffer) { if(!isBuffer){ input=new InputStreamReader(System.in); }else{ br=new BufferedReader(new InputStreamReader(System.in)); } } public boolean hasNext(){ try{ String s=br.readLine(); if(s==null){ return false; } st=new StringTokenizer(s); }catch(IOException e){ e.printStackTrace(); } return true; } public String next() { if(input!=null){ try { StringBuilder sb=new StringBuilder(); int ch=input.read(); while(ch=='\n'||ch=='\r'||ch==32){ ch=input.read(); } while(ch!='\n'&&ch!='\r'&&ch!=32){ sb.append((char)ch); ch=input.read(); } return sb.toString(); }catch (Exception e){ e.printStackTrace(); } } while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return (int)nextLong(); } public long nextLong() { try { if(input!=null){ long ret=0; int b=input.read(); while(b<'0'||b>'9'){ b=input.read(); } while(b>='0'&&b<='9'){ ret=ret*10+(b-'0'); b=input.read(); } return ret; } }catch (Exception e){ e.printStackTrace(); } return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
e19830762eec12265e0f122b656b2b3e
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; /* */ public class E { static TreeSet<Node> allNodes=new TreeSet<>(); public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { allNodes.clear(); int h=fs.nextInt(), w=fs.nextInt(), nLadders=fs.nextInt(); int[] moveCostAtX=fs.readArray(h); Node start=get(0, 0); // Node[] ends=new Node[w]; // for (int i=0; i<w; i++) ends[i]=get(h-1, i); Node end=get(h-1, w-1); for (int i=0; i<nLadders; i++) { Ladder l=new Ladder(fs.nextInt()-1, fs.nextInt()-1, fs.nextInt()-1, fs.nextInt()-1, fs.nextInt()); Node from=get(l.low, l.sx), to=get(l.hi, l.ex); from.edges.add(new Edge(from, to, -l.health)); } for (Node nn:allNodes) { // if (nn.floor==h-1) break; Node next=allNodes.higher(nn); if (next==null || next.floor!=nn.floor) continue; nn.edges.add(new Edge(nn, next, moveCostAtX[nn.floor]*(long)(next.x-nn.x))); next.edges.add(new Edge(next, nn, moveCostAtX[nn.floor]*(long)(next.x-nn.x))); } PriorityQueue<State> pq=new PriorityQueue<>(); pq.add(new State(start, 0)); start.dist=0; while (!pq.isEmpty()) { State curState=pq.remove(); if (curState.cost!=curState.at.dist) continue; for (Edge ee:curState.at.edges) { long newCost=ee.cost+curState.cost; if (newCost<ee.to.dist) { ee.to.dist=newCost; pq.add(new State(ee.to, newCost)); } } } long ans=end.dist; // for (Node nn:ends) { // ans=Math.min(ans, nn.dist); // } System.out.println(ans>=Long.MAX_VALUE/2?"NO ESCAPE":(""+ans)); } } static Node get(int floor, int x) { Node test=new Node(floor, x); Node ceil=allNodes.ceiling(test); if (ceil!=null && ceil.x==test.x&& ceil.floor==test.floor) return ceil; allNodes.add(test); return test; } static Node getNextOnFloor(int floor, int x) { Node test=new Node(floor, x); Node ceil=allNodes.ceiling(test); if (ceil==null) return null; if (ceil.floor==test.floor) return ceil; return null; } static class Node implements Comparable<Node> { int floor; int x; long dist=Long.MAX_VALUE/2; ArrayList<Edge> edges=new ArrayList<>(); public Node(int floor, int x) { this.floor=floor; this.x=x; } public int compareTo(Node o) { if (floor!=o.floor) return Integer.compare(floor, o.floor); return Integer.compare(x, o.x); } } static class Edge { Node from; Node to; long cost; public Edge(Node from, Node to, long cost) { this.from=from; this.to=to; this.cost=cost; } } static class State implements Comparable<State> { Node at; long cost; public State(Node at, long cost) { this.at=at; this.cost=cost; } public int compareTo(State o) { if (at.floor!=o.at.floor) return Integer.compare(at.floor, o.at.floor); return Long.compare(cost, o.cost); } } static class Ladder { int low, hi, health; int sx, ex; public Ladder(int low, int sx, int high, int ex, int health) { this.low=low; this.hi=high; this.health=health; this.sx=sx; this.ex=ex; } } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
acd5d10fbc57de4f9d417b7b99baffbf
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeSet; /* */ public class E { static TreeSet<Node> allNodes=new TreeSet<>(); public static void main(String[] args) { FastScanner fs=new FastScanner(); PrintWriter out=new PrintWriter(System.out); int T=fs.nextInt(); for (int tt=0; tt<T; tt++) { allNodes.clear(); int h=fs.nextInt(), w=fs.nextInt(), nLadders=fs.nextInt(); int[] moveCostAtX=fs.readArray(h); Node start=get(0, 0); // Node[] ends=new Node[w]; // for (int i=0; i<w; i++) ends[i]=get(h-1, i); Node end=get(h-1, w-1); for (int i=0; i<nLadders; i++) { Ladder l=new Ladder(fs.nextInt()-1, fs.nextInt()-1, fs.nextInt()-1, fs.nextInt()-1, fs.nextInt()); Node from=get(l.low, l.sx), to=get(l.hi, l.ex); from.edges.add(new Edge(from, to, -l.health)); } for (Node nn:allNodes) { // if (nn.floor==h-1) break; Node next=allNodes.higher(nn); if (next==null || next.floor!=nn.floor) continue; nn.edges.add(new Edge(nn, next, moveCostAtX[nn.floor]*(long)(next.x-nn.x))); next.edges.add(new Edge(next, nn, moveCostAtX[nn.floor]*(long)(next.x-nn.x))); } PriorityQueue<State> pq=new PriorityQueue<>(); pq.add(new State(start, 0)); start.dist=0; while (!pq.isEmpty()) { State curState=pq.remove(); if (curState.cost!=curState.at.dist) continue; for (Edge ee:curState.at.edges) { long newCost=ee.cost+curState.cost; if (newCost<ee.to.dist) { ee.to.dist=newCost; pq.add(new State(ee.to, newCost)); } } } long ans=end.dist; // for (Node nn:ends) { // ans=Math.min(ans, nn.dist); // } System.out.println(ans>=Long.MAX_VALUE/2?"NO ESCAPE":(""+ans)); } } static Node get(int floor, int x) { Node test=new Node(floor, x); Node ceil=allNodes.ceiling(test); if (ceil!=null && ceil.x==test.x&& ceil.floor==test.floor) return ceil; allNodes.add(test); return test; } static Node getNextOnFloor(int floor, int x) { Node test=new Node(floor, x); Node ceil=allNodes.ceiling(test); if (ceil==null) return null; if (ceil.floor==test.floor) return ceil; return null; } static class Node implements Comparable<Node> { int floor; int x; long dist=Long.MAX_VALUE/2; ArrayList<Edge> edges=new ArrayList<>(); public Node(int floor, int x) { this.floor=floor; this.x=x; } public int compareTo(Node o) { if (floor!=o.floor) return Integer.compare(floor, o.floor); return Integer.compare(x, o.x); } } static class Edge { Node from; Node to; long cost; public Edge(Node from, Node to, long cost) { this.from=from; this.to=to; this.cost=cost; } } static class State implements Comparable<State> { Node at; long cost; public State(Node at, long cost) { this.at=at; this.cost=cost; } public int compareTo(State o) { if (at.floor!=o.at.floor) return Integer.compare(at.floor, o.at.floor); return Long.compare(cost, o.cost); } } static class Ladder { int low, hi, health; int sx, ex; public Ladder(int low, int sx, int high, int ex, int health) { this.low=low; this.hi=high; this.health=health; this.sx=sx; this.ex=ex; } } static final Random random=new Random(); static final int mod=1_000_000_007; static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static long add(long a, long b) { return (a+b)%mod; } static long sub(long a, long b) { return ((a-b)%mod+mod)%mod; } static long mul(long a, long b) { return (a*b)%mod; } static long exp(long base, long exp) { if (exp==0) return 1; long half=exp(base, exp/2); if (exp%2==0) return mul(half, half); return mul(half, mul(half, base)); } static long[] factorials=new long[2_000_001]; static long[] invFactorials=new long[2_000_001]; static void precompFacts() { factorials[0]=invFactorials[0]=1; for (int i=1; i<factorials.length; i++) factorials[i]=mul(factorials[i-1], i); invFactorials[factorials.length-1]=exp(factorials[factorials.length-1], mod-2); for (int i=invFactorials.length-2; i>=0; i--) invFactorials[i]=mul(invFactorials[i+1], i+1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n-k])); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
570974151fd5d8f71eb98c5ecccfa84d
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.Collections; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Sparsh Sanchorawala */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ENotEscaping solver = new ENotEscaping(); solver.solve(1, in, out); out.close(); } static class ENotEscaping { public void solve(int testNumber, InputReader s, PrintWriter w) { int t = s.nextInt(); while (t-- > 0) { int n = s.nextInt(), m = s.nextInt(), k = s.nextInt(); long[] x = new long[n]; for (int i = 0; i < n; i++) x[i] = s.nextInt(); Ladder[] ladders = new Ladder[k]; for (int i = 0; i < k; i++) ladders[i] = new Ladder(s.nextInt() - 1, s.nextInt() - 1, s.nextInt() - 1, s.nextInt() - 1, s.nextLong()); HashSet<Integer>[] inhs = new HashSet[n]; HashSet<Integer>[] ouths = new HashSet[n]; HashMap<Integer, Long>[] inhm = new HashMap[n]; HashMap<Integer, Long>[] outhm = new HashMap[n]; for (int i = 0; i < n; i++) { inhs[i] = new HashSet<>(); ouths[i] = new HashSet<>(); inhm[i] = new HashMap<>(); outhm[i] = new HashMap<>(); } ArrayList<Integer>[] al = new ArrayList[n]; for (int i = 0; i < n; i++) al[i] = new ArrayList<>(); inhs[0].add(0); inhm[0].put(0, 0L); for (int i = 0; i < k; i++) { Ladder l = ladders[i]; inhs[l.c].add(l.d); ouths[l.a].add(l.b); al[l.a].add(i); } ouths[n - 1].add(m - 1); ArrayList<Integer>[] in = new ArrayList[n]; ArrayList<Integer>[] out = new ArrayList[n]; for (int i = 0; i < n; i++) { in[i] = new ArrayList<>(inhs[i]); Collections.sort(in[i]); out[i] = new ArrayList<>(ouths[i]); Collections.sort(out[i]); } for (int i = 0; i < n; i++) { long best = Long.MIN_VALUE; int l = -1; int last = -1; for (int j : out[i]) { if (best != Long.MIN_VALUE) { best -= x[i] * (j - last); } last = j; while (l + 1 < in[i].size() && in[i].get(l + 1) <= j) { int v = in[i].get(l + 1); if (inhm[i].get(v) != null) { best = Math.max(best, inhm[i].get(v) - x[i] * (j - v)); } l++; } if (best != Long.MIN_VALUE) { outhm[i].put(j, best); } } best = Long.MIN_VALUE; int r = in[i].size(); last = -1; for (int ll = out[i].size() - 1; ll >= 0; ll--) { int j = out[i].get(ll); if (best != Long.MIN_VALUE) { best -= x[i] * (last - j); } last = j; while (r - 1 >= 0 && in[i].get(r - 1) >= j) { int v = in[i].get(r - 1); if (inhm[i].get(v) != null) { best = Math.max(best, inhm[i].get(v) - x[i] * (v - j)); } r--; } if (best != Long.MIN_VALUE) { if (outhm[i].get(j) == null || outhm[i].get(j) < best) outhm[i].put(j, best); } } for (int z : al[i]) { Ladder lad = ladders[z]; if (outhm[lad.a].get(lad.b) != null) { if (inhm[lad.c].get(lad.d) == null || inhm[lad.c].get(lad.d) < outhm[lad.a].get(lad.b) + lad.h) { inhm[lad.c].put(lad.d, outhm[lad.a].get(lad.b) + lad.h); } } } } if (outhm[n - 1].get(m - 1) != null) w.println(-outhm[n - 1].get(m - 1)); else w.println("NO ESCAPE"); } } class Ladder { int a; int b; int c; int d; long h; Ladder(int a, int b, int c, int d, long h) { this.a = a; this.b = b; this.c = c; this.d = d; this.h = h; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output
PASSED
4f66e43a78a095036405add690d7ed8c
train_109.jsonl
1642257300
Major Ram is being chased by his arch enemy Raghav. Ram must reach the top of the building to escape via helicopter. The building, however, is on fire. Ram must choose the optimal path to reach the top of the building to lose the minimum amount of health.The building consists of $$$n$$$ floors, each with $$$m$$$ rooms each. Let $$$(i, j)$$$ represent the $$$j$$$-th room on the $$$i$$$-th floor. Additionally, there are $$$k$$$ ladders installed. The $$$i$$$-th ladder allows Ram to travel from $$$(a_i, b_i)$$$ to $$$(c_i, d_i)$$$, but not in the other direction. Ram also gains $$$h_i$$$ health points if he uses the ladder $$$i$$$. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders.If Ram is on the $$$i$$$-th floor, he can move either left or right. Travelling across floors, however, is treacherous. If Ram travels from $$$(i, j)$$$ to $$$(i, k)$$$, he loses $$$|j-k| \cdot x_i$$$ health points.Ram enters the building at $$$(1, 1)$$$ while his helicopter is waiting at $$$(n, m)$$$. What is the minimum amount of health Ram loses if he takes the most optimal path? Note this answer may be negative (in which case he gains health). Output "NO ESCAPE" if no matter what path Ram takes, he cannot escape the clutches of Raghav.
256 megabytes
import java.util.*; import java.io.*; public class E1627 { static int n, m, k; static int[] x; static ArrayList<int[]>[] ladders; static final long INF = (long) 1e18, NIL = (long) 2e18; public static int getCeilingLadder(int row, int col) { ArrayList<int[]> myRow = ladders[row]; int lo = 0; int hi = myRow.size() - 1; int ans = -1; while (lo <= hi) { int mid = lo + hi >> 1; if (myRow.get(mid)[1] >= col) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } public static int getFloorLadder(int row, int col) { ArrayList<int[]> myRow = ladders[row]; int lo = 0; int hi = myRow.size() - 1; int ans = -1; while (lo <= hi) { int mid = lo + hi >> 1; if (myRow.get(mid)[1] <= col) { ans = mid; lo = mid + 1; } else { hi = mid - 1; } } return ans; } static long[][][] dp; public static long dp(int row, int ladderIdx, int state) { // System.out.println(row + " " + ladderIdx + " " + state); if (dp[state][row][ladderIdx] != NIL) { return dp[state][row][ladderIdx]; } long ans = INF; int[] myLadder = ladders[row].get(ladderIdx); if (state <= 2) { ans = Math.min(ans, dp(row, ladderIdx, 3) - myLadder[4]); } if (state == 0 || state == 1) { if (ladderIdx + 1 < ladders[row].size()) { ans = Math.min(ans, dp(row, ladderIdx + 1, 1) + 1l * x[row] * (ladders[row].get(ladderIdx + 1)[1] - myLadder[1])); } } if (state == 0 || state == 2) { if (ladderIdx - 1 >= 0) { ans = Math.min(ans, dp(row, ladderIdx - 1, 2) + 1l * x[row] * (myLadder[1] - ladders[row].get(ladderIdx - 1)[1])); } } if (state == 3) { if (myLadder[2] == n - 1) { ans = 1l * x[n - 1] * (m - 1 - myLadder[3]); } int floorLadderIdx = getFloorLadder(myLadder[2], myLadder[3]); int ceilLadderIdx = getCeilingLadder(myLadder[2], myLadder[3]); if (floorLadderIdx != -1) { ans = Math.min(ans, dp(myLadder[2], floorLadderIdx, 2) + 1l * x[myLadder[2]] * Math.abs(myLadder[3] - ladders[myLadder[2]].get(floorLadderIdx)[1])); } if (ceilLadderIdx != -1) { ans = Math.min(ans, dp(myLadder[2], ceilLadderIdx, 1) + 1l * x[myLadder[2]] * Math.abs(myLadder[3] - ladders[myLadder[2]].get(ceilLadderIdx)[1])); } } return dp[state][row][ladderIdx] = ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { n = sc.nextInt(); m = sc.nextInt(); k = sc.nextInt(); ladders = new ArrayList[n]; for (int i = 0; i < n; i++) { ladders[i] = new ArrayList<>(); } x = sc.nextIntArr(n); while (k-- > 0) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int c = sc.nextInt() - 1; int d = sc.nextInt() - 1; int h = sc.nextInt(); int[] ladder = {a, b, c, d, h}; ladders[a].add(ladder); } for (ArrayList<int[]> row : ladders) { Collections.sort(row, (u, v) -> u[1] - v[1]); } dp = new long[4][n][]; for (int i = 0; i < 4; i++) { for (int j = 0; j < n; j++) { dp[i][j] = new long[ladders[j].size()]; Arrays.fill(dp[i][j], NIL); } } long ans = INF; for (int i = 0; i < ladders[0].size(); i++) { ans = Math.min(ans, dp(0, i, 0) + 1l * x[0] * ladders[0].get(i)[1]); } // System.err.println(dp(0, 0, 0)); pw.println(ans >= (long)1e17 ? "NO ESCAPE" : ans); } pw.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(next()); } return arr; } } }
Java
["4\n\n5 3 3\n\n5 17 8 1 4\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n6 3 3\n\n5 17 8 1 4 2\n\n1 3 3 3 4\n\n3 1 5 2 5\n\n3 2 5 1 6\n\n5 3 1\n\n5 17 8 1 4\n\n1 3 5 3 100\n\n5 5 5\n\n3 2 3 7 5\n\n3 5 4 2 1\n\n2 2 5 4 5\n\n4 4 5 2 3\n\n1 2 4 2 2\n\n3 3 5 2 4"]
2 seconds
["16\nNO ESCAPE\n-90\n27"]
NoteThe figure for the first test case is in the statement. There are only $$$2$$$ possible paths to $$$(n, m)$$$: Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 2)$$$, takes the ladder to $$$(5, 1)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-2| - h_3 + x_5 \cdot |1-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 1 - 6 + 4 \cdot 2 \\ &amp;= 16. \end{align*} $$$$$$ Ram travels to $$$(1, 3)$$$, takes the ladder to $$$(3, 3)$$$, travels to $$$(3, 1)$$$, takes the ladder to $$$(5, 2)$$$, travels to $$$(5, 3)$$$ where he finally escapes via helicopter. The health lost would be $$$$$$ \begin{align*} &amp;\mathrel{\phantom{=}} x_1 \cdot |1-3| - h_1 + x_3 \cdot |3-1| - h_2 + a_5 \cdot |2-3| \\ &amp;= 5 \cdot 2 - 4 + 8 \cdot 2 - 5 + 4 \cdot 1 \\ &amp;= 21. \end{align*} $$$$$$ Therefore, the minimum health lost would be $$$16$$$.In the second test case, there is no path to $$$(n, m)$$$.In the third case case, Ram travels to $$$(1, 3)$$$ and takes the only ladder to $$$(5, 3)$$$. He loses $$$5 \cdot 2$$$ health points and gains $$$h_1 = 100$$$ health points. Therefore the total loss is $$$10-100=-90$$$ (negative implies he gains health after the path).
Java 8
standard input
[ "data structures", "dp", "implementation", "shortest paths", "two pointers" ]
0c2fd0e84b88d407a3bd583d8879de34
The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The first line of each test case consists of $$$3$$$ integers $$$n, m, k$$$ ($$$2 \leq n, m \leq 10^5$$$; $$$1 \leq k \leq 10^5$$$) — the number of floors, the number of rooms on each floor and the number of ladders respectively. The second line of a test case consists of $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \leq x_i \leq 10^6$$$). The next $$$k$$$ lines describe the ladders. Ladder $$$i$$$ is denoted by $$$a_i, b_i, c_i, d_i, h_i$$$ ($$$1 \leq a_i &lt; c_i \leq n$$$; $$$1 \leq b_i, d_i \leq m$$$; $$$1 \leq h_i \leq 10^6$$$)  — the rooms it connects and the health points gained from using it. It is guaranteed $$$a_i &lt; c_i$$$ for all ladders and there is at most one ladder between any 2 rooms in the building. The sum of $$$n$$$, the sum of $$$m$$$, and the sum of $$$k$$$ over all test cases do not exceed $$$10^5$$$.
2,200
Output the minimum health Ram loses on the optimal path from $$$(1, 1)$$$ to $$$(n, m)$$$. If Ram cannot escape the clutches of Raghav regardless of the path he takes, output "NO ESCAPE" (all uppercase, without quotes).
standard output