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
222f7220092784ebb5f5f2f3ad07b006
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i<j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i<j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i < j \le n$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(); int N = in.nextInt(); int M = in.nextInt(); if (N > M) { System.out.println(0); return; } int[] A = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } long ans = 1; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { ans = ans * Math.abs(A[j] - A[i]) % M; } } System.out.println(ans); } static class InputReader { public BufferedReader reader; public StringTokenizer st; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output
PASSED
231ba9d68fb96994c79829402a7a1870
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
256 megabytes
import java.util.*; public class Main { static Scanner input = new Scanner(System.in); public static void main(String[] args) { int n = input.nextInt(); int mod = input.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); } if(n>mod){ System.out.println(0); return; } long ans = 1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int m = Math.abs(a[i] - a[j]); ans *= m; ans %= mod; } } System.out.println(ans % mod); } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output
PASSED
ac7cd3248e27ebe2f8174c7198e091c5
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { public static void main(String[] args) throws java.lang.Exception { Reader pm =new Reader(); //Scanner pm = new Scanner(new BufferedReader(new InputStreamReader(System.in))); int n = pm.nextInt(); int m = pm.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = pm.nextInt(); if(n <= m){ long ans = 1; for(int i=0;i<n;i++){ int flag = 0; for(int j=i+1;j<n;j++){ long d = Math.abs(a[i]-a[j]); //long pl = d % m; //System.out.println(d+" "+pl); ans= ((ans % m) * (d % m)) % m; if(ans == 0){ flag = 1; break; } } if(flag == 1) break; } System.out.println(ans % m); } else System.out.println(0 % m); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output
PASSED
58435479480f10bb6a362f2d9630f7ef
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; public class Main { void solve(){ int n=ni(),m=ni(); if(n>m){ pw.println("0"); return; } long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nl(); Arrays.sort(a); long ans=1; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ ans=(ans*Math.abs(a[i]-a[j])%m)%m; } } pw.println(ans); } long mul(long x,long y,long M){ x*=y; if(x>=M) x%=M; return x; } long modpow(long a, long b,long M) { if(b==0) return 1; if(a==0) return 0; long r=1; while(b>0) { if((b&1)>0) r=mul(r,a,M); a=mul(a,a,M); b>>=1; } return r; } InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o)); } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output
PASSED
4ffe78711a171c6941c7d84bb122838e
train_001.jsonl
1583246100
To become the king of Codeforces, Kuroni has to solve the following problem.He is given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. Help Kuroni to calculate $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$. As result can be very big, output it modulo $$$m$$$.If you are not familiar with short notation, $$$\prod_{1\le i&lt;j\le n} |a_i - a_j|$$$ is equal to $$$|a_1 - a_2|\cdot|a_1 - a_3|\cdot$$$ $$$\dots$$$ $$$\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$$$ $$$\dots$$$ $$$\cdot|a_2 - a_n| \cdot$$$ $$$\dots$$$ $$$\cdot |a_{n-1} - a_n|$$$. In other words, this is the product of $$$|a_i - a_j|$$$ for all $$$1\le i &lt; j \le n$$$.
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 m=input.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=input.nextInt(); } if(n<=m) { int p=1; for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { int d=Math.abs(a[i]-a[j]); p=((p%m)*(d%m))%m; } } out.println(p); } else { out.println(0); } } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["2 10\n8 5", "3 12\n1 4 5", "3 7\n1 4 9"]
1 second
["3", "0", "1"]
NoteIn the first sample, $$$|8 - 5| = 3 \equiv 3 \bmod 10$$$.In the second sample, $$$|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$$$.In the third sample, $$$|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$$$.
Java 8
standard input
[ "combinatorics", "number theory", "brute force", "math" ]
bf115b24d85a0581e709c012793b248b
The first line contains two integers $$$n$$$, $$$m$$$ ($$$2\le n \le 2\cdot 10^5$$$, $$$1\le m \le 1000$$$) — number of numbers and modulo. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).
1,600
Output the single number — $$$\prod_{1\le i&lt;j\le n} |a_i - a_j| \bmod m$$$.
standard output
PASSED
d7cccf0dd22cbed71c0c6a4db26708ca
train_001.jsonl
1557671700
Let $$$s$$$ be some string consisting of symbols "0" or "1". Let's call a string $$$t$$$ a substring of string $$$s$$$, if there exists such number $$$1 \leq l \leq |s| - |t| + 1$$$ that $$$t = s_l s_{l+1} \ldots s_{l + |t| - 1}$$$. Let's call a substring $$$t$$$ of string $$$s$$$ unique, if there exist only one such $$$l$$$. For example, let $$$s = $$$"1010111". A string $$$t = $$$"010" is an unique substring of $$$s$$$, because $$$l = 2$$$ is the only one suitable number. But, for example $$$t = $$$"10" isn't a unique substring of $$$s$$$, because $$$l = 1$$$ and $$$l = 3$$$ are suitable. And for example $$$t =$$$"00" at all isn't a substring of $$$s$$$, because there is no suitable $$$l$$$.Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him.You are given $$$2$$$ positive integers $$$n$$$ and $$$k$$$, such that $$$(n \bmod 2) = (k \bmod 2)$$$, where $$$(x \bmod 2)$$$ is operation of taking remainder of $$$x$$$ by dividing on $$$2$$$. Find any string $$$s$$$ consisting of $$$n$$$ symbols "0" or "1", such that the length of its minimal unique substring is equal to $$$k$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static void main() throws Exception{ int n=sc.nextInt(),k=sc.nextInt(); int a=(n-k)/2; int c=0; while(c<n) { for(int i=0;i<a && c<n;i++,c++) { pw.print(0); } if(c==n)break; c++; pw.print(1); } } public static void main(String[] args) throws Exception{ pw=new PrintWriter(System.out); sc = new MScanner(System.in); int tc=1; while(tc-->0) main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["4 4", "5 3", "7 3"]
1 second
["1111", "01010", "1011011"]
NoteIn the first test, it's easy to see, that the only unique substring of string $$$s = $$$"1111" is all string $$$s$$$, which has length $$$4$$$.In the second test a string $$$s = $$$"01010" has minimal unique substring $$$t =$$$"101", which has length $$$3$$$.In the third test a string $$$s = $$$"1011011" has minimal unique substring $$$t =$$$"110", which has length $$$3$$$.
Java 11
standard input
[ "constructive algorithms", "math", "strings" ]
7e8baa4fb780f11e66bb2b7078e34c04
The first line contains two integers $$$n$$$ and $$$k$$$, separated by spaces ($$$1 \leq k \leq n \leq 100\,000$$$, $$$(k \bmod 2) = (n \bmod 2)$$$).
2,200
Print a string $$$s$$$ of length $$$n$$$, consisting of symbols "0" and "1". Minimal length of the unique substring of $$$s$$$ should be equal to $$$k$$$. You can find any suitable string. It is guaranteed, that there exists at least one such string.
standard output
PASSED
81c417794dbcbd291a1b3d89be43a55b
train_001.jsonl
1517582100
Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).
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 */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); queue a[] = new queue[n]; for (int i = 0; i < n; i++) { a[i] = new queue(in.nextInt(), in.nextInt(), i); } int curr = 1; for (int i = 0; i < n; i++) { if (curr <= a[i].r) { if (curr < a[i].l) { a[i].ans = a[i].l; curr = a[i].l + 1; } else { a[i].ans = curr; curr++; } } } for (int i = 0; i < n - 1; i++) { out.print(a[i].ans + " "); } out.println(a[n - 1].ans); } } class queue { int l; int r; int ind; int ans = 0; queue() { } queue(int l, int r, int ind) { this.l = l; this.r = r; this.ind = ind; } } } 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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"]
1 second
["1 2 \n1 0 2"]
NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.
Java 8
standard input
[ "implementation" ]
471f80e349e70339eedd20d45b16e253
The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students. Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li - 1 ≤ li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t = 1.
1,200
For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.
standard output
PASSED
234c76fe4f38e031b93b7d2b336acb60
train_001.jsonl
1517582100
Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class B{ public static void main(String[] args)throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int c = Integer.parseInt(in.readLine()); while(c-->0){ int n = Integer.parseInt(in.readLine()); StringBuilder ans = new StringBuilder(); int co = 1; for(int i = 0; i<n;i++){ String lr[] = in.readLine().split(" "); int l = Integer.parseInt(lr[0]); int r = Integer.parseInt(lr[1]); if(r>=co && l<co){ ans.append(co+" "); co++; }else if(l>=co){ ans.append(l+" "); co = l; co++; }else{ ans.append("0 "); } } System.out.println(ans); } } }
Java
["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"]
1 second
["1 2 \n1 0 2"]
NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.
Java 8
standard input
[ "implementation" ]
471f80e349e70339eedd20d45b16e253
The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students. Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li - 1 ≤ li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t = 1.
1,200
For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.
standard output
PASSED
9b070b5d0f72ca921a7de20c0baa6325
train_001.jsonl
1517582100
Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Omar-Handouk */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, FastReader in, OutputWriter out) { int t = in.nextInt(); while (t-- > 0) { int n = in.nextInt(); int time[][] = new int[n][2]; for (int i = 0; i < n; ++i) { time[i][0] = in.nextInt(); time[i][1] = in.nextInt(); } int elapsed = time[0][0]; for (int i = 0; i < n; ++i) //If i try to enter and and elapsed > l i cant { if (elapsed <= time[i][1] && elapsed >= time[i][0] || time[i][0] > elapsed) { if (time[i][0] > elapsed) { elapsed = time[i][0] + 1; out.print(elapsed - 1 + " "); } else { out.print(elapsed + " "); ++elapsed; } } else { out.print(0 + " "); } } out.println(); } } } static class FastReader { BufferedReader bufferedReader; StringTokenizer stringTokenizer; public FastReader(InputStream stream) { bufferedReader = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException error) { error.printStackTrace(); } } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(this.next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println() { writer.println(); } public void close() { writer.close(); } } }
Java
["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"]
1 second
["1 2 \n1 0 2"]
NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.
Java 8
standard input
[ "implementation" ]
471f80e349e70339eedd20d45b16e253
The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students. Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li - 1 ≤ li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t = 1.
1,200
For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.
standard output
PASSED
ffd14e867bab7a467c7faac8377d6aeb
train_001.jsonl
1517582100
Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class B{ static int t,n,l[],r[],res[]; static void MainMethod()throws Exception{ t=reader.nextInt(); int i,k=0; for (t=t;t>0;t--) { n=reader.nextInt(); l=new int[n];r=new int[n]; res=new int [n]; for (i=0;i<n;i++) { l[i]=reader.nextInt(); r[i]=reader.nextInt(); if (i==0) { res[i]=l[i]; k=res[i]; }else { if (r[i]<Math.max(k+1, l[i])) res[i]=0; else { res[i]=Math.max(k+1, l[i]); k=res[i]; } } } for (i=0;i<n;i++) printer.print(res[i]+" "); printer.println(); } } public static void main(String[] args)throws Exception{ MainMethod(); printer.close(); } static void halt(){ printer.close(); System.exit(0); } static PrintWriter printer=new PrintWriter(new OutputStreamWriter(System.out)); static class reader{ static BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer token=new StringTokenizer(""); static String readNextLine() throws Exception{ return bReader.readLine(); } static String next() throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return token.nextToken(); } static int nextInt()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Integer.parseInt(token.nextToken()); } static long nextLong()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Long.parseLong(token.nextToken()); } static double nextDouble()throws Exception{ while (token.hasMoreTokens()==false){ token=new StringTokenizer(bReader.readLine()); } return Double.parseDouble(token.nextToken()); } } static class MyMathCompute{ static long [][] MatrixMultiplyMatrix(long [][] A, long [][] B, long mod) throws Exception{ int n=A.length, m=B[0].length; int p=A[0].length; int i,j,k; if (B.length!=p) throw new Exception("invalid matrix input"); long [][] res=new long [n][m]; for (i=0;i<n;i++) for (j=0;j<m;j++){ if (A[i].length!=p) throw new Exception("invalid matrix input"); res[i][j]=0; for (k=0;k<p;k++) res[i][j]=(res[i][j]+((A[i][k]*B[k][j])% mod))% mod; } return res; } static double [][] MatrixMultiplyMatrix(double [][] A, double [][] B ) throws Exception{ int n=A.length, m=B[0].length; int p=A[0].length; int i,j,k; if (B.length!=p) throw new Exception("invalid matrix input"); double [][] res=new double [n][m]; for (i=0;i<n;i++) for (j=0;j<m;j++){ if (A[i].length!=p) throw new Exception("invalid matrix input"); res[i][j]=0; for (k=0;k<p;k++) res[i][j]=res[i][j]+(A[i][k]*B[k][j]); } return res; } static long [][] MatrixPow(long [][] A,long n, long mod) throws Exception{ if (n==1) return A; long [][] res=MatrixPow(A, n/2, mod); res=MatrixMultiplyMatrix(res, res, mod); if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res, mod); return res; } static double [][] MatrixPow(double [][] A,long n) throws Exception{ if (n==1) return A; double[][] res=MatrixPow(A, n/2); res=MatrixMultiplyMatrix(res, res); if ((n % 2) == 1) res=MatrixMultiplyMatrix(A,res); return res; } static long pow(long a,long n,long mod){ a= a % mod; if (n==0) return 1; long k=pow(a,n/2,mod); if ((n % 2)==0) return ((k*k)%mod); else return (((k*k) % mod)*a) % mod; } static double pow(double a,long n){ if (n==0) return 1; double k=pow(a,n/2); if ((n % 2)==0) return (k*k); else return (((k*k) )*a) ; } } }
Java
["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"]
1 second
["1 2 \n1 0 2"]
NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.
Java 8
standard input
[ "implementation" ]
471f80e349e70339eedd20d45b16e253
The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students. Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li - 1 ≤ li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t = 1.
1,200
For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.
standard output
PASSED
dd6a08ac1b5bd44b04f1927095104d11
train_001.jsonl
1517582100
Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).
256 megabytes
import java.lang.*; import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class Main { public void solve() throws IOException { int t = nextInt(); for (int tt = 0; tt < t; tt++) { int n = nextInt(); int a[] = new int[n], b[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); b[i] = nextInt(); } int time = 0; for (int i = 0; i < n; i++) { if(time < a[i]) time = a[i]; if(b[i] < time) out.print("0 "); else { out.print(time + " "); time++; } } out.println(); } } BufferedReader br; StringTokenizer sc; PrintWriter out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Main().run(); } void run() throws IOException { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("pnumbers.in"(); // out = new PrintWriter(new File("out.txt")); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } String nextToken() throws IOException { while (sc == null || !sc.hasMoreTokens()) { try { sc = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return sc.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"]
1 second
["1 2 \n1 0 2"]
NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea.
Java 8
standard input
[ "implementation" ]
471f80e349e70339eedd20d45b16e253
The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 1000). Then t test cases follow. The first line of each test case contains one integer n (1 ≤ n ≤ 1000) — the number of students. Then n lines follow. Each line contains two integer li, ri (1 ≤ li ≤ ri ≤ 5000) — the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li - 1 ≤ li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t = 1.
1,200
For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.
standard output
PASSED
ac37d0845d17dbf9c687d5b65b78f23b
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; public class CodeForces { static int MAX = 100001; static int[] prime = new int[MAX + 1]; static int[] countdiv = new int[MAX + 1]; static void SieveOfEratosthenes() { for (int i = 2; i * i <= MAX; ++i) { if (prime[i] == 0) for (int j = i * 2; j <= MAX; j += i) prime[j] = i; } for (int i = 1; i < MAX; ++i) if (prime[i] == 0) prime[i] = i; } static int largestGCDSubsequence(int arr[], int n) { int ans = 0; for (int i = 0; i < n; ++i) { int element = arr[i]; while (element > 1) { int div = prime[element]; ++countdiv[div]; ans = Math.max(ans, countdiv[div]); while (element % div == 0) element /= div; } } return ans; } public static void main (String[] args) { Scanner sc=new Scanner(System.in); SieveOfEratosthenes(); int n=sc.nextInt(); int arr[] = new int[n]; int c1=0; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); if(arr[i]==1) { c1++; } } if(n==1||c1==n) { System.out.println(1); return; } int size = arr.length; System.out.println(largestGCDSubsequence(arr, size)); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
492c8079a56cb5f3264f211ad01d8f20
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; import java.io.*; public class Main757B { static PrintWriter out=new PrintWriter(System.out); public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int[] a=new int[100001]; Arrays.fill(a,0); for(int i=0;i<n;i++) { int x=sc.nextInt(); a[x]+=1; } if(n==1) out.println(1); else{ boolean[] prime=new boolean[100001]; Arrays.fill(prime,true); int max=1; for(long i=2;i<=100000;i++) { if(prime[(int)i]) { int cnt=0; cnt+=a[(int)i]; for(long j=i*2;Math.abs(j)<=100000;j+=i) { //if(j>=100000) break; prime[(int)j]=false; cnt+=a[(int)j]; } if(cnt>max) max=cnt; } } out.println(max); } out.flush(); } static class Scanner { BufferedReader br; StringTokenizer tk=new StringTokenizer(""); public Scanner(InputStream is) { br=new BufferedReader(new InputStreamReader(is)); } public int nextInt() throws IOException { if(tk.hasMoreTokens()) return Integer.parseInt(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextInt(); } public long nextLong() throws IOException { if(tk.hasMoreTokens()) return Long.parseLong(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextLong(); } public String next() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken()); tk=new StringTokenizer(br.readLine()); return next(); } public String nextLine() throws IOException { tk=new StringTokenizer(""); return br.readLine(); } public double nextDouble() throws IOException { if(tk.hasMoreTokens()) return Double.parseDouble(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextDouble(); } public char nextChar() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken().charAt(0)); tk=new StringTokenizer(br.readLine()); return nextChar(); } 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 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[] nextIntArrayOneBased(int n) throws IOException { int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); return a; } public long[] nextLongArrayOneBased(int n) throws IOException { long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nextLong(); return a; } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
1ce64b5e613d4073f1853f1f7ce44f8f
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class B391 { public static void main(String[] args) { boolean[] prime = new boolean[400]; for(int i=2;i<prime.length;i++){ for(int j=2;i*j<prime.length;j++){ prime[i*j]=true; } } ArrayList<Integer> primes = new ArrayList<>(); for(int i=2;i<prime.length;i++)if(!prime[i])primes.add(i); HashMap<Integer, Integer> count = new HashMap<>(); FS scan = new FS(System.in); int N = scan.nextInt(); for(int i=0;i<N;i++){ int x = scan.nextInt(); int idx = 0; while(x!=1&&idx<primes.size()){ if(x%primes.get(idx)==0){ if(!count.containsKey(primes.get(idx)))count.put(primes.get(idx), 1); else count.put(primes.get(idx), count.get(primes.get(idx))+1); } while(x%primes.get(idx)==0){ x/=primes.get(idx); } idx++; } if(x!=1){ if(!count.containsKey(x))count.put(x, 1); else count.put(x, count.get(x)+1); } } int best = 1; for(int i : count.keySet()){ best = Math.max(best, count.get(i)); } System.out.println(best); } private static long gcd (long a, long b) { return b==0?a:gcd(b,a%b); } public static class FS { BufferedReader br; StringTokenizer st; public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } return st.nextToken(); } public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
cb868b49159a8ef7db9704e6080ace90
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class CF757B { public static void main(String args[]){ InputReader in = new InputReader(System.in); //OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(System.out); HashMap<Integer,Integer>hashmap=new HashMap<>(); int n=in.nextInt(); int ar1[]=sieveOfEratosthenes(100000); int l=ar1.length; //int o=1; HashSet<Integer>hashset; for(int i=0;i<l;i++) { hashmap.put(ar1[i], i); } int ar[]=new int[l]; for(int i=0;i<n;i++) { int x=in.nextInt(); //o=x; hashset=primeFactors(x); Iterator iterator=hashset.iterator(); while (iterator.hasNext()) { int nn = (int) iterator.next(); ar[hashmap.get(nn)]++; } } Arrays.sort(ar); out.println(Math.max(ar[l-1],1)); out.close(); } public static HashSet<Integer> primeFactors(int n) { // Print the number of 2s that divide n HashSet<Integer>hashSet=new HashSet<>(); while (n%2==0) { //System.out.print(2 + " "); hashSet.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i*i<= n; i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { hashSet.add(i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if(n>2) hashSet.add(n); return hashSet; } static int [] 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. boolean prime[] = new boolean[n+1]; for(int i=0;i<=n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p*2; i <= n; i += p) prime[i] = false; } } int c=0; for(int i = 2; i <= n; i++) { if(prime[i] == true) c++; } // return c; int x=0; // Print all prime numbers int ar[]=new int[c]; for(int i = 2; i <= n; i++) { if(prime[i] == true) { //System.out.print(i + " "); ar[x]=i; //System.out.print(ar[x] + " "); x++; } } return ar; } static class Pair implements Comparable<Pair> { int u; int v; BigInteger bi; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static long modulo(long a,long b,long c) { long x=1; long y=a; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } public static long getClosestK(long[] a, long x) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; // test lower case if (mid == 0) { if (a.length == 1) { return a[0]; } return Math.min(Math.abs(a[0] - x), Math.abs(a[1] - x)) + x; } // test upper case if (mid == a.length - 1) { return a[a.length - 1]; } // test equality if (a[mid] == x || a[mid + 1] == x) { return x; } // test perfect range. if (a[mid] < x && a[mid + 1] > x) { return Math.min(Math.abs(a[mid] - x), Math.abs(a[mid + 1] - x)) + x; } // keep searching. if (a[mid] < x) { low = mid + 1; } else { high = mid; } } throw new IllegalArgumentException("The array cannot be empty"); } long factorial(long n,long M) { long ans=1; while(n>=1) { ans=(ans*n)%M; n--; } return ans; } static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine(){ String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
4880c81752f740ed72fa76d2dec1ba14
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import static java.lang.System.out; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] s = new int[n]; int m = 0; for (int i=0;i<n;i++) { s[i] = sc.nextInt(); m = Math.max(m, s[i]); } Arrays.sort(s); int ans = 1; int len = 1; for (int i=1;i<n;i++) { if (s[i]==s[i-1] && s[i]!=1){ len++; }else{ ans = Math.max(ans, len); len=1; } } ans = Math.max(ans, len); for (int i=2;i*i<=m;i++) { int c1 = 0; int c2 = 0; int j = m/i; for (int x : s) { if (x%i==0) c1++; if (j>0 && x%j==0) c2++; } ans = Math.max(ans, Math.max(c1, c2)); } out.println(ans); sc.close(); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
7e9ceedd601cd3521cc5d5fc55d86555
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; import java.io.*; /** * * @author root */ public class B { public static void main(String args[]){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[] = new int[n]; for(int i = 0;i<n;i++) a[i] = in.nextInt(); int counts[] = new int[100001]; int max= 1; for(int i = 0;i<n;i++){ for(int j = 1;j<=(int)Math.sqrt(a[i]);j++){ if(a[i]%j != 0 ) continue; counts[j]++; if(a[i]/j > (int)Math.sqrt(a[i])){ counts[a[i]/j]++; } } } for(int i = 2;i<counts.length;i++) max = Math.max(max, counts[i]); System.out.println(max); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
2f733b41d3955139b7836a6ac58260f8
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; import java.io.*; /** * * @author root */ public class B { public static void main(String args[]){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int a[] = new int[n]; for(int i = 0;i<n;i++) a[i] = in.nextInt(); int counts[] = new int[100001]; int max= 1; for(int i = 0;i<n;i++){ int sqrt = (int)Math.sqrt(a[i]); for(int j = 1;j<=sqrt;j++){ if(a[i]%j != 0 ) continue; counts[j]++; if(a[i]/j > sqrt){ counts[a[i]/j]++; } } } for(int i = 2;i<counts.length;i++) max = Math.max(max, counts[i]); System.out.println(max); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
1c2b197f28d8d0e2714d7dcdee6dc389
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import javax.swing.RowFilter.Entry; public class c391c { static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n=in.nextInt(); int count=0; int max=1; int p=0; boolean con=true; int k=0; int arr[]=new int[100005]; for(int i=0;i<n;i++) { arr[in.nextInt()]++; } for(int i=2;i<100005;i++) { for(int j=i;j<100005;j+=i) { if(arr[j]>0) count+=arr[j]; } max=max(count,max); count=0; } out.println(max); } } 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(); solver.solve(1, in, out); out.close(); } /* java.util.Arrays.sort(array_name,new java.util.Comparator<int[]>(){ public int compare(int[] a, int[] b) { return Integer.compare(a[0], b[0]); }}); */ static void radixSort(int[] xs){ int[] cnt = new int[(1<<16)+1]; int[] ys = new int[xs.length]; for(int j = 0; j <= 16; j += 16) { Arrays.fill(cnt, 0); for(int x : xs) { cnt[(x>>j&0xFFFF)+1]++; } for(int i = 1; i < cnt.length; i++) { cnt[i] += cnt[i-1]; } for(int x : xs) { ys[cnt[x>>j&0xFFFF]++] = x; } { final int[] t = xs; xs = ys; ys = t; } } if(xs[0] < 0 || xs[xs.length - 1] >= 0) return; int i, j, c; for(i = xs.length - 1, c = 0; xs[i] < 0; i--, c++) { ys[c] = xs[i]; } for(j = xs.length - 1; i >= 0; i--, j--) { xs[j] = xs[i]; } for(i = c - 1; i >= 0; i--) { xs[i] = ys[c-1-i]; } } static long min(long x,long y){return x<y?x:y;} static long min(long x,long y,long z){return x<y?(x<z?x:z):(y<z?y:z);} static long min(long n1,long n2,long n3,long n4){ return n1<n2?(n1<n3?(n1<n4?n1:n4):(n3<n4?n3:n4)):(n2<n3?(n2<n4?n2:n4):(n3<n4?n3:n4));} static long max(long x,long y){return x>y?x:y;} static long max(long x,long y,long z){return x>y?(x>z?x:z):(y>z?y:z);} static long max(long n1,long n2,long n3,long n4){ return n1>n2?(n1>n3?(n1>n4?n1:n4):(n3>n4?n3:n4)):(n2>n3?(n2>n4?n2:n4):(n3>n4?n3:n4));} static int min(int x,int y){return x<y?x:y;} static int min(int x,int y,int z){return x<y?(x<z?x:z):(y<z?y:z);} static long min(int n1,int n2,int n3,int n4){ return n1<n2?(n1<n3?(n1<n4?n1:n4):(n3<n4?n3:n4)):(n2<n3?(n2<n4?n2:n4):(n3<n4?n3:n4));} static int max(int x,int y){return x>y?x:y;} static int max(int x,int y,int z){return x>y?(x>z?x:z):(y>z?y:z);} static long max(int n1,int n2,int n3,int n4){ return n1>n2?(n1>n3?(n1>n4?n1:n4):(n3>n4?n3:n4)):(n2>n3?(n2>n4?n2:n4):(n3>n4?n3:n4));} static long sumarr(int arr[],int n1,int n2){ long sum=0; for(int i=n1-1;i<n2;i++) sum=sum+arr[i]; return sum; } //**************************************Reader Class*********************************************// 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 String nextLine() { String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
3bb8aa0cd9e0937aeff240703b6c6bcb
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
/* * UMANG PANCHAL * DAIICT */ import java.util.*; import java.io.*; import java.math.*; import java.util.Comparator; public class Main { private static final Comparator<? super Integer> Comparator = null; static LinkedList<Integer> adj[]; static ArrayList<Integer> adj1[]; static int[] color,visited1; static boolean b[],visited[],possible; static int level[]; static Map<Integer,HashSet<Integer>> s; static int totalnodes,colored; static int count[]; static long sum[]; static int nodes; static long ans=0; static long[] as=new long[10001]; static long c1=0,c2=0; static int[] a,d,k; static int max=100000000; static long MOD = 1000000007,sm=0,m=Long.MIN_VALUE; static boolean[] prime=new boolean[1000005]; static int[] levl; static int[] eat; static int price[]; static int res[],par[]; static int result=0; static int[] root,size,du,dv; static long p=Long.MAX_VALUE; static int start,end; static boolean[] vis1,vis2; // --------------------My Code Starts Here---------------------- public static void main(String[] args) throws IOException { in=new InputReader(System.in); w=new PrintWriter(System.out); int n=ni(); int[] d=new int[(int)1e5+5]; int[] a=na(n); for(int i=0;i<n;i++) { for(int j=1;j*j<=a[i];j++) { if(j*j==a[i]) d[j]++; else if(a[i]%j==0) { d[j]++; d[a[i]/j]++; } } } d[1]=1; int ans=-1; for(int i=1;i<d.length;i++) ans=Math.max(ans,d[i]); if(n==1) ans=d[a[0]]; w.print(ans); w.close(); } // --------------------My Code Ends Here------------------------ /* * PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return Integer.compare(o2,o1); } }); * * */ public static void bfs1(int u) { Queue<Integer> q=new LinkedList(); q.add(u); vis1[u]=true; while(!q.isEmpty()) { //w.print(1); int p=q.poll(); for(int i=0;i<adj[p].size();i++) { if(!vis1[adj[p].get(i)]) { du[adj[p].get(i)]=du[p]+1; q.add(adj[p].get(i)); vis1[adj[p].get(i)]=true; } } } } public static void bfs2(int u) { Queue<Integer> q=new LinkedList(); q.add(u); vis2[u]=true; while(!q.isEmpty()) { int p=q.poll(); for(int i=0;i<adj[p].size();i++) { if(!vis2[adj[p].get(i)]) { dv[adj[p].get(i)]=dv[p]+1; q.add(adj[p].get(i)); vis2[adj[p].get(i)]=true; } } } } public static void buildgraph(int n) { adj=new LinkedList[n+1]; visited=new boolean[n]; level=new int[n]; par=new int[n]; for(int i=0;i<=n;i++) { adj[i]=new LinkedList<Integer>(); } } /*public static long kruskal(Pair[] p) { long ans=0; int w=0,x=0,y=0; for(int i=0;i<p.length;i++) { w=p[i].w; x=p[i].x; y=p[i].y; if(root(x)!=root(y)) { ans+=w; union(x,y); } } return ans; }*/ static class Pair implements Comparable<Pair> { char a,b; Pair(char a,char b) { this.a=a; this.b=b; } public int compareTo(Pair o) { //return (int)(sum-o.sum); return 0; } } public static int root(int i) { while(root[i]!=i) { root[i]=root[root[i]]; i=root[i]; } return i; } public static void init(int n) { root=new int[n+1]; for(int i=1;i<=n;i++) root[i]=i; } public static void union(int a,int b) { int root_a=root(a); int root_b=root(b); root[root_a]=root_b; // size[root_b]+=size[root_a]; } public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop 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 ns() { return in.nextLine(); } public static int ni() { return in.nextInt(); } public static long nl() { return in.nextLong(); } public static int[] na(int n) { int[] a=new int[n]; for(int i=0;i<n;i++) a[i]=ni(); return a; } public static long[] nla(int n) { long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=nl(); return a; } public static void sieve() { int n=prime.length; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*2; i <n; i += p) prime[i] = false; } } } public static String rev(String s) { StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long gcd(long a, long b) { while (b > 0) { long temp = b; b = a % b; // % is remainder a = temp; } return a; } static InputReader in; static PrintWriter w; static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { 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 = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
7426d1e9625b78ac9c404f76d9266e09
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Tester { public static long mod=(long)(1e9+7); public static long x,y,d; public static void main(String[] args) { InputReader s=new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out=new PrintWriter(outputStream); int N=100000; int minPrime[] = new int[N+1]; for (int i = 2; i * i <= N; ++i) { if (minPrime[i] == 0) { //If i is prime for (int j = i * i; j <= N; j += i) { if (minPrime[j] == 0) { minPrime[j] = i; } } } } for (int i = 2; i <= N; ++i) { if (minPrime[i] == 0) { minPrime[i] = i; } } int n=s.nextInt(); HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0; i<n; i++) { int x=s.nextInt(); boolean f[] = new boolean[N+1]; //HashSet<Integer> set = new HashSet<>(); while(x!=1) { if(f[minPrime[x]]==false) { if(map.containsKey(minPrime[x])) map.put(minPrime[x], map.get(minPrime[x])+1); else map.put(minPrime[x], 1); f[minPrime[x]]=true; } //set.add(minPrime[x]); x=x/minPrime[x]; } /*for(int xx: set) { if(!map.containsKey(xx)) map.put(xx, 1); else map.put(xx, map.get(xx)+1); }*/ } int max=1; for(int x: map.keySet()) { max=Math.max(max, map.get(x)); } out.println(max); out.close(); } static int firstOccurrence(int A[], int left, int right, int item) { int mid; while (right - left > 1) { mid = left + (right - left) / 2; if (A[mid] >= item) right = mid; else left = mid; } return right; } static void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } static boolean isPrime(long n, long k) { //Fermat Little Theorem if(n<=1 || n==4) return false; if(n<=3) return true; while(k-->0) { long a = 2+((long)Math.random())%(n-4); if(modulo(a,n-1,n) != 1) return false; } return true; } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long modulo(long x,long y,long p) { long res = 1; x = x % p; while (y > 0) { if (y%2==1) res = (res*x) % p; y = y>>1; x = (x*x) % p; } return res; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static long exp(long a, long b) { if(b==0) return 1; if(b==1) return a; if(b==2) return a*a; if(b%2==0) return exp(exp(a,b/2),2); else return a*exp(exp(a,(b-1)/2),2); } static int findLastOccurence(int a[], int val, int lb, int ub) { int mid = (lb+ub)/2; if(mid==lb && a[mid]>val ) { return -1; } if (a[mid] <= val && (mid == ub || a[mid + 1] > val)) { return mid; } if (a[mid] <= val) { return findLastOccurence(a, val, mid + 1, ub); } else { return findLastOccurence(a, val, lb, mid); } } static class Pair implements Comparable<Pair> { long x,y; Pair(long ii, long cc) { x=ii; y=cc; } public int compareTo(Pair o) { return Long.compare(this.x, o.x); } public int hashCode() { int hu = (int) (x ^ (x >>> 32)); int hv = (int) (y ^ (y >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return x == other.x && y == other.y; } public String toString() { return "[x=" + x + ", y=" + y + "]"; } } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
14b8f07c44f782dffdf1d848db890ba3
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Tester { public static long mod=(long)(1e9+7); public static long x,y,d; public static void main(String[] args) { InputReader s=new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out=new PrintWriter(outputStream); int N=100000; int minPrime[] = new int[N+1]; for (int i = 2; i * i <= N; ++i) { if (minPrime[i] == 0) { //If i is prime for (int j = i * i; j <= N; j += i) { if (minPrime[j] == 0) { minPrime[j] = i; } } } } for (int i = 2; i <= N; ++i) { if (minPrime[i] == 0) { minPrime[i] = i; } } int n=s.nextInt(); TreeMap<Integer, Integer> map = new TreeMap<>(); for(int i=0; i<n; i++) { int x=s.nextInt(); //boolean f[] = new boolean[N+1]; HashSet<Integer> set = new HashSet<>(); while(x!=1) { /*if(f[minPrime[x]]==false) { if(map.containsKey(minPrime[x])) map.put(minPrime[x], map.get(minPrime[x])+1); else map.put(minPrime[x], 1); f[minPrime[x]]=true; }*/ set.add(minPrime[x]); x=x/minPrime[x]; } for(int xx: set) { if(!map.containsKey(xx)) map.put(xx, 1); else map.put(xx, map.get(xx)+1); } } int max=1; for(int x: map.keySet()) { max=Math.max(max, map.get(x)); } System.out.println(max); out.close(); } static int firstOccurrence(int A[], int left, int right, int item) { int mid; while (right - left > 1) { mid = left + (right - left) / 2; if (A[mid] >= item) right = mid; else left = mid; } return right; } static void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } static boolean isPrime(long n, long k) { //Fermat Little Theorem if(n<=1 || n==4) return false; if(n<=3) return true; while(k-->0) { long a = 2+((long)Math.random())%(n-4); if(modulo(a,n-1,n) != 1) return false; } return true; } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long modulo(long x,long y,long p) { long res = 1; x = x % p; while (y > 0) { if (y%2==1) res = (res*x) % p; y = y>>1; x = (x*x) % p; } return res; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } static long exp(long a, long b) { if(b==0) return 1; if(b==1) return a; if(b==2) return a*a; if(b%2==0) return exp(exp(a,b/2),2); else return a*exp(exp(a,(b-1)/2),2); } static int findLastOccurence(int a[], int val, int lb, int ub) { int mid = (lb+ub)/2; if(mid==lb && a[mid]>val ) { return -1; } if (a[mid] <= val && (mid == ub || a[mid + 1] > val)) { return mid; } if (a[mid] <= val) { return findLastOccurence(a, val, mid + 1, ub); } else { return findLastOccurence(a, val, lb, mid); } } static class Pair implements Comparable<Pair> { long x,y; Pair(long ii, long cc) { x=ii; y=cc; } public int compareTo(Pair o) { return Long.compare(this.x, o.x); } public int hashCode() { int hu = (int) (x ^ (x >>> 32)); int hv = (int) (y ^ (y >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return x == other.x && y == other.y; } public String toString() { return "[x=" + x + ", y=" + y + "]"; } } public static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine=null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine=reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } 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 long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
05f55dd700a8b3b728571c232d5056ec
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.*; public class Test2 { private static boolean isEven(int num) { return num % 2 == 0; } private static HashMap<Integer, Integer> primeFactors(int num) { HashMap<Integer, Integer> hm = new HashMap<>(); while (isEven(num)) { if (hm.containsKey(2)) hm.put(2, hm.get(2) + 1); else hm.put(2, 1); num /= 2; } int i = 3; while (i <= Math.sqrt(num)) { if (num % i == 0) { if (hm.containsKey(i)) hm.put(i, hm.get(i) + 1); else hm.put(i, 1); num /= i; i = 3; } else i += 2; } if (num > 1) { if (hm.containsKey(num)) hm.put(num, hm.get(num) + 1); else hm.put(num, 1); } return hm; } private static boolean isAllOnes(int[] arr) { for (int num: arr) { if (num != 1) return false; } return true; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] input = new int[n]; for (int i = 0; i < n; ++i) input[i] = in.nextInt(); if (n == 1 || isAllOnes(input)) System.out.println(1); else { List<Map<Integer, Integer>> mapList = new ArrayList<Map<Integer, Integer>>(); for (int num: input) { mapList.add(primeFactors(num)); } Map<Integer, Integer> primeTimes = new HashMap<Integer, Integer>(); for (Map<Integer, Integer> m: mapList) { for (Map.Entry<Integer, Integer> e: m.entrySet()) { if (primeTimes.containsKey(e.getKey())) primeTimes.put(e.getKey(), primeTimes.get(e.getKey()) + 1); else primeTimes.put(e.getKey(), 1); } } int prime = 0; int times = 0; for (Map.Entry<Integer, Integer> e: primeTimes.entrySet()) { if (e.getValue() > times) { prime = e.getKey(); times = e.getValue(); } } System.out.println(times); } } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
35733ba29eb96e098bbc15c16ccc27c7
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by Vasyukevich Andrey on 12.01.2017. */ public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] cnt = new int[100100]; int n = scanner.nextInt(); for (int i = 0; i < n; ++i) { int s = scanner.nextInt(); Set<Integer> delims = new HashSet<>(); for (int d = 1; d < Math.min(Math.sqrt(s) + 5, s); ++d) if (s % d == 0) { delims.add(d); delims.add(s / d); } delims.remove(1); for(Integer d : delims) ++cnt[d]; } System.out.println(Arrays.stream(cnt).filter(e -> e > 0).max().orElse(1)); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
17d6b6de1e0a3bbd76b7aeece4f831a3
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by Vasyukevich Andrey on 12.01.2017. */ public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] cnt = new int[100100]; int n = scanner.nextInt(); for (int i = 0; i < n; ++i) { int s = scanner.nextInt(); if (s != 1) { ++cnt[s]; for (int d = 2; d * d <= s; ++d) if (s % d == 0) { ++cnt[d]; if (s / d != d) ++cnt[s / d]; } } } System.out.println(Math.max(1, Arrays.stream(cnt).max().getAsInt())); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
fc089b2f319f4186b34192389af9855b
train_001.jsonl
1484235300
Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k &gt; 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.
512 megabytes
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by Vasyukevich Andrey on 12.01.2017. */ public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] cnt = new int[100100]; int n = scanner.nextInt(); for (int i = 0; i < n; ++i) { int s = scanner.nextInt(); Set<Integer> divisors = new HashSet<>(); for (int d = 1; d * d <= s; ++d) if (s % d == 0) { divisors.add(d); divisors.add(s / d); } divisors.remove(1); for(Integer d : divisors) ++cnt[d]; } System.out.println(Arrays.stream(cnt).filter(e -> e > 0).max().orElse(1)); } }
Java
["3\n2 3 4", "5\n2 3 4 6 7"]
2 seconds
["2", "3"]
Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.
Java 8
standard input
[ "number theory", "greedy", "math" ]
eea7860e6bbbe5f399b9123ebd663e3e
The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.
1,400
Print single integer — the maximum number of Pokemons Bash can take.
standard output
PASSED
f93c1c3960c0ff21592de2c9e2dafedf
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EEhabsREALNumberTheoryProblem solver = new EEhabsREALNumberTheoryProblem(); solver.solve(1, in, out); out.close(); } } static class EEhabsREALNumberTheoryProblem { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } EulerSieve sieve = new EulerSieve(1000000); IntegerMultiWayStack allPrime = Factorization.factorizeRangePrime(1000000); IntegerHashMap primeToIndex = new IntegerHashMap(sieve.getPrimeCount() + 1, false); for (int i = 0, end = sieve.getPrimeCount(); i < end; i++) { primeToIndex.put(sieve.get(i), i); } primeToIndex.put(1, sieve.getPrimeCount()); List<UndirectedEdge>[] g = Graph.createUndirectedGraph(primeToIndex.size()); IntegerList collect = new IntegerList(2); for (int i = 0; i < n; i++) { int x = a[i]; collect.clear(); for (IntegerIterator iterator = allPrime.iterator(x); iterator.hasNext(); ) { int p = iterator.next(); int cnt = 0; while (x % p == 0) { x /= p; cnt ^= 1; } if (cnt == 1) { collect.add(p); } } if (collect.size() == 0) { out.println(1); return; } if (collect.size() == 1) { collect.add(1); } //debug.debug("a", collect.get(0)); //debug.debug("b", collect.get(1)); Graph.addUndirectedEdge(g, primeToIndex.get(collect.get(0)), primeToIndex.get(collect.get(1))); } IntegerList circle = new IntegerList(n); UndirectedOneWeightMinCircle minCircle = new UndirectedOneWeightMinCircle(g); minCircle.optimize(sieve.getPrimeCount(), circle); for (int i = 0; sieve.get(i) < 1000; i++) { minCircle.optimize(i, circle); } if (circle.size() == 0) { out.println(-1); return; } out.println(circle.size()); } } static interface IntegerIterator { boolean hasNext(); int next(); } static class Graph { public static void addUndirectedEdge(List<UndirectedEdge>[] g, int s, int t) { UndirectedEdge toT = new UndirectedEdge(t); UndirectedEdge toS = new UndirectedEdge(s); toT.rev = toS; toS.rev = toT; g[s].add(toT); g[t].add(toS); } public static List<UndirectedEdge>[] createUndirectedGraph(int n) { List<UndirectedEdge>[] ans = new List[n]; for (int i = 0; i < n; i++) { ans[i] = new ArrayList<>(); } return ans; } } static class EulerSieve { private int[] primes; private boolean[] isComp; private int primeLength; public int getPrimeCount() { return primeLength; } public int get(int k) { return primes[k]; } public EulerSieve(int limit) { isComp = new boolean[limit + 1]; primes = new int[limit + 1]; primeLength = 0; for (int i = 2; i <= limit; i++) { if (!isComp[i]) { primes[primeLength++] = i; } for (int j = 0, until = limit / i; j < primeLength && primes[j] <= until; j++) { int pi = primes[j] * i; isComp[pi] = true; if (i % primes[j] == 0) { break; } } } } } static class UndirectedOneWeightMinCircle { private List<UndirectedEdge>[] g; int[] dist; int[] prev; UndirectedEdge[] tag; IntegerDeque dq; public UndirectedOneWeightMinCircle(List<UndirectedEdge>[] g) { this.g = g; int n = g.length; dist = new int[n]; prev = new int[n]; tag = new UndirectedEdge[n]; dq = new IntegerDequeImpl(n); } private void collect(int root, IntegerList circle) { while (root != -1) { circle.add(root); root = prev[root]; } } public boolean optimize(int root, IntegerList circle) { Arrays.fill(dist, -1); Arrays.fill(prev, -1); Arrays.fill(tag, null); dq.clear(); dist[root] = 0; boolean ans = false; for (UndirectedEdge e : g[root]) { if (dist[e.to] != -1) { if (e.to == root && (circle.size() == 0 || circle.size() > 1)) { circle.clear(); circle.add(root); ans = true; } if (circle.size() == 0 || circle.size() > 2) { circle.clear(); circle.add(root); circle.add(e.to); ans = true; } continue; } dist[e.to] = 1; tag[e.to] = e; prev[e.to] = root; dq.addLast(e.to); } if (circle.size() == 1 || circle.size() == 2) { return ans; } UndirectedEdge cross = null; int best = circle.size() == 0 ? g.length + 1 : circle.size(); while (!dq.isEmpty()) { int head = dq.removeFirst(); for (UndirectedEdge e : g[head]) { if (dist[e.to] != -1) { if (e.to != root && tag[e.to] != tag[head] && best > dist[head] + dist[e.to] + 1) { best = dist[head] + dist[e.to] + 1; cross = e; } continue; } dist[e.to] = dist[head] + 1; tag[e.to] = tag[head]; prev[e.to] = head; dq.addLast(e.to); } } if (cross != null && (circle.size() == 0 || best < circle.size())) { circle.clear(); collect(cross.to, circle); circle.pop(); int size = circle.size(); collect(cross.rev.to, circle); SequenceUtils.reverse(circle.getData(), size, circle.size() - 1); ans = true; } return ans; } } static class Hasher { private long time = System.nanoTime() + System.currentTimeMillis(); private int shuffle(long x) { x += time; x += 0x9e3779b97f4a7c15L; x = (x ^ (x >>> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >>> 27)) * 0x94d049bb133111ebL; return (int) (x ^ (x >>> 31)); } public int hash(int x) { return shuffle(x); } } static class IntegerMultiWayStack { private int[] values; private int[] next; private int[] heads; private int alloc; private int stackNum; public IntegerIterator iterator(final int queue) { return new IntegerIterator() { int ele = heads[queue]; public boolean hasNext() { return ele != 0; } public int next() { int ans = values[ele]; ele = next[ele]; return ans; } }; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); values = Arrays.copyOf(values, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; } public IntegerMultiWayStack(int qNum, int totalCapacity) { values = new int[totalCapacity + 1]; next = new int[totalCapacity + 1]; heads = new int[qNum]; stackNum = qNum; } public void addLast(int qId, int x) { alloc(); values[alloc] = x; next[alloc] = heads[qId]; heads[qId] = alloc; } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < stackNum; i++) { builder.append(i).append(": "); for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) { builder.append(iterator.next()).append(","); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('\n'); } return builder.toString(); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class UndirectedEdge extends DirectedEdge { public UndirectedEdge rev; public UndirectedEdge(int to) { super(to); } } static class DirectedEdge { public int to; public DirectedEdge(int to) { this.to = to; } public String toString() { return "->" + to; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class IntegerHashMap { private int[] slot; private int[] next; private int[] keys; private int[] values; private int alloc; private boolean[] removed; private int mask; private int size; private boolean rehash; private Hasher hasher = new Hasher(); public IntegerHashMap(int cap, boolean rehash) { this.mask = (1 << (32 - Integer.numberOfLeadingZeros(cap - 1))) - 1; slot = new int[mask + 1]; next = new int[cap + 1]; keys = new int[cap + 1]; values = new int[cap + 1]; removed = new boolean[cap + 1]; this.rehash = rehash; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); keys = Arrays.copyOf(keys, newSize); values = Arrays.copyOf(values, newSize); removed = Arrays.copyOf(removed, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; removed[alloc] = false; size++; } private void rehash() { int[] newSlots = new int[Math.max(16, slot.length * 2)]; int newMask = newSlots.length - 1; for (int i = 0; i < slot.length; i++) { if (slot[i] == 0) { continue; } int head = slot[i]; while (head != 0) { int n = next[head]; int s = hash(keys[head]) & newMask; next[head] = newSlots[s]; newSlots[s] = head; head = n; } } this.slot = newSlots; this.mask = newMask; } private int hash(int x) { return hasher.hash(x); } public void put(int x, int y) { put(x, y, true); } public void put(int x, int y, boolean cover) { int h = hash(x); int s = h & mask; if (slot[s] == 0) { alloc(); slot[s] = alloc; keys[alloc] = x; values[alloc] = y; } else { int index = findIndexOrLastEntry(s, x); if (keys[index] != x) { alloc(); next[index] = alloc; keys[alloc] = x; values[alloc] = y; } else if (cover) { values[index] = y; } } if (rehash && size >= slot.length) { rehash(); } } public int getOrDefault(int x, int def) { int h = hash(x); int s = h & mask; if (slot[s] == 0) { return def; } int index = findIndexOrLastEntry(s, x); return keys[index] == x ? values[index] : def; } public int get(int x) { return getOrDefault(x, 0); } private int findIndexOrLastEntry(int s, int x) { int iter = slot[s]; while (keys[iter] != x) { if (next[iter] != 0) { iter = next[iter]; } else { return iter; } } return iter; } public IntegerEntryIterator iterator() { return new IntegerEntryIterator() { int index = 1; int readIndex = -1; public boolean hasNext() { while (index <= alloc && removed[index]) { index++; } return index <= alloc; } public int getEntryKey() { return keys[readIndex]; } public int getEntryValue() { return values[readIndex]; } public void next() { if (!hasNext()) { throw new IllegalStateException(); } readIndex = index; index++; } }; } public int size() { return size; } public String toString() { IntegerEntryIterator iterator = iterator(); StringBuilder builder = new StringBuilder("{"); while (iterator.hasNext()) { iterator.next(); builder.append(iterator.getEntryKey()).append("->").append(iterator.getEntryValue()).append(','); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('}'); return builder.toString(); } } static interface IntegerDeque extends IntegerStack { int removeFirst(); } static class MinimumNumberWithMaximumFactors { private static int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53}; public static long[] maximumPrimeFactor(long n) { long[] ans = new long[2]; ans[0] = 1; for (int i = 0; i < primes.length; i++) { if (DigitUtils.isMultiplicationOverflow(ans[0], primes[i], n)) { break; } ans[0] *= primes[i]; ans[1]++; } return ans; } } static interface IntegerEntryIterator { boolean hasNext(); void next(); int getEntryKey(); int getEntryValue(); } static class DigitUtils { private DigitUtils() { } public static boolean isMultiplicationOverflow(long a, long b, long limit) { if (limit < 0) { limit = -limit; } if (a < 0) { a = -a; } if (b < 0) { b = -b; } if (a == 0 || b == 0) { return false; } //a * b > limit => a > limit / b return a > limit / b; } } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static void reverse(int[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class IntegerDequeImpl implements IntegerDeque { private int[] data; private int bpos; private int epos; private static final int[] EMPTY = new int[0]; private int n; public IntegerDequeImpl(int cap) { if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } bpos = 0; epos = 0; n = cap; } private void expandSpace(int len) { while (n < len) { n = Math.max(n + 10, n * 2); } int[] newData = new int[n]; if (bpos <= epos) { if (bpos < epos) { System.arraycopy(data, bpos, newData, 0, epos - bpos); } } else { System.arraycopy(data, bpos, newData, 0, data.length - bpos); System.arraycopy(data, 0, newData, data.length - bpos, epos); } epos = size(); bpos = 0; data = newData; } public IntegerIterator iterator() { return new IntegerIterator() { int index = bpos; public boolean hasNext() { return index != epos; } public int next() { int ans = data[index]; index = IntegerDequeImpl.this.next(index); return ans; } }; } public int removeFirst() { int ans = data[bpos]; bpos = next(bpos); return ans; } public void addLast(int x) { ensureMore(); data[epos] = x; epos = next(epos); } public void clear() { bpos = epos = 0; } private int next(int x) { return x + 1 >= n ? 0 : x + 1; } private void ensureMore() { if (next(epos) == bpos) { expandSpace(n + 1); } } public int size() { int ans = epos - bpos; if (ans < 0) { ans += data.length; } return ans; } public boolean isEmpty() { return bpos == epos; } public String toString() { StringBuilder builder = new StringBuilder(); for (IntegerIterator iterator = iterator(); iterator.hasNext(); ) { builder.append(iterator.next()).append(' '); } return builder.toString(); } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public int[] getData() { return data; } public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException("invalid index " + i); } } public int get(int i) { checkRange(i); return data[i]; } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int pop() { return data[--size]; } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static interface IntegerStack { void addLast(int x); boolean isEmpty(); void clear(); } static class Factorization { public static IntegerMultiWayStack factorizeRangePrime(int n) { int maxFactorCnt = (int) MinimumNumberWithMaximumFactors.maximumPrimeFactor(n)[1]; IntegerMultiWayStack stack = new IntegerMultiWayStack(n + 1, n * maxFactorCnt); boolean[] isComp = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (isComp[i]) { continue; } for (int j = i; j <= n; j += i) { isComp[j] = true; stack.addLast(j, i); } } return stack; } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
4b5bfc4d5f27c1061b78a799ff6d9211
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.util.ArrayList; import java.io.UncheckedIOException; import java.util.List; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); EEhabsREALNumberTheoryProblem solver = new EEhabsREALNumberTheoryProblem(); solver.solve(1, in, out); out.close(); } } static class EEhabsREALNumberTheoryProblem { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } EulerSieve sieve = new EulerSieve(1000000); IntegerMultiWayStack allPrime = Factorization.factorizeRangePrime(1000000); IntegerHashMap primeToIndex = new IntegerHashMap(sieve.getPrimeCount() + 1, false); for (int i = 0, end = sieve.getPrimeCount(); i < end; i++) { primeToIndex.put(sieve.get(i), i); } primeToIndex.put(1, sieve.getPrimeCount()); List<UndirectedEdge>[] g = Graph.createUndirectedGraph(primeToIndex.size()); IntegerList collect = new IntegerList(2); for (int i = 0; i < n; i++) { int x = a[i]; collect.clear(); for (IntegerIterator iterator = allPrime.iterator(x); iterator.hasNext(); ) { int p = iterator.next(); int cnt = 0; while (x % p == 0) { x /= p; cnt ^= 1; } if (cnt == 1) { collect.add(p); } } if (collect.size() == 0) { out.println(1); return; } if (collect.size() == 1) { collect.add(1); } //debug.debug("a", collect.get(0)); //debug.debug("b", collect.get(1)); Graph.addUndirectedEdge(g, primeToIndex.get(collect.get(0)), primeToIndex.get(collect.get(1))); } UndirectedOneWeightMinCircle circle = new UndirectedOneWeightMinCircle(g); circle.optimize(sieve.getPrimeCount()); for (int i = 0; sieve.get(i) < 1000; i++) { circle.optimize(i); } IntegerList c = circle.getCircle(); if (c == null) { out.println(-1); return; } out.println(c.size()); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 20]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class MinimumNumberWithMaximumFactors { private static int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53}; public static long[] maximumPrimeFactor(long n) { long[] ans = new long[2]; ans[0] = 1; for (int i = 0; i < primes.length; i++) { if (DigitUtils.isMultiplicationOverflow(ans[0], primes[i], n)) { break; } ans[0] *= primes[i]; ans[1]++; } return ans; } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public int[] getData() { return data; } public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } private void checkRange(int i) { if (i < 0 || i >= size) { throw new ArrayIndexOutOfBoundsException("invalid index " + i); } } public int get(int i) { checkRange(i); return data[i]; } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int pop() { return data[--size]; } public int size() { return size; } public int[] toArray() { return Arrays.copyOf(data, size); } public void clear() { size = 0; } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } static interface IntegerEntryIterator { boolean hasNext(); void next(); int getEntryKey(); int getEntryValue(); } static class DigitUtils { private DigitUtils() { } public static boolean isMultiplicationOverflow(long a, long b, long limit) { if (limit < 0) { limit = -limit; } if (a < 0) { a = -a; } if (b < 0) { b = -b; } if (a == 0 || b == 0) { return false; } //a * b > limit => a > limit / b return a > limit / b; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class DirectedEdge { public int to; public DirectedEdge(int to) { this.to = to; } public String toString() { return "->" + to; } } static interface IntegerStack { void addLast(int x); boolean isEmpty(); void clear(); } static class UndirectedOneWeightMinCircle { private List<UndirectedEdge>[] g; int[] dist; int[] prev; UndirectedEdge[] tag; IntegerDeque dq; IntegerList circle; public UndirectedOneWeightMinCircle(List<UndirectedEdge>[] g) { this.g = g; int n = g.length; dist = new int[n]; prev = new int[n]; tag = new UndirectedEdge[n]; dq = new IntegerDequeImpl(n); circle = new IntegerList(n + n); } private void collect(int root) { while (root != -1) { circle.add(root); root = prev[root]; } } public IntegerList getCircle() { return circle.size() == 0 ? null : circle; } public void optimize(int root) { Arrays.fill(dist, -1); Arrays.fill(prev, -1); Arrays.fill(tag, null); dq.clear(); dist[root] = 0; for (UndirectedEdge e : g[root]) { if (dist[e.to] != -1) { if (e.to == root && (circle.size() == 0 || circle.size() > 1)) { circle.clear(); circle.add(root); } if (circle.size() == 0 || circle.size() > 2) { circle.clear(); circle.add(root); circle.add(e.to); } continue; } dist[e.to] = 1; tag[e.to] = e; prev[e.to] = root; dq.addLast(e.to); } UndirectedEdge cross = null; int best = circle.size() == 0 ? g.length + 1 : circle.size(); while (!dq.isEmpty()) { int head = dq.removeFirst(); for (UndirectedEdge e : g[head]) { if (dist[e.to] != -1) { if (e.to != root && tag[e.to] != tag[head] && best > dist[head] + dist[e.to] + 1) { best = dist[head] + dist[e.to] + 1; cross = e; } continue; } dist[e.to] = dist[head] + 1; tag[e.to] = tag[head]; prev[e.to] = head; dq.addLast(e.to); } } if (cross != null && (circle.size() == 0 || best < circle.size())) { circle.clear(); collect(cross.to); circle.pop(); int size = circle.size(); collect(cross.rev.to); SequenceUtils.reverse(circle.getData(), size, circle.size() - 1); } } } static interface IntegerDeque extends IntegerStack { int removeFirst(); } static class IntegerDequeImpl implements IntegerDeque { private int[] data; private int bpos; private int epos; private static final int[] EMPTY = new int[0]; private int n; public IntegerDequeImpl(int cap) { if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } bpos = 0; epos = 0; n = cap; } private void expandSpace(int len) { while (n < len) { n = Math.max(n + 10, n * 2); } int[] newData = new int[n]; if (bpos <= epos) { if (bpos < epos) { System.arraycopy(data, bpos, newData, 0, epos - bpos); } } else { System.arraycopy(data, bpos, newData, 0, data.length - bpos); System.arraycopy(data, 0, newData, data.length - bpos, epos); } epos = size(); bpos = 0; data = newData; } public IntegerIterator iterator() { return new IntegerIterator() { int index = bpos; public boolean hasNext() { return index != epos; } public int next() { int ans = data[index]; index = IntegerDequeImpl.this.next(index); return ans; } }; } public int removeFirst() { int ans = data[bpos]; bpos = next(bpos); return ans; } public void addLast(int x) { ensureMore(); data[epos] = x; epos = next(epos); } public void clear() { bpos = epos = 0; } private int next(int x) { return x + 1 >= n ? 0 : x + 1; } private void ensureMore() { if (next(epos) == bpos) { expandSpace(n + 1); } } public int size() { int ans = epos - bpos; if (ans < 0) { ans += data.length; } return ans; } public boolean isEmpty() { return bpos == epos; } public String toString() { StringBuilder builder = new StringBuilder(); for (IntegerIterator iterator = iterator(); iterator.hasNext(); ) { builder.append(iterator.next()).append(' '); } return builder.toString(); } } static class Hasher { private long time = System.nanoTime() + System.currentTimeMillis(); private int shuffle(long x) { x += time; x += 0x9e3779b97f4a7c15L; x = (x ^ (x >>> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >>> 27)) * 0x94d049bb133111ebL; return (int) (x ^ (x >>> 31)); } public int hash(int x) { return shuffle(x); } } static class EulerSieve { private int[] primes; private boolean[] isComp; private int primeLength; public int getPrimeCount() { return primeLength; } public int get(int k) { return primes[k]; } public EulerSieve(int limit) { isComp = new boolean[limit + 1]; primes = new int[limit + 1]; primeLength = 0; for (int i = 2; i <= limit; i++) { if (!isComp[i]) { primes[primeLength++] = i; } for (int j = 0, until = limit / i; j < primeLength && primes[j] <= until; j++) { int pi = primes[j] * i; isComp[pi] = true; if (i % primes[j] == 0) { break; } } } } } static class UndirectedEdge extends DirectedEdge { public UndirectedEdge rev; public UndirectedEdge(int to) { super(to); } } static class IntegerHashMap { private int[] slot; private int[] next; private int[] keys; private int[] values; private int alloc; private boolean[] removed; private int mask; private int size; private boolean rehash; private Hasher hasher = new Hasher(); public IntegerHashMap(int cap, boolean rehash) { this.mask = (1 << (32 - Integer.numberOfLeadingZeros(cap - 1))) - 1; slot = new int[mask + 1]; next = new int[cap + 1]; keys = new int[cap + 1]; values = new int[cap + 1]; removed = new boolean[cap + 1]; this.rehash = rehash; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); keys = Arrays.copyOf(keys, newSize); values = Arrays.copyOf(values, newSize); removed = Arrays.copyOf(removed, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; removed[alloc] = false; size++; } private void rehash() { int[] newSlots = new int[Math.max(16, slot.length * 2)]; int newMask = newSlots.length - 1; for (int i = 0; i < slot.length; i++) { if (slot[i] == 0) { continue; } int head = slot[i]; while (head != 0) { int n = next[head]; int s = hash(keys[head]) & newMask; next[head] = newSlots[s]; newSlots[s] = head; head = n; } } this.slot = newSlots; this.mask = newMask; } private int hash(int x) { return hasher.hash(x); } public void put(int x, int y) { put(x, y, true); } public void put(int x, int y, boolean cover) { int h = hash(x); int s = h & mask; if (slot[s] == 0) { alloc(); slot[s] = alloc; keys[alloc] = x; values[alloc] = y; } else { int index = findIndexOrLastEntry(s, x); if (keys[index] != x) { alloc(); next[index] = alloc; keys[alloc] = x; values[alloc] = y; } else if (cover) { values[index] = y; } } if (rehash && size >= slot.length) { rehash(); } } public int getOrDefault(int x, int def) { int h = hash(x); int s = h & mask; if (slot[s] == 0) { return def; } int index = findIndexOrLastEntry(s, x); return keys[index] == x ? values[index] : def; } public int get(int x) { return getOrDefault(x, 0); } private int findIndexOrLastEntry(int s, int x) { int iter = slot[s]; while (keys[iter] != x) { if (next[iter] != 0) { iter = next[iter]; } else { return iter; } } return iter; } public IntegerEntryIterator iterator() { return new IntegerEntryIterator() { int index = 1; int readIndex = -1; public boolean hasNext() { while (index <= alloc && removed[index]) { index++; } return index <= alloc; } public int getEntryKey() { return keys[readIndex]; } public int getEntryValue() { return values[readIndex]; } public void next() { if (!hasNext()) { throw new IllegalStateException(); } readIndex = index; index++; } }; } public int size() { return size; } public String toString() { IntegerEntryIterator iterator = iterator(); StringBuilder builder = new StringBuilder("{"); while (iterator.hasNext()) { iterator.next(); builder.append(iterator.getEntryKey()).append("->").append(iterator.getEntryValue()).append(','); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('}'); return builder.toString(); } } static class Factorization { public static IntegerMultiWayStack factorizeRangePrime(int n) { int maxFactorCnt = (int) MinimumNumberWithMaximumFactors.maximumPrimeFactor(n)[1]; IntegerMultiWayStack stack = new IntegerMultiWayStack(n + 1, n * maxFactorCnt); boolean[] isComp = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (isComp[i]) { continue; } for (int j = i; j <= n; j += i) { isComp[j] = true; stack.addLast(j, i); } } return stack; } } static class IntegerMultiWayStack { private int[] values; private int[] next; private int[] heads; private int alloc; private int stackNum; public IntegerIterator iterator(final int queue) { return new IntegerIterator() { int ele = heads[queue]; public boolean hasNext() { return ele != 0; } public int next() { int ans = values[ele]; ele = next[ele]; return ans; } }; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); values = Arrays.copyOf(values, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; } public IntegerMultiWayStack(int qNum, int totalCapacity) { values = new int[totalCapacity + 1]; next = new int[totalCapacity + 1]; heads = new int[qNum]; stackNum = qNum; } public void addLast(int qId, int x) { alloc(); values[alloc] = x; next[alloc] = heads[qId]; heads[qId] = alloc; } public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < stackNum; i++) { builder.append(i).append(": "); for (IntegerIterator iterator = iterator(i); iterator.hasNext(); ) { builder.append(iterator.next()).append(","); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('\n'); } return builder.toString(); } } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } public static void reverse(int[] data, int l, int r) { while (l < r) { swap(data, l, r); l++; r--; } } public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static interface IntegerIterator { boolean hasNext(); int next(); } static class Graph { public static void addUndirectedEdge(List<UndirectedEdge>[] g, int s, int t) { UndirectedEdge toT = new UndirectedEdge(t); UndirectedEdge toS = new UndirectedEdge(s); toT.rev = toS; toS.rev = toT; g[s].add(toT); g[t].add(toS); } public static List<UndirectedEdge>[] createUndirectedGraph(int n) { List<UndirectedEdge>[] ans = new List[n]; for (int i = 0; i < n; i++) { ans[i] = new ArrayList<>(); } return ans; } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
a834f727aee33753d288e87cb0396cde
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Queue; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { HashMap<Integer, Integer> map = new HashMap<>(); HashMap<Integer, Integer> rev = new HashMap<>(); HashSet<Integer> seen = new HashSet<>(); boolean two = false; ArrayList<Edge>[] graph; public void solve(int testNumber, InputReader in, PrintWriter out) { int cnt = 1; int N = in.nextInt(); int[][] edge = new int[N][2]; for (int i = 0; i < N; i++) { int a = in.nextInt(); ArrayList<Integer> div = new ArrayList<>(); for (int d = 2; d <= Math.sqrt(a); d++) { if (a % d == 0) { int tot = 0; while (a % d == 0) { tot++; a /= d; } if (tot % 2 == 1) { if (!map.containsKey(d)) { map.put(d, cnt++); rev.put(cnt - 1, d); } div.add(d); } } } if (a > 1) { div.add(a); if (!map.containsKey(a)) { map.put(a, cnt++); rev.put(cnt - 1, a); } } if (div.size() == 0) { out.println(1); return; } if (seen.contains(prod(div))) { two = true; } else { seen.add(prod(div)); } if (div.size() > 1) { edge[i] = new int[]{map.get(div.get(0)), map.get(div.get(1))}; } else { edge[i] = new int[]{0, map.get(div.get(0))}; } } rev.put(0, 1); if (two) { out.println(2); return; } graph = new ArrayList[cnt]; for (int i = 0; i < cnt; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < N; i++) { graph[edge[i][0]].add(new Edge(edge[i][1], i)); graph[edge[i][1]].add(new Edge(edge[i][0], i)); } out.println(shortest_cycle(cnt)); } int prod(ArrayList<Integer> div) { if (div.size() == 1) { return div.get(0); } return div.get(0) * div.get(1); } int shortest_cycle(int n) { // To store length of the shortest cycle int ans = Integer.MAX_VALUE; // For all vertices for (int i = 0; i < n; i++) { if (rev.get(i) <= 1000) { // Make distance maximum int[] dist = new int[n]; Arrays.fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; Arrays.fill(par, -1); // Distance of source to source is 0 dist[i] = 0; Queue<Integer> q = new ArrayDeque<>(); // Push the source element q.add(i); // Continue until queue is not empty while (!q.isEmpty()) { // Take the first element int x = q.poll(); // Traverse for all it's childs for (Edge c : graph[x]) { int child = c.a; // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.add(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } } // If graph contains no cycle if (ans == Integer.MAX_VALUE) return -1; // If graph contains cycle else return ans; } class Edge { int i; int a; Edge(int a, int i) { this.i = i; this.a = 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()); } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
51844715d59e33bfd55f9af04eb80e96
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class E1325 { 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[] in = sc.nextIntArr(n); int[] arr = new int[(int) 1e6 + 1]; for (int i = 1; i < arr.length; i++) { for (int j = i; j < arr.length; j += i) { arr[j]++; } } int[][] arr2 = new int[(int) 1e6 + 1][2]; for (int i = 2; i < arr.length; i++) { if (arr2[i][0] == 0) for (int j = i; j < arr.length; j += i) { if (arr2[j][0] == 0) { arr2[j][0] = i; } else arr2[j][1] = i; } } ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 1; i < arr.length; i++) { if (arr[i] == 2) { primes.add(i); } } for (int i = 0; i < (int) 1e6 + 1; i++) { if (arr[i] > 7) continue; if (arr2[i][1] == 0) { if (arr[i] % 2 == 1) arr2[i][0] = 0; } else if (arr[i] == 6) { if (i == arr2[i][0] * arr2[i][0] * arr2[i][1]) { arr2[i][0] = arr2[i][1]; arr2[i][1] = 0; } else arr2[i][1] = 0; } } HashSet<Integer> test = new HashSet<Integer>(); for (int i = 0; i < in.length; i++) { if (arr2[in[i]][0] == 0) { pw.println(1); pw.close(); return; } if (arr2[in[i]][1] == 0) { in[i] = arr2[in[i]][0]; } test.add(in[i]); } if (test.size() != in.length) { pw.println(2); pw.close(); return; } int[] hm = new int[(int) 1e6 + 1]; for (int i = 0; i < primes.size(); i++) hm[primes.get(i)] = i; ArrayList<Integer> adjList[] = new ArrayList[primes.size() + 1]; for (int i = 0; i < adjList.length; i++) { adjList[i] = new ArrayList<Integer>(); } hm[1] = adjList.length - 1; for (int i = 0; i < n; i++) { int x = in[i]; int k = arr2[x][0]; int h = x / k; k = hm[k]; h = hm[h]; adjList[k].add(h); adjList[h].add(k); } int[][] adjList2 = new int[adjList.length][]; for (int i = 0; i < adjList2.length; i++) { adjList2[i] = new int[adjList[i].size()]; for (int j = 0; j < adjList2[i].length; j++) { adjList2[i][j] = adjList[i].get(j); } } adjList = null; int idx = 0; int min = (int) 1e9; // for (int i = 0; i < 10; i++) { // pw.println(adjList[i]); // } // pw.println(adjList[adjList.length - 1]); while (true) { if (primes.get(idx) * primes.get(idx) > (int) 1e6) break; int[] dist = new int[adjList2.length]; Arrays.fill(dist, -1); dist[idx] = 0; int[] par = new int[adjList2.length]; Arrays.fill(par, -1); Queue<Integer> q = new LinkedList<Integer>(); q.add(idx); int f = (int) 1e9; while (!q.isEmpty()) { int cur = q.poll(); for (int x : adjList2[cur]) { if (dist[x] == -1) { dist[x] = dist[cur] + 1; par[x] = cur; q.add(x); } else if (x != idx && x != par[cur]) { f = Math.min(dist[cur] + dist[x] + 1, f); // if (idx == 0) // pw.println(f + " " + cur + " " + x + " " + (dist[cur] + dist[x] + 1)); } } } min = Math.min(min, f); idx++; } pw.println(min == (int) 1e9 ? -1 : min); 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 { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
a0365cca3457af8088c61a1f1b9ab290
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class E1325 { 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[] in = sc.nextIntArr(n); int[] arr = new int[(int) 1e6 + 1]; for (int i = 1; i < arr.length; i++) { for (int j = i; j < arr.length; j += i) { arr[j]++; } } int[][] arr2 = new int[(int) 1e6 + 1][2]; for (int i = 2; i < arr.length; i++) { if (arr2[i][0] == 0) for (int j = i; j < arr.length; j += i) { if (arr2[j][0] == 0) { arr2[j][0] = i; } else arr2[j][1] = i; } } ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 1; i < arr.length; i++) { if (arr[i] == 2) { primes.add(i); } } for (int i = 0; i < (int) 1e6 + 1; i++) { if (arr[i] > 7) continue; if (arr2[i][1] == 0) { if (arr[i] % 2 == 1) arr2[i][0] = 0; } else if (arr[i] == 6) { if (i == arr2[i][0] * arr2[i][0] * arr2[i][1]) { arr2[i][0] = arr2[i][1]; arr2[i][1] = 0; } else arr2[i][1] = 0; } } HashSet<Integer> test = new HashSet<Integer>(); for (int i = 0; i < in.length; i++) { if (arr2[in[i]][0] == 0) { pw.println(1); pw.close(); return; } if (arr2[in[i]][1] == 0) { in[i] = arr2[in[i]][0]; } test.add(in[i]); } if (test.size() != in.length) { pw.println(2); pw.close(); return; } int[] hm = new int[(int) 1e6 + 1]; for (int i = 0; i < primes.size(); i++) hm[primes.get(i)] = i; ArrayList<Integer> adjList[] = new ArrayList[primes.size() + 1]; for (int i = 0; i < adjList.length; i++) { adjList[i] = new ArrayList<Integer>(); } hm[1] = adjList.length - 1; for (int i = 0; i < n; i++) { int x = in[i]; int k = arr2[x][0]; int h = x / k; k = hm[k]; h = hm[h]; adjList[k].add(h); adjList[h].add(k); } int idx = 0; int min = (int) 1e9; // for (int i = 0; i < 10; i++) { // pw.println(adjList[i]); // } // pw.println(adjList[adjList.length - 1]); while (true) { if (primes.get(idx) * primes.get(idx) > (int) 1e6) break; int[] dist = new int[adjList.length]; Arrays.fill(dist, -1); dist[idx] = 0; int[] par = new int[adjList.length]; Arrays.fill(par, -1); Queue<Integer> q = new LinkedList<Integer>(); q.add(idx); int f = (int) 1e9; while (!q.isEmpty()) { int cur = q.poll(); for (int x : adjList[cur]) { if (dist[x] == -1) { dist[x] = dist[cur] + 1; par[x] = cur; q.add(x); } else if (x != idx && x != par[cur]) { f = Math.min(dist[cur] + dist[x] + 1, f); // if (idx == 0) // pw.println(f + " " + cur + " " + x + " " + (dist[cur] + dist[x] + 1)); } } } min = Math.min(min, f); idx++; } pw.println(min == (int) 1e9 ? -1 : min); 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 { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
99b91169e60de6499848570a68a5429c
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); boolean two = false; for(int i = 0; i < n; i++) { int a = reduce(sc.nextInt()); if(a == 1) { System.out.println(1); return; } if(set.contains(a)) { two = true; } set.add(a); } if(two) { System.out.println(2); return; } //all numbers are reduces and distinct now, that means no double edges HashMap<Integer, Integer> ps = new HashMap<>(); int count = 0; ArrayList<Pair> pairs = new ArrayList<>(); for(int x: set) { ArrayList<Integer> divs = new ArrayList<>(); for(int d = 2; d*d <= x; d++) { if(x % d == 0) { divs.add(d); if(!ps.containsKey(d)) { ps.put(d, count++); } x /= d; } } if(x >= 1) { if(!ps.containsKey(x)) { ps.put(x, count++); } divs.add(x); } if(divs.size() == 1) { divs.add(1); if(!ps.containsKey(1)) { ps.put(1, count++); } } pairs.add(new Pair(divs.get(0), divs.get(1))); } int p = count; int[] primes = new int[p]; for(int prime: ps.keySet()) { primes[ps.get(prime)] = prime; } ArrayList<Integer>[] g = new ArrayList[p]; for(int i = 0; i < p; i++) { g[i] = new ArrayList<>(); } for(Pair pr: pairs) { g[ps.get(pr.a)].add(ps.get(pr.b)); g[ps.get(pr.b)].add(ps.get(pr.a)); } //find cycle int min = p+1; for(int u0 = 0; u0 < p; u0++) { if(primes[u0] <= 1000) { // min = Math.min(min, shortestCycle(g, p, u0)); } } if(min > p) { System.out.println(-1); } else { System.out.println(min); } } static int shortestCycle(ArrayList<Integer>[] g, int n, int u0) { int[] p = new int[n]; int[] dist = new int[n]; Arrays.fill(p, -1); Arrays.fill(dist, -1); LinkedList<Integer> q = new LinkedList<>(); q.add(u0); dist[u0] = 0; while(!q.isEmpty()) { int u = q.removeFirst(); for(int v: g[u]) { if(dist[v] >= 0 && p[u] != v) { return dist[u] + dist[v] + 1; } if(dist[v] < 0) { p[v] = u; dist[v] = dist[u]+1; q.add(v); } } } return n+1; } static class Pair{ int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } } static boolean isPrime(int x) { for(int d = 2; d*d <= x; d++) { if(x % d == 0) return false; } return true; } static int reduce(int x) { for(int d = 2; d*d <= x; d++) { if(x % d == 0) { while(x % (d*d) == 0) x /= (d*d); } } return x; } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { 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()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
9c64e6ad2441b2965c7ca825addbe98a
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class E1325 { 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[] in = sc.nextIntArr(n); int[] arr = new int[(int) 1e6 + 1]; for (int i = 1; i < arr.length; i++) { for (int j = i; j < arr.length; j += i) { arr[j]++; } } int[][] arr2 = new int[(int) 1e6 + 1][2]; for (int i = 2; i < arr.length; i++) { if (arr2[i][0] == 0) for (int j = i; j < arr.length; j += i) { if (arr2[j][0] == 0) { arr2[j][0] = i; } else arr2[j][1] = i; } } ArrayList<Integer> primes = new ArrayList<Integer>(); for (int i = 1; i < arr.length; i++) { if (arr[i] == 2) { primes.add(i); } } for (int i = 0; i < (int) 1e6 + 1; i++) { if (arr[i] > 7) continue; if (arr2[i][1] == 0) { if (arr[i] % 2 == 1) arr2[i][0] = 0; } else if (arr[i] == 6) { if (i == arr2[i][0] * arr2[i][0] * arr2[i][1]) { arr2[i][0] = arr2[i][1]; arr2[i][1] = 0; } else arr2[i][1] = 0; } } HashSet<Integer> test = new HashSet<Integer>(); for (int i = 0; i < in.length; i++) { if (arr2[in[i]][0] == 0) { pw.println(1); pw.close(); return; } if (arr2[in[i]][1] == 0) { in[i] = arr2[in[i]][0]; } test.add(in[i]); } if (test.size() != in.length) { pw.println(2); pw.close(); return; } int[] hm = new int[(int) 1e6 + 1]; for (int i = 0; i < primes.size(); i++) hm[primes.get(i)] = i; ArrayList<Integer> adjList[] = new ArrayList[primes.size() + 1]; for (int i = 0; i < adjList.length; i++) { adjList[i] = new ArrayList<Integer>(); } hm[1] = adjList.length - 1; for (int i = 0; i < n; i++) { int x = in[i]; int k = arr2[x][0]; int h = x / k; k = hm[k]; h = hm[h]; adjList[k].add(h); adjList[h].add(k); } int idx = 0; int min = (int) 1e9; // for (int i = 0; i < 10; i++) { // pw.println(adjList[i]); // } // pw.println(adjList[adjList.length - 1]); while (true) { if (primes.get(idx) * primes.get(idx) > (int) 1e6) break; int[] dist = new int[adjList.length]; Arrays.fill(dist, -1); dist[idx] = 0; int[] par = new int[adjList.length]; Arrays.fill(par, -1); Queue<Integer> q = new LinkedList<Integer>(); q.add(idx); int f = (int) 1e9; while (!q.isEmpty()) { int cur = q.poll(); for (int x : adjList[cur]) { if (dist[x] == -1) { dist[x] = dist[cur] + 1; par[x] = cur; q.add(x); } else if (x != idx && x != par[cur]) { f = Math.min(dist[cur] + dist[x] + 1, f); // if (idx == 0) // pw.println(f + " " + cur + " " + x + " " + (dist[cur] + dist[x] + 1)); } } } min = Math.min(min, f); idx++; } pw.println(min == (int) 1e9 ? -1 : min); 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 { return Double.parseDouble(next()); } public int[] nextIntArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public boolean ready() throws IOException { return br.ready(); } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
c112a09f0755e699b122b29d2849c53d
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.*; import java.util.*; public class GFG { private static int MAX=1000000000; private static int factor(int a){ int n=1,cnt=0; while(a%2==0){ a/=2; cnt++; } if(cnt%2!=0) n=2; for(int i=3;i*i<=a;i+=2){ cnt=0; while(a%i==0){ a/=i; cnt++; } if(cnt%2!=0) n*=i; } if(a!=1) n*=a; return n; } private static void find(int a,Map<Integer,ArrayList<Integer>> map,int[] prime){ ArrayList<Integer> A=new ArrayList<>(); for(int i=2;i*i<=a;i++){ if(a%i==0){ A.add(i); A.add(a/i); prime[i]=1; prime[a/i]=1; map.put(a,A); return; } } A.add(a); A.add(1); prime[a]=1; map.put(a,A); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //int t = Integer.parseInt(br.readLine().trim()); //while (t-- != 0) { int n = Integer.parseInt(br.readLine().trim()); String s = br.readLine().trim(); String ss[]=s.split("\\s+"); int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(ss[i]); HashSet<Integer> set=new HashSet<>(); for(int i:a) set.add(factor(i)); if(set.contains(1)){ System.out.println("1"); return; } if(set.size()!=n){ System.out.println("2"); return; } int prime[]=new int[1000000]; Map<Integer,ArrayList<Integer>> map=new HashMap<>(); for(int i:set) find(i,map,prime); int j=0; int pi[]=new int[1000000]; ArrayList<Integer> P=new ArrayList<>(); pi[1]=j++; P.add(1); for(int i=2;i<pi.length;i++){ if(prime[i]!=0){ pi[i]=j++; P.add(i); } } ArrayList<Integer> G[]=new ArrayList[j]; for(int i=0;i<j;i++) G[i]=new ArrayList<>(); for(int i:set){ ArrayList<Integer> A=map.get(i); int u=pi[A.get(0)]; int v=pi[A.get(1)]; // System.out.println(i+"="+u+" "+v); G[u].add(v); G[v].add(u); } int ans=MAX; for(int i=0;i<j;i++){ if(P.get(i)*P.get(i)>1000000) break; int d[]=new int[j]; Arrays.fill(d,MAX); d[i]=0; int p[]=new int[j]; Queue<Integer> q=new LinkedList<>(); q.add(i); while(!q.isEmpty()){ int u=q.poll(); for(int k=0;k<G[u].size();k++){ int v=G[u].get(k); if(d[v]==MAX){ d[v]=d[u]+1; p[v]=u; q.add(v); } else if(p[v]!=u&&p[u]!=v) ans=Math.min(ans,d[u]+d[v]+1); } } } System.out.println((ans==MAX)?-1:ans); //} } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
89c7c0fdd34b56a953b81dd6a5adecb2
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class E { private static int pf[]; private static final int lim=(int)(1e6+5); private static ArrayList<Integer> edge[]; private static int dist[], parent[]; private static ArrayList<Integer> vis; private static void sieve() { int k=0; for(int i=2;i<lim;i++) { if(pf[i]==0) { pf[i]=i; if((long)i*i<lim) for(int j=i*i;j<lim;j+=i) { if(pf[j]==0) pf[j]=i; } } } } private static int normalize(int N) { int val=1; while (N>1) { int tmp=pf[N]; int c=0; while (pf[N]==tmp) { c^=1; N/=tmp; } if(c==1) val*=tmp; } return val; } private static int BFS(int u) { ArrayDeque<Integer> queue=new ArrayDeque<>(); int ans=lim; queue.add(u); dist[u]=0; vis.add(u); outer: while (!queue.isEmpty()) { int v=queue.poll(); int d=dist[v]; for(int child:edge[v]) { if(dist[child]==-1) { parent[child]=v; dist[child]=d+1; queue.add(child); vis.add(child); } else if(parent[v]!=child) { ans= d + dist[child] + 1; break outer; } } } for(int i:vis) dist[i]=-1; vis.clear(); return ans; } public static void main(String[] args) throws IOException { Reader r=new Reader(); int i,N,max=0; N=r.nextInt(); int a[]=new int[N]; for(i=0;i<N;i++) a[i]=r.nextInt(); for(i=0;i<N;i++) max=Math.max(max,a[i]); vis=new ArrayList<>(); pf=new int[lim]; edge=new ArrayList[lim]; dist=new int[lim]; parent=new int[lim]; for(i=0;i<lim;i++) dist[i]=-1; for(i=0;i<lim;i++) edge[i]=new ArrayList<>(); sieve(); int ans=lim; for(i=0;i<N;i++) { a[i]=normalize(a[i]); if(a[i]==1) { System.out.println(1); System.exit(0); } int u=pf[a[i]]; int v=a[i]/u; edge[u].add(v); edge[v].add(u); } for(i=0;i<lim;i++) { Collections.sort(edge[i]); for(int j=0;j<edge[i].size()-1;j++) { if(edge[i].get(j)==edge[i].get(j+1)) { System.out.println(2); System.exit(0); } } } for(i=1;i<=1000;i++) { if(edge[i].isEmpty()) continue; ans=Math.min(ans,BFS(i)); } System.out.println(ans==lim?-1:ans); } static class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt); }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret; }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1; }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++]; }public void close() throws IOException{if(din==null) return;din.close();} } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
7e521c1f401839d16d12e2f2f7ed84dd
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class E { private static final int lim=(int)(1e6+5); private static int[] dist, parent, spf; private static ArrayList<Integer> edge[], vis; private static void sieve() { for(int i=2;i<lim;i++) { if(spf[i]==0) { spf[i]=i; if((long)i*i<lim) for(int j=i*i;j<lim;j+=i) { if(spf[j]==0) spf[j]=i; } } } } private static int normalise(int N) { int val=1; while (N>1) { int f=spf[N]; int c=0; while (spf[N]==f) { c^=1; N/=f; } if(c==1) val*=f; } return val; } private static int cycleLength(int u) { vis.clear(); vis.add(u); dist[u]=0; int ans=lim; ArrayDeque<Integer> queue=new ArrayDeque<>(); queue.add(u); outer: while (!queue.isEmpty()) { int v=queue.poll(); for(int child:edge[v]) { if(dist[child]==-1) { dist[child]=dist[v]+1; parent[child]=v; vis.add(child); queue.add(child); } else if(parent[v]!=child) { ans=dist[v]+dist[child]+1; break outer; } } } for(int i:vis) dist[i]=-1; return ans; } public static void main(String[] args) throws IOException { Reader r=new Reader(); int i,N; vis=new ArrayList<>(); spf=new int[lim]; dist=new int[lim]; parent=new int[lim]; edge=new ArrayList[lim]; for(i=0;i<lim;i++) edge[i]=new ArrayList<>(); Arrays.fill(dist,-1); sieve(); N=r.nextInt(); int a[]=new int[N]; for(i=0;i<N;i++) a[i]=r.nextInt(); for(i=0;i<N;i++) { a[i]=normalise(a[i]); if(a[i]==1) { System.out.println(1); System.exit(0); } int u=spf[a[i]]; int v=a[i]/u; edge[u].add(v); edge[v].add(u); } for(i=0;i<lim;i++) { Collections.sort(edge[i]); for(int j=0;j<edge[i].size()-1;j++) { if(edge[i].get(j)==edge[i].get(j+1)) { System.out.println(2); System.exit(0); } } } int ans=lim; for(i=1;i<=1000;i++) { if(edge[i].isEmpty()) continue; ans=Math.min(ans,cycleLength(i)); } System.out.println(ans==lim?-1:ans); } static class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt); }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret; }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1; }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++]; }public void close() throws IOException{if(din==null) return;din.close();} } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
47934459dc2203e6382f6f093ec4e591
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class E { private static final int lim=(int)(1e6+5); private static int[] dist, parent, spf; private static ArrayList<Integer> edge[], vis; private static void sieve() { for(int i=2;i<lim;i++) { if(spf[i]==0) { spf[i]=i; if((long)i*i<lim) for(int j=i*i;j<lim;j+=i) { if(spf[j]==0) spf[j]=i; } } } } private static int normalise(int N) { int val=1; while (N>1) { int f=spf[N]; int c=0; while (spf[N]==f) { c^=1; N/=f; } if(c==1) val*=f; } return val; } private static int cycleLength(int u) { vis.clear(); vis.add(u); dist[u]=0; int ans=lim; ArrayDeque<Integer> queue=new ArrayDeque<>(); queue.add(u); outer: while (!queue.isEmpty()) { int v=queue.poll(); for(int child:edge[v]) { if(dist[child]==-1) { dist[child]=dist[v]+1; parent[child]=v; vis.add(child); queue.add(child); } else if(parent[v]!=child) { ans=dist[v]+dist[child]+1; break outer; } } } for(int i:vis) dist[i]=-1; return ans; } public static void main(String[] args) throws IOException { Reader r=new Reader(); int i,N,max=0; vis=new ArrayList<>(); spf=new int[lim]; dist=new int[lim]; parent=new int[lim]; edge=new ArrayList[lim]; for(i=0;i<lim;i++) edge[i]=new ArrayList<>(); Arrays.fill(dist,-1); sieve(); N=r.nextInt(); int a[]=new int[N]; for(i=0;i<N;i++) a[i]=r.nextInt(); for(i=0;i<N;i++) { a[i]=normalise(a[i]); max=Math.max(a[i],max); if(a[i]==1) { System.out.println(1); System.exit(0); } int u=spf[a[i]]; int v=a[i]/u; edge[u].add(v); edge[v].add(u); } for(i=0;i<lim;i++) { Collections.sort(edge[i]); for(int j=0;j<edge[i].size()-1;j++) { if(edge[i].get(j)==edge[i].get(j+1)) { System.out.println(2); System.exit(0); } } } int ans=lim; int sqrt=(int)(Math.sqrt(max)); for(i=1;i<=sqrt;i++) { if(edge[i].isEmpty()) continue; ans=Math.min(ans,cycleLength(i)); } System.out.println(ans==lim?-1:ans); } static class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt); }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret; }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1; }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++]; }public void close() throws IOException{if(din==null) return;din.close();} } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
3a8d958efd046aaabb754b2fac8cdb99
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class E { private static int pf[]; private static final int lim=(int)(1e6+5); private static ArrayList<Integer> edge[]; private static int dist[], parent[]; private static ArrayList<Integer> vis; private static void sieve() { int k=0; for(int i=2;i<lim;i++) { if(pf[i]==0) { pf[i]=i; if((long)i*i<lim) for(int j=i*i;j<lim;j+=i) { if(pf[j]==0) pf[j]=i; } } } } private static int normalize(int N) { int val=1; while (N>1) { int tmp=pf[N]; int c=0; while (pf[N]==tmp) { c^=1; N/=tmp; } if(c==1) val*=tmp; } return val; } private static int BFS(int u) { ArrayDeque<Integer> queue=new ArrayDeque<>(); int ans=lim; queue.add(u); dist[u]=0; parent[u]=u; vis.add(u); outer: while (!queue.isEmpty()) { int v=queue.poll(); int d=dist[v]; for(int child:edge[v]) { if(dist[child]==-1) { parent[child]=v; dist[child]=d+1; queue.add(child); vis.add(child); } else if(parent[v]!=child) { ans= d + dist[child] + 1; break outer; } } } for(int i:vis) dist[i]=-1; vis.clear(); return ans; } public static void main(String[] args) throws IOException { Reader r=new Reader(); int i,N,max=0; N=r.nextInt(); int a[]=new int[N]; for(i=0;i<N;i++) a[i]=r.nextInt(); for(i=0;i<N;i++) max=Math.max(max,a[i]); vis=new ArrayList<>(); pf=new int[lim]; edge=new ArrayList[lim]; dist=new int[lim]; parent=new int[lim]; for(i=0;i<lim;i++) dist[i]=-1; for(i=0;i<lim;i++) edge[i]=new ArrayList<>(); sieve(); int ans=lim; for(i=0;i<N;i++) { a[i]=normalize(a[i]); if(a[i]==1) { System.out.println(1); System.exit(0); } int u=pf[a[i]]; int v=a[i]/u; edge[u].add(v); edge[v].add(u); } for(i=0;i<lim;i++) { Collections.sort(edge[i]); for(int j=0;j<edge[i].size()-1;j++) { if(edge[i].get(j)==edge[i].get(j+1)) { System.out.println(2); System.exit(0); } } } for(i=1;i<=1000;i++) { if(edge[i].isEmpty()) continue; ans=Math.min(ans,BFS(i)); } System.out.println(ans==lim?-1:ans); } static class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt); }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret; }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1; }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++]; }public void close() throws IOException{if(din==null) return;din.close();} } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
acf169d386b2830b0ddc0e97707786fb
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
//created by Whiplash99 import java.io.*; import java.util.*; public class E { private static final int lim=(int)(1e6+5); private static int[] dist, parent, spf; private static ArrayList<Integer> edge[], vis; private static void sieve() { for(int i=2;i<lim;i++) { if(spf[i]==0) { spf[i]=i; if((long)i*i<lim) for(int j=i*i;j<lim;j+=i) { if(spf[j]==0) spf[j]=i; } } } } private static int normalise(int N) { int val=1; while (N>1) { int f=spf[N]; int c=0; while (spf[N]==f) { c^=1; N/=f; } if(c==1) val*=f; } return val; } private static int cycleLength(int u) { vis.clear(); vis.add(u); dist[u]=0; int ans=-1; ArrayDeque<Integer> queue=new ArrayDeque<>(); queue.add(u); while (ans==-1&&!queue.isEmpty()) { int v=queue.poll(); for(int child:edge[v]) { if(dist[child]==-1) { dist[child]=dist[v]+1; parent[child]=v; vis.add(child); queue.add(child); } else if(parent[v]!=child) { ans=dist[v]+dist[child]+1; break; } } } for(int i:vis) dist[i]=-1; return ans; } public static void main(String[] args) throws IOException { Reader r=new Reader(); int i,N; vis=new ArrayList<>(); spf=new int[lim]; dist=new int[lim]; parent=new int[lim]; edge=new ArrayList[lim]; for(i=0;i<lim;i++) edge[i]=new ArrayList<>(); Arrays.fill(dist,-1); sieve(); N=r.nextInt(); int a[]=new int[N]; for(i=0;i<N;i++) a[i]=r.nextInt(); for(i=0;i<N;i++) { a[i]=normalise(a[i]); if(a[i]==1) { System.out.println(1); System.exit(0); } int u=spf[a[i]]; int v=a[i]/u; edge[u].add(v); edge[v].add(u); } for(i=0;i<lim;i++) { Collections.sort(edge[i]); for(int j=0;j<edge[i].size()-1;j++) { if(edge[i].get(j)==edge[i].get(j+1)) { System.out.println(2); System.exit(0); } } } int ans=lim; for(i=1;i<=1000;i++) { if(edge[i].isEmpty()) continue; int tmp=cycleLength(i); if(tmp!=-1) ans=Math.min(ans,tmp); } System.out.println(ans==lim?-1:ans); } static class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public Reader(String file_name) throws IOException{din=new DataInputStream(new FileInputStream(file_name));buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0; }public String readLine() throws IOException{byte[] buf=new byte[64];int cnt=0,c;while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt); }public int nextInt() throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public long nextLong() throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret; }public double nextDouble() throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret; }private void fillBuffer() throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1; }private byte read() throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++]; }public void close() throws IOException{if(din==null) return;din.close();} } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
d2fe221687165c6482158c596e6e01ed
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
//package Round628; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; /** * @author sguar <shugangcao@gmail.com> * strive for greatness * Created on 2020-01-10 */ public class E { InputStream is; PrintWriter out; private static final String INPUT_FILE_NAME = "/Users/sguar/IdeaProjects/kotlinLearn/src/input.txt"; private static final int N = 1_000_001; private static final int INF = N + 1; ArrayList<Integer>[] path; int[] dist; Set<Integer> primeSet = new HashSet<>(); void solve() { int n = ni(); int[] a = na(n); //Arrays.sort(a); path = new ArrayList[N]; dist = new int[N]; for (int i = 1; i < N; i++) { path[i] = new ArrayList<>(); } PrimeUtil primeUtil = new PrimeUtil(N); debug(primeUtil.factor[10]); debug(primeUtil.getPrimeFactors(10)); debug(primeUtil.getPrimeFactors(5)); debug(primeUtil.getPrimeFactors(100001)); for (int x : a) { List<Integer> primesOfAi = primeUtil.getPrimeFactors(x); if (primesOfAi.isEmpty()) { debug("1", x); out.println(1); out.flush(); System.exit(0); } else if (primesOfAi.size() == 1) { primesOfAi.add(1); } int u = primesOfAi.get(0); int v = primesOfAi.get(1); path[u].add(v); path[v].add(u); primeSet.addAll(primesOfAi); } int result = primeSet.stream().filter(prime -> prime <= 1000) .map(this::getCircleLength) .reduce(Math::min) .get(); out.println(result >= INF ? -1 : result); } private int getCircleLength(int start) { int ans = INF; primeSet.forEach(i -> dist[i] = INF); dist[start] = 0; Queue<Integer> queue = new ArrayDeque<>(); queue.add(start); while (!queue.isEmpty()) { int now = queue.poll(); // debug(now, dist[now], path[now]); for (int next : path[now]) { if (dist[next] >= dist[now]) { ans = Math.min(ans, dist[next] + dist[now] + 1); //debug(next, dist[next], ans); } if (dist[next] > dist[now] + 1) { dist[next] = dist[now] + 1; queue.add(next); } } } return ans; } class PrimeUtil { PrimeUtil(int primeMax) { init(primeMax); } int [] factor; void init(int primeMax) { factor = new int[primeMax]; for(int i = 2; i < primeMax; i++) { if(factor[i] == 0) { for(int j = i; j >= i && j < primeMax; j += i) { if(factor[j] == 0) { factor[j] = i; } } } } } List<Integer> getPrimeFactors(int x) { List<Integer> factors = new ArrayList<>(); while (x > 1) { int fac = factor[x]; int cnt = 0; while (x % fac == 0) { x /= fac; cnt++; } if (cnt % 2 == 1) { factors.add(fac); } } return factors; } } class Pair { int x; int y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "x: " + x + ", y: " + y; } } public static long invl(long a, long mod) { long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } void run() throws Exception { is = oj ? System.in : new FileInputStream(INPUT_FILE_NAME); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); debug(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new E().run(); } private byte[] inbuf = new byte[1024]; int lenbuf = 0; int ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void debug(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } private void debug(Object a, Object o) { if (!oj) { System.out.println(a.toString() + ": " + o.toString()); } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
8aafafbcace3c95756ae04e2cb536889
train_001.jsonl
1584196500
You are given an array $$$a$$$ of length $$$n$$$ that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { static final long MOD = 998244353L; static final long INF = 1000000000000000007L; //static final long MOD = 1000000007L; //static final int INF = 1000000007; //static long[] factorial; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); HashMap<Integer,Integer> primes = new HashMap<Integer,Integer>(); primes.put(1,0); boolean[] euclid = new boolean[1000001]; int index = 1; for (int p = 2; p <= 1000000; p++) { if (! euclid[p]) { primes.put(p,index); index++; for (int i = 2*p; i <= 1000000; i += p) { euclid[i] = true; } } } ArrayList<Integer>[] graph = new ArrayList[primes.size()]; for (int i = 0; i < graph.length; i++) graph[i] = new ArrayList<Integer>(); int N = sc.ni(); for (int i = 0; i < N; i++) { int n = sc.ni(); for (int square = 1000; square >= 2; square--) { if (n % (square*square) == 0) { n /= (square*square); break; } } boolean pq = false; for (int p = 2; p*p <= n; p++) { if (n % p == 0) { int q = n/p; int n1 = primes.get(p); int n2 = primes.get(q); graph[n1].add(n2); graph[n2].add(n1); pq = true; break; } } if (!pq) { graph[0].add(primes.get(n)); if (n>1) graph[primes.get(n)].add(0); } } int ans = shortest_cycle(graph); boolean two = false; checktwo: for (int i = 1; i < graph.length; i++) { Collections.sort(graph[i]); for (int j = 1; j < graph[i].size(); j++) { if (graph[i].get(j)==graph[i].get(j-1)) { two = true; break checktwo; } } } if (two) ans = Math.min(ans,2); if (ans == Integer.MAX_VALUE) pw.println(-1); else pw.println(ans); pw.close(); } static int shortest_cycle(ArrayList<Integer>[] graph) { //number of vertices is the number of primes int n = graph.length; // To store length of the shortest cycle int ans = Integer.MAX_VALUE; // For all vertices for (int i = 0; i <= 168; i++) { // Make distance maximum int[] dist = new int[n]; Arrays.fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; Arrays.fill(par, -1); // Distance of source to source is 0 dist[i] = 0; ArrayDeque<Integer> q = new ArrayDeque<Integer>(); // Push the source element q.add(i); // Continue until queue is not empty while (!q.isEmpty()) { // Take the first element int x = q.poll(); // Traverse for all it's childs for (int child : graph[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.add(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } return ans; } public static long dist(long[] p1, long[] p2) { return (Math.abs(p2[0]-p1[0])+Math.abs(p2[1]-p1[1])); } //Find the GCD of two numbers public static long gcd(long a, long b) { if (a < b) return gcd(b,a); if (b == 0) return a; else return gcd(b,a%b); } //Fast exponentiation (x^y mod m) public static long power(long x, long y, long m) { if (y < 0) return 0L; long ans = 1; x %= m; while (y > 0) { if(y % 2 == 1) ans = (ans * x) % m; y /= 2; x = (x * x) % m; } return ans; } public static int[] shuffle(int[] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static long[] shuffle(long[] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[][] shuffle(int[][] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { //return a[0]-b[0]; //ascending order if (a[1] != b[1]) { return (a[1]-b[1]); } else { return (a[0]-b[0]); } } }); return array; } public static long[][] sort(long[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] < b[0]) return -1; else if (a[0] > b[0]) return 1; else return 0; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n1 4 6", "4\n2 3 6 6", "3\n6 15 10", "4\n2 3 5 7"]
3 seconds
["1", "2", "3", "-1"]
NoteIn the first sample, you can choose a subsequence $$$[1]$$$.In the second sample, you can choose a subsequence $$$[6, 6]$$$.In the third sample, you can choose a subsequence $$$[6, 15, 10]$$$.In the fourth sample, there is no such subsequence.
Java 8
standard input
[ "graphs", "number theory", "shortest paths", "dfs and similar", "brute force" ]
22a43ccaa9e5579dd193bc941855b47d
The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.
2,600
Output the length of the shortest non-empty subsequence of $$$a$$$ product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".
standard output
PASSED
bf188bad82ff1d06e3d358c47677968f
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.text.*; import java.io.*; import java.math.*; public class code5 { InputStream is; PrintWriter out; static long mod=pow(10,9)+7; static int dx[]={0,0,1,-1},dy[]={1,-1,0,0}; void solve() throws Exception { int n=ni(); int a[]=na(n); int max=1000000; int dp[]=new int[max+1]; boolean avail[]=new boolean[max+1]; for(int i=0;i<n;i++) avail[a[i]]=true; int ans=0; for(int j=max;j>=1;j--) { if(!avail[j]) continue; int count=0; for(int k=j;k<=max;k+=j) { count=Math.max(count,dp[k]); } dp[j]=count+1; ans=Math.max(dp[j],ans); } out.println(ans); } ArrayList<Integer> al[]; void take(int n,int m) { al=new ArrayList[n]; for(int i=0;i<n;i++) al[i]=new ArrayList<Integer>(); for(int i=0;i<m;i++) { int x=ni()-1; int y=ni()-1; al[x].add(y); al[y].add(x); } } int check(long n) { int count=0; while(n!=0) { if(n%10!=0) break; n/=10; count++; } return count; } public static int count(int x) { int num=0; while(x!=0) { x=x&(x-1); num++; } return num; } static long d, x, y; void extendedEuclid(long A, long B) { if(B == 0) { d = A; x = 1; y = 0; } else { extendedEuclid(B, A%B); long temp = x; x = y; y = temp - (A/B)*y; } } long modInverse(long A,long M) //A and M are coprime { extendedEuclid(A,M); return (x%M+M)%M; //x may be negative } public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } static class Pair implements Comparable<Pair>{ int x,y,k; int i,dir; Pair (int xx,int yy){ this.x=xx; this.y=yy; this.k=k; } public int compareTo(Pair o) { if(this.y!=o.y) return this.y-o.y; return this.k-o.k; } public String toString(){ return x+" "+y+" "+k+" "+i;} 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 static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(y==0) return x; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(y==0) return x; return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new code5().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); //new code5().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
4401ab08f1f9d039d3b633f04ce0b37f
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class _566F { static final int MAX = 1111111; static int n; static int[] cnt = new int[MAX]; static int[] f = new int[MAX]; static List<Integer>[] factors = new List[MAX]; static { for (int i=0; i<factors.length; i++) factors[i] = new ArrayList<>(1); for (int i=2; i * i < MAX; i++) if (factors[i].size() == 0) { for (int j=i; j<MAX; j+=i) factors[j].add(i); } } public static void main(String[] args) throws Exception { Reader.init(System.in); BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out)); n = Reader.nextInt(); for (int i=0; i<n; i++) cnt[Reader.nextInt()]++; for (int i=1; i<MAX; i++) { f[i] += cnt[i]; int max = 0; for (int factor : factors[i]) max = Math.max(max, f[i / factor]); f[i] += max; } System.out.println(ArrayUtil.max(f)); cout.close(); } static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> { final U _1; final V _2; private Pair(U key, V val) { this._1 = key; this._2 = val; } public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) { return new Pair<U, V>(_1, _2); } @Override public String toString() { return _1 + " " + _2; } @Override public int hashCode() { int res = 17; res = res * 31 + _1.hashCode(); res = res * 31 + _2.hashCode(); return res; } @Override public int compareTo(Pair<U, V> that) { int res = this._1.compareTo(that._1); if (res < 0 || res > 0) return res; else return this._2.compareTo(that._2); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Pair)) return false; Pair<?, ?> that = (Pair<?, ?>) obj; return _1.equals(that._1) && _2.equals(that._2); } } /** Class for buffered reading int and double values */ static class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { // TODO add check for eof if necessary tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } } static class ArrayUtil { static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(long[] a, int i, int j) { long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(double[] a, int i, int j) { double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(char[] a, int i, int j) { char tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void swap(boolean[] a, int i, int j) { boolean tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void reverse(int[] a, int i, int j) { for (; i < j; i++, j--) swap(a, i, j); } static void reverse(long[] a, int i, int j) { for (; i < j; i++, j--) swap(a, i, j); } static void reverse(double[] a, int i, int j) { for (; i < j; i++, j--) swap(a, i, j); } static void reverse(char[] a, int i, int j) { for (; i < j; i++, j--) swap(a, i, j); } static void reverse(boolean[] a, int i, int j) { for (; i < j; i++, j--) swap(a, i, j); } static long sum(int[] a) { int 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 double sum(double[] a) { double sum = 0; for (double i : a) sum += i; return sum; } static int max(int[] a) { int max = Integer.MIN_VALUE; for (int i : a) if (i > max) max = i; return max; } static int min(int[] a) { int min = Integer.MAX_VALUE; for (int i : a) if (i < min) min = i; return min; } static long max(long[] a) { long max = Long.MIN_VALUE; for (long i : a) if (i > max) max = i; return max; } static long min(long[] a) { long min = Long.MAX_VALUE; for (long i : a) if (i < min) min = i; return min; } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
843e5ca7c3bbb108d3b39ed6b4c240a6
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { BufferedReader in; StringTokenizer stok; final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; final static String IO = "_std"; void solve() throws IOException { int n = nextInt(); int[] a = nextIntArray(n); int[] d = new int[(int) 1e6 + 1]; int ans = 0; for (int i = 0; i < n; i++) { int x = a[i]; d[x] = max(d[x], 1); for (int j = x + x; j < d.length; j += x) { d[j] = max(d[j], d[x] + 1); } ans = max(ans, d[x]); } println(ans); } Main() { super(System.out); in = new BufferedReader(new InputStreamReader(System.in)); } Main(String fileIn, String fileOut) throws IOException { super(fileOut); in = new BufferedReader(new FileReader(fileIn)); } public static void main(String[] args) throws IOException { Main main; if ("_std".equals(IO)) { main = new Main(); } else if ("_iodef".equals(IO)) { main = new Main("input.txt", "output.txt"); } else { main = new Main(IO + ".in", IO + ".out"); } main.solve(); main.close(); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.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()); } int[] nextIntArray(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = nextInt(); } return a; } int[] nextIntArraySorted(int len) throws IOException { int[] a = nextIntArray(len); shuffle(a); Arrays.sort(a); return a; } void shuffle(int[] a) { for (int i = 1; i < a.length; i++) { int x = rand.nextInt(i + 1); int _ = a[i]; a[i] = a[x]; a[x] = _; } } void shuffleAndSort(int[] a) { shuffle(a); Arrays.sort(a); } boolean nextPermutation(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; } <T> List<T>[] createAdjacencyList(int n) { List<T>[] res = new List[n]; for (int i = 0; i < n; i++) { res[i] = new ArrayList<>(); } return res; } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
2ffec2131c24449d1ab91fc384c963df
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.io.*; public class Solution { static int N = (int) 1e6 + 5; static int dp[] = new int[N]; static int a[] = new int[N]; public static void main(String[] ks) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); String s[] = bf.readLine().trim().split("\\s+"); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(s[i]); dp[a[i]] = 1; } int ans = 1; for (int i = n - 1; i >= 0; i--) { for (int j = 2 * a[i]; j < N; j += a[i]) { dp[a[i]] = Math.max(dp[a[i]], dp[j] + 1); } ans = Math.max(ans, dp[a[i]]); } System.out.println(ans); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
f35555ff95d8dc5f5d324fd33b6c2783
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class Main { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String [] tmp = br.readLine().split(" "); int[] a = new int[1000001]; int max_ele = 0; for (int i=0; i<n; i++) { max_ele = Integer.parseInt(tmp[i]); a[max_ele] = 1; } for (int i=1; i<=max_ele; i++) { if (a[i] == 0) continue; for(int j=2*i; j<=max_ele; j+=i) if (a[j] != 0) a[j] = Math.max(a[j], a[i] + 1); } int max_v = 0; for (int i=0; i<=max_ele; i++) if (a[i] > max_v) max_v = a[i]; System.out.println(max_v); } catch (IOException e) { e.printStackTrace(); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
78721887aabcdad6881f1fddfbb9f2bc
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class VK2015F { public static PrintWriter out; public static FastScanner in; private void solve() { int n = in.nextInt(); int[] a = new int[n+1]; for(int i=0;i<n;i++){ a[i]= in.nextInt(); } Arrays.sort(a); int[] count = new int[1000002]; Arrays.fill(count,0); int mx; for(int i=1;i<=n;i++){ count[a[i]]++; for(int k = a[i];k<=a[n];k+=a[i]){ count[k] = Math.max(count[k],count[a[i]]); } } mx = 0; for (int i=0;i<=a[n];i++){ mx = Math.max(mx,count[i]); } out.print(mx); } private void runIO() { in = new FastScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); solve(); out.close(); } private static class FastScanner { BufferedReader bufferedReader; StringTokenizer stringTokenizer; private FastScanner() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } private String next() { if (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return stringTokenizer.nextToken(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private String nextLine() { String ret = ""; try { ret = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return ret; } } public static void main(String[] args) { new VK2015F().runIO(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
277daada099a17d67b01d8529a481d08
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.StringTokenizer; public class aa { public static class node { int val; int idx; int num; node(int a, int b, int c) { val = a; idx = b; num = c; } } public static String tree1[]; public static String tree2[]; public static void build(int s, int e, int p, String a, String tree[]) { if (s == e) { tree[p] = "" + a.charAt(s - 1); return; } int mid = (s + e) / 2; build(s, mid, p * 2, a, tree); build(mid + 1, e, p * 2 + 1, a, tree); tree[p] = tree[p * 2] + tree[p * 2 + 1]; } public static String get(int s, int e, int p, int from, int to, String tree[]) { if (s >= from && e <= to) { return tree[p]; } if (s > to || e < from) return ""; int mid = (s + e) / 2; String a = get(s, mid, p * 2, from, to, tree); String b = get(mid + 1, e, p * 2 + 1, from, to, tree); return a + b; } public static String[] split(String a) { int len = a.length() / 2; String one = ""; String two = ""; for (int i = 0; i < len; i++) { one += a.charAt(i); } for (int i = len; i < a.length(); i++) { two += a.charAt(i); } String aa[] = new String[2]; aa[0] = one; aa[1] = two; return aa; } public static int len; public static HashMap<String, Boolean> mp = new HashMap(); public static boolean eqiv(int s1, int e1, int s2, int e2) { String aaa = s1 + " " + e1 + " " + s2; if (mp.containsKey(aaa)) return mp.get(aaa); String get1 = get(1, len, 1, s1, e1, tree1); String get2 = get(1, len, 1, s2, e2, tree2); if (get1.equals(get2)) return true; if (e1 - s1 + 1 % 2 == 1) return false; int mid1 = (s1 + e1) / 2; int mid2 = (s2 + e2) / 2; if (eqiv(s1, mid1, s2, mid2) && eqiv(mid1 + 1, e1, mid2 + 1, e2)) { mp.put(aaa, true); return true; } else if (eqiv(s1, mid1, mid2 + 1, e2) && eqiv(mid1 + 1, e1, s2, mid2)) { mp.put(aaa, true); return true; } mp.put(aaa, false); return false; } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader in = new BufferedReader(new // FileReader("out.txt")); StringBuilder q = new StringBuilder(); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // PrintWriter out = new PrintWriter(new FileWriter("out.txt")); int n = Integer.parseInt(in.readLine()); String y[] = in.readLine().split(" "); int a[] = new int[n]; int dp[] = new int[1000005]; boolean ok[] = new boolean[1000005]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(y[i]); dp[a[i]] = 1; ok[a[i]] = true; } int max = 0; for (int i = 0; i < n; i++) { for (int j = a[i] + a[i]; j < dp.length; j += a[i]) { if (ok[j]) { dp[j] = Math.max(dp[j], dp[a[i]] + 1); // System.out.println(j+" "+dp[j]+" "+a[i]); } } //System.out.println(dp[a[i]] + " " + a[i]); max = Math.max(max, dp[a[i]]); } System.out.println(max); out.close(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
b0a493652c2da5da498ada722b0c854e
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Main { static int[] inp; static int[] maxClique; public static void main(String[] args) throws Exception{ // write your code here BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int size = Integer.parseInt(reader.readLine()); inp = new int[size]; int[] isPresent = new int[1000*1000+1]; String[] line = reader.readLine().split(" "); for(int i = 0; i < size;++i ) { inp[i] = Integer.parseInt(line[i]); isPresent[inp[i]] = 1; } int max =1; for(int i = size-1; i >= 0; --i){ int currentValue = inp[i]; for(int j = 2*currentValue;j <= inp[size-1];j=j+currentValue){ if(isPresent[j] > 0) { isPresent[currentValue] = Math.max(isPresent[currentValue], isPresent[j] + 1); } } if(isPresent[currentValue] > max) max = isPresent[currentValue]; } System.out.println(max); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
efe25797d956cd870c8ac92274f31f69
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long mod = (long) (1e9+7); static long cf = 998244353; static final int MAX = 100000; // public static List<Integer>[] edges; public static void main(String[] args) { FastReader sc = new FastReader(); int n = sc.nextInt(); int[] a = new int[n]; int[] dp = new int[(int) (1e6+1)]; for(int i=0;i<n;++i) { a[i] = sc.nextInt(); dp[a[i]]++; } int ans = 1; for(int i=1;i<dp.length;++i) { if(dp[i] == 0) continue; for(int j=2*i;j<dp.length;j+=i) { if(dp[j] == 0) continue; dp[j] = Math.max(dp[j], dp[i]+1); ans = Math.max(ans,dp[j]); } ans = Math.max(ans, dp[i]); } out.print(ans); out.close(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
152c63a37daaab6daca8eb03b2f67c9b
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public void solve(int testNumber, InputReader in, OutputWriter out) { int count = in.readInt(); int[] a = IOUtils.readIntArray(in, count); int[] div = IntegerUtils.generateDivisorTable(1000001); int[] ans = new int[1000001]; for (int i = 1; i <= 1000000; i++) { int cur = i; while (cur > 1) { ans[i] = Math.max(ans[i], ans[i / div[cur]]); int d = div[cur]; do { cur /= d; } while (cur % d == 0); } if (Arrays.binarySearch(a, i) >= 0) { ans[i]++; } } out.printLine(ArrayUtils.maxElement(ans)); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class IntegerUtils { public static int[] generateDivisorTable(int upTo) { int[] divisor = new int[upTo]; for (int i = 1; i < upTo; i++) divisor[i] = i; for (int i = 2; i * i < upTo; i++) { if (divisor[i] == i) { for (int j = i * i; j < upTo; j += i) divisor[j] = i; } } return divisor; } } static class ArrayUtils { public static int maxElement(int[] array) { return maxElement(array, 0, array.length); } public static int maxElement(int[] array, int from, int to) { int result = Integer.MIN_VALUE; for (int i = from; i < to; i++) result = Math.max(result, array[i]); return result; } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { 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
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
57d5b7977acc6c4a2abc2175cea41104
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; public class Main { static void solve(InputReader in, OutputWriter out) { int size = 1_000_000; int n = in.nextInt(); int max = 1; int[] ar = new int[size + 1]; for (int i = 0; i < n; i++) { int x = in.nextInt(); ar[x]++; if (ar[x] > max) max = ar[x]; for (int j = 2; j * x <= size; j++) { ar[j * x] = Math.max(ar[j * x], ar[x]); } } out.print(max); } static class Tuple { int x, y; Tuple(int x, int y) { this.x = x; this.y = y; } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static void shuffleTupleList(List<Tuple> list) { int index; Random random = new Random(); for (int i = list.size() - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { Tuple t = list.get(i); list.set(i, list.get(index)); list.set(index, t); } } } static void shuffleArray(int[] array) { int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { index = random.nextInt(i + 1); if (index != i) { array[index] ^= array[i]; array[i] ^= array[index]; array[index] ^= array[i]; } } } public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); solve(in, out); in.close(); out.close(); } static class InputReader { private BufferedReader br; private StringTokenizer st; InputReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); st = null; } String nextLine() { String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } String next() { while (st == null || !st.hasMoreTokens()) { String line = nextLine(); if (line == null) return null; st = new StringTokenizer(line); } return st.nextToken(); } byte nextByte() { return Byte.parseByte(next()); } short nextShort() { return Short.parseShort(next()); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static class OutputWriter { BufferedWriter bw; OutputWriter(OutputStream os) { bw = new BufferedWriter(new OutputStreamWriter(os)); } void print(int i) { print(Integer.toString(i)); } void println(int i) { println(Integer.toString(i)); } void print(long l) { print(Long.toString(l)); } void println(long l) { println(Long.toString(l)); } void print(double d) { print(Double.toString(d)); } void println(double d) { println(Double.toString(d)); } void print(boolean b) { print(Boolean.toString(b)); } void println(boolean b) { println(Boolean.toString(b)); } void print(char c) { try { bw.write(c); } catch (IOException e) { e.printStackTrace(); } } void println(char c) { println(Character.toString(c)); } void print(String s) { try { bw.write(s); } catch (IOException e) { e.printStackTrace(); } } void println(String s) { print(s); print('\n'); } void close() { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
77ae6ab3e408b6a5374f795e711f64e7
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.io.*; public class C { static final int N = (int)1e6; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine().trim()); int[] dp = new int[N+1]; boolean[] arr = new boolean[N+1]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++){ int a = Integer.parseInt(st.nextToken()); arr[a] = true; dp[a]++; } for(int i = 1; i <= N; i++){ if(!arr[i]) continue; for(int j = 2*i; j <= N; j += i){ if(!arr[j]) continue; dp[j] = Integer.max(dp[j], dp[i]+1); } } int max = 0; for(int i = 1; i <= N; i++){ max = Integer.max(max, dp[i]); } System.out.println(max); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
a93a82f1d863a32087331acac7cb4c7f
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String []args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int array[] = new int[n]; boolean isPresent[] = new boolean[1000*1000 + 5]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i = 0;i < n;i++){ array[i]=Integer.parseInt(st.nextToken()); isPresent[array[i]] = true; } int max = 0; int dp[] = new int[1000*1000 + 5]; for(int i = 0;i < n;i++)dp[array[i]] = 1; //System.out.println(dp[3]); for(int i = 0;i < n;i++){ int ans = 0; int increment = array[i]; for(int j = 2*array[i];j <= 1000*1000;j += increment){ if(j > 1000*1000)continue; if(isPresent[j]){ dp[j] = Math.max(dp[j],dp[array[i]] + 1); //System.out.println(dp[j] + " " + j); } } } for(int i = 0;i < n;i++){ max = Math.max(max,dp[array[i]]); } System.out.println(max); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
df78ab2bad699a454f4d87ac5a7b87aa
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.lang.*; import java.io.*; import java.util.*; import java.math.*; public class Main{ static int cnt[], dp[]; static BufferedReader br; static { br = new BufferedReader(new InputStreamReader(System.in)); cnt = new int[1048576]; dp = new int[1048576]; } static void solve() throws Exception { Arrays.fill(cnt,0); Arrays.fill(dp,0); int n = Integer.parseInt(br.readLine()); StringTokenizer st=new StringTokenizer(br.readLine()); for(int i = 0; i < n; i++) { int x = Integer.parseInt(st.nextToken()); cnt[x]++; } for(int i = 1; i <= 500000; i++) { if(cnt[i]==0) continue; int y=cnt[i]+dp[i]; for(int j = i+i; j <= 1000000; j+=i) { if(cnt[j]==0) continue; if(y>dp[j]) dp[j]=y; } } int ans = 0; for(int i = 1; i <= 1000000; i++) if(ans < cnt[i]+dp[i]) ans = cnt[i]+dp[i]; System.out.println(ans); } public static void main(String args[]) throws Exception { //int nCases = Integer.parseInt(br.readLine()); //while(nCases-->0) solve(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
059ef5ff2dddb0142d0251346ce8fe17
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Andrey Rechitsky (arechitsky@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } } class TaskF { final static int MAXA = 1000005; public void solve(int testNumber, FastScanner in, FastPrinter out) { int n = in.nextInt(); int [] a = new int[MAXA]; Arrays.fill(a, 0); for (int i = 0; i < n; i++) { a[in.nextInt()] = 1; } for (int i = 1; i < MAXA; i++) { if (a[i]==0) continue; for (int j = i+i; j < MAXA; j+=i) { if (a[j]==0) continue; a[j] = Math.max(a[j], a[i]+1); } } int ans = 0; for (int i = 0; i < MAXA; i++) { ans = Math.max(ans, a[i]); } out.printLine(ans); } } class FastScanner { private BufferedReader reader; private StringTokenizer st; public FastScanner(InputStream stream) { this.reader = new BufferedReader(new InputStreamReader(stream)); this.st = new StringTokenizer(""); } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (!st.hasMoreTokens()) { st = new StringTokenizer(readLine()); } return st.nextToken(); } private String readLine() { try { String line = reader.readLine(); if (line == null) throw new InputMismatchException(); return line; } catch (IOException e) { throw new InputMismatchException(); } } } class FastPrinter { private final PrintWriter writer; public FastPrinter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
721cde23527248cd3bdca23afc037840
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; 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; } } public static void main(String ar[]){ FastReader sc = new FastReader(); int n = sc.nextInt(); int max = (int)Math.pow(10, 6) + 10 ; int count[] = new int[max]; for(int i = 0 ; i < n ; i++){ count[sc.nextInt()]++ ; } int dp[] = new int[max]; int ans = Integer.MIN_VALUE ; for(int i = max - 1 ; i > 0 ; i--){ dp[i] = count[i] ; for(int j = i + i ; j < max ; j += i) dp[i] = Math.max(dp[i], dp[j] + count[i]) ; ans = Math.max(ans, dp[i]); } System.out.println(ans) ; } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
54a775655386bc18da2889beaf3f9778
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = index - 1; i >= 0; i--) { int u = x[i]; int v = y[i]; graph[u][--size[u]] = v; graph[v][--size[v]] = u; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readLong(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { int n = readInt(); int MAX = 1000000 + 10; int[] count = new int[MAX]; for (int i = 0; i < n; i++) { count[readInt()]++; } int[] answer = new int[MAX]; int best = 0; for (int i = 1; i < MAX; i++) { answer[i] += count[i]; for (int j = 2 * i; j < MAX; j += i) { answer[j] = Math.max(answer[j], answer[i]); } best = Math.max(best, answer[i]); } out.println(best); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
dfefe7d8984c5ae2e31e09d0ad3ddf6b
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; 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 */ 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); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int a[] = new int[N]; int idx[] = new int[1000001]; Arrays.fill(idx, -1); for (int i = 0; i < N; i++) { a[i] = in.nextInt(); idx[a[i]] = i; } int ans = 0; int dp[] = new int[N + 1]; dp[0] = 0; Arrays.fill(dp, 1); for (int i = 1; i <= N; i++) { for (int j = a[i - 1] + a[i - 1]; j <= a[N - 1]; j += a[i - 1]) { if (idx[j] != -1) { dp[idx[j] + 1] = Math.max(dp[idx[j] + 1], 1 + dp[i]); } } } for (int i = N; i >= 0; i--) { ans = Math.max(ans, dp[i]); } out.println(ans); } } 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()); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
48f1f592a58ec3f0261a56f71221e371
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; import java.util.stream.Collector; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); while(in.hasNext()) { int n=in.nextInt(); ArrayList<Integer> v=new ArrayList<Integer>(); v.clear(); for(int i=0;i<n;i++) { int a=in.nextInt(); v.add(a); } Collections.sort(v); int[] mp=new int[1000005]; Arrays.fill(mp, -1); for(int i=0;i<v.size();i++) { mp[v.get(i)]=Math.max(1, mp[v.get(i)]); for(int j=2*(v.get(i));j<1000005;j+=v.get(i)) mp[j]=Math.max(mp[j], 1+mp[v.get(i)]); } int ans=1; for(int i=0;i<v.size();i++) ans=Math.max(ans, mp[v.get(i)]); out.println(ans); } out.close(); } } class InputReader { BufferedReader buf; StringTokenizer tok; InputReader() { buf = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (tok == null || !tok.hasMoreElements()) { try { tok = new StringTokenizer(buf.readLine()); } catch (Exception e) { return false; } } return true; } String next() { if (hasNext()) return tok.nextToken(); return null; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } BigInteger nextBigInteger() { return new BigInteger(next()); } BigDecimal nextBigDecimal() { return new BigDecimal(next()); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
7962af8c225de30e159b880c0059981f
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.io.BufferedWriter; import java.io.PrintWriter; import java.io.Writer; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.IOException; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main{ public static void main(String[] args){ InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF{ public void solve(int testNumber, InputReader in, OutputWriter out){ int MAX = 1000009; int n = in.ri(); int[] best = new int[MAX]; for(int i = 0; i < n; i++) best[in.ri()] = 1; int res = 0; for(int i = MAX - 1; i >= 1; i--) { if(best[i] == 1){ int otherbest = 0; for(int val = 2 * i; val < MAX; val += i) otherbest = Math.max(otherbest, best[val]); best[i] += otherbest; res = Math.max(res, best[i]); } } out.printLine(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 ri(){ return readInt(); } public int readInt(){ 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); } } static class OutputWriter{ private final PrintWriter writer; public OutputWriter(OutputStream outputStream){ writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer){ this.writer = new PrintWriter(writer); } public void close(){ writer.close(); } public void printLine(int i){ writer.println(i); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
82b1bcaad9f597fa2ec64a71e6eb5982
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; public class icpc { public static void main(String[] args) throws IOException { Reader in = new Reader(); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = in.nextInt(); int[] A = new int[n]; for (int i=0;i<n;i++) A[i] = in.nextInt(); int[] dp = new int[n]; dp[0] = 0; int[] index = new int[1000001]; Arrays.fill(index, -1); for (int i=0;i<n;i++) index[A[i]] = i; Arrays.fill(dp, 1); for (int i=0;i<n;i++) { for (int j=2 * A[i];j<=1000000;j+=A[i]) { if (index[j] > -1) { dp[index[j]] = Math.max(dp[index[j]], dp[i] + 1); } } } int max = Integer.MIN_VALUE; for (int i=0;i<n;i++) max = Math.max(max, dp[i]); System.out.println(max); } } class DSU { int[] parent; int[] size; //Pass number of total nodes as parameter to the constructor DSU(int n) { this.parent = new int[n]; this.size = new int[n]; Arrays.fill(parent, -1); } public void makeSet(int v) { parent[v] = v; size[v] = 1; } public int findSet(int v) { if (v == parent[v]) return v; return parent[v] = findSet(parent[v]); } public void unionSets(int a, int b) { a = findSet(a); b = findSet(b); if (a != b) { if (size[a] < size[b]) { int temp = a; a = b; b = temp; } parent[b] = a; size[a] += size[b]; } } } class FastFourierTransform { private void fft(double[] a, double[] b, boolean invert) { int count = a.length; for (int i = 1, j = 0; i < count; i++) { int bit = count >> 1; for (; j >= bit; bit >>= 1) j -= bit; j += bit; if (i < j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; temp = b[i]; b[i] = b[j]; b[j] = temp; } } for (int len = 2; len <= count; len <<= 1) { int halfLen = len >> 1; double angle = 2 * Math.PI / len; if (invert) angle = -angle; double wLenA = Math.cos(angle); double wLenB = Math.sin(angle); for (int i = 0; i < count; i += len) { double wA = 1; double wB = 0; for (int j = 0; j < halfLen; j++) { double uA = a[i + j]; double uB = b[i + j]; double vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB; double vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA; a[i + j] = uA + vA; b[i + j] = uB + vB; a[i + j + halfLen] = uA - vA; b[i + j + halfLen] = uB - vB; double nextWA = wA * wLenA - wB * wLenB; wB = wA * wLenB + wB * wLenA; wA = nextWA; } } } if (invert) { for (int i = 0; i < count; i++) { a[i] /= count; b[i] /= count; } } } public long[] multiply(long[] a, long[] b) { int resultSize = Integer.highestOneBit(Math.max(a.length, b.length) - 1) << 2; resultSize = Math.max(resultSize, 1); double[] aReal = new double[resultSize]; double[] aImaginary = new double[resultSize]; double[] bReal = new double[resultSize]; double[] bImaginary = new double[resultSize]; for (int i = 0; i < a.length; i++) aReal[i] = a[i]; for (int i = 0; i < b.length; i++) bReal[i] = b[i]; fft(aReal, aImaginary, false); fft(bReal, bImaginary, false); for (int i = 0; i < resultSize; i++) { double real = aReal[i] * bReal[i] - aImaginary[i] * bImaginary[i]; aImaginary[i] = aImaginary[i] * bReal[i] + bImaginary[i] * aReal[i]; aReal[i] = real; } fft(aReal, aImaginary, true); long[] result = new long[resultSize]; for (int i = 0; i < resultSize; i++) result[i] = Math.round(aReal[i]); return result; } } class NumberTheory { public boolean isPrime(long n) { if(n < 2) return false; for(long x = 2;x * x <= n;x++) { if(n % x == 0) return false; } return true; } public ArrayList<Long> primeFactorisation(long n) { ArrayList<Long> f = new ArrayList<>(); for(long x=2;x * x <= n;x++) { while(n % x == 0) { f.add(x); n /= x; } } if(n > 1) f.add(n); return f; } public int[] sieveOfEratosthenes(int n) { //Returns an array with the smallest prime factor for each number and primes marked as 0 int[] sieve = new int[n + 1]; for(int x=2;x * x <= n;x++) { if(sieve[x] != 0) continue; for(int u=x*x;u<=n;u+=x) { if(sieve[u] == 0) { sieve[u] = x; } } } return sieve; } public long gcd(long a, long b) { if(b == 0) return a; return gcd(b, a % b); } public long phi(long n) { double result = n; for(long p=2;p*p<=n;p++) { if(n % p == 0) { while (n % p == 0) n /= p; result *= (1.0 - (1.0 / (double)p)); } } if(n > 1) result *= (1.0 - (1.0 / (double)n)); return (long)result; } public Name extendedEuclid(long a, long b) { if(b == 0) return new Name(a, 1, 0); Name n1 = extendedEuclid(b, a % b); Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y); return n2; } public long modularExponentiation(long a, long b, long n) { long d = 1L; String bString = Long.toBinaryString(b); for(int i=0;i<bString.length();i++) { d = (d * d) % n; if(bString.charAt(i) == '1') d = (d * a) % n; } return d; } } class Name { long d; long x; long y; public Name(long d, long x, long y) { this.d = d; this.x = x; this.y = y; } } class SuffixArray { int ALPHABET_SZ = 256, N; int[] T, lcp, sa, sa2, rank, tmp, c; public SuffixArray(String str) { this(toIntArray(str)); } private static int[] toIntArray(String s) { int[] text = new int[s.length()]; for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i); return text; } public SuffixArray(int[] text) { T = text; N = text.length; sa = new int[N]; sa2 = new int[N]; rank = new int[N]; c = new int[Math.max(ALPHABET_SZ, N)]; construct(); kasai(); } private void construct() { int i, p, r; for (i = 0; i < N; ++i) c[rank[i] = T[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i; for (p = 1; p < N; p <<= 1) { for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i; for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p; Arrays.fill(c, 0, ALPHABET_SZ, 0); for (i = 0; i < N; ++i) c[rank[i]]++; for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1]; for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i]; for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i) { if (!(rank[sa[i - 1]] == rank[sa[i]] && sa[i - 1] + p < N && sa[i] + p < N && rank[sa[i - 1] + p] == rank[sa[i] + p])) r++; sa2[sa[i]] = r; } tmp = rank; rank = sa2; sa2 = tmp; if (r == N - 1) break; ALPHABET_SZ = r + 1; } } private void kasai() { lcp = new int[N]; int[] inv = new int[N]; for (int i = 0; i < N; i++) inv[sa[i]] = i; for (int i = 0, len = 0; i < N; i++) { if (inv[i] > 0) { int k = sa[inv[i] - 1]; while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++; lcp[inv[i] - 1] = len; if (len > 0) len--; } } } } class ZAlgorithm { public int[] calculateZ(char input[]) { int Z[] = new int[input.length]; int left = 0; int right = 0; for(int k = 1; k < input.length; k++) { if(k > right) { left = right = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } else { //we are operating inside box int k1 = k - left; //if value does not stretches till right bound then just copy it. if(Z[k1] < right - k + 1) { Z[k] = Z[k1]; } else { //otherwise try to see if there are more matches. left = k; while(right < input.length && input[right] == input[right - left]) { right++; } Z[k] = right - left; right--; } } } return Z; } public ArrayList<Integer> matchPattern(char text[], char pattern[]) { char newString[] = new char[text.length + pattern.length + 1]; int i = 0; for(char ch : pattern) { newString[i] = ch; i++; } newString[i] = '$'; i++; for(char ch : text) { newString[i] = ch; i++; } ArrayList<Integer> result = new ArrayList<>(); int Z[] = calculateZ(newString); for(i = 0; i < Z.length ; i++) { if(Z[i] == pattern.length) { result.add(i - pattern.length - 1); } } return result; } } class KMPAlgorithm { public int[] computeTemporalArray(char[] pattern) { int[] lps = new int[pattern.length]; int index = 0; for(int i=1;i<pattern.length;) { if(pattern[i] == pattern[index]) { lps[i] = index + 1; index++; i++; } else { if(index != 0) { index = lps[index - 1]; } else { lps[i] = 0; i++; } } } return lps; } public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern) { int[] lps = computeTemporalArray(pattern); int j = 0; int i = 0; int n = text.length; int m = pattern.length; ArrayList<Integer> indices = new ArrayList<>(); while(i < n) { if(pattern[j] == text[i]) { i++; j++; } if(j == m) { indices.add(i - j); j = lps[j - 1]; } else if(i < n && pattern[j] != text[i]) { if(j != 0) j = lps[j - 1]; else i = i + 1; } } return indices; } } class Hashing { public long[] computePowers(long p, int n, long m) { long[] powers = new long[n]; powers[0] = 1; for(int i=1;i<n;i++) { powers[i] = (powers[i - 1] * p) % m; } return powers; } public long computeHash(String s) { long p = 31; long m = 1_000_000_009; long hashValue = 0L; long[] powers = computePowers(p, s.length(), m); for(int i=0;i<s.length();i++) { char ch = s.charAt(i); hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m; } return hashValue; } } class BasicFunctions { public 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; } public long max(long[] A) { long max = Long.MAX_VALUE; for(int i=0;i<A.length;i++) { max = Math.max(max, A[i]); } return max; } } class MergeSortInt { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class MergeSortLong { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } } class Node { int x; int y; public Node(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object ob) { if(ob == null) return false; if(!(ob instanceof Node)) return false; if(ob == this) return true; Node obj = (Node)ob; if(this.x == obj.x && this.y == obj.y) return true; return false; } @Override public int hashCode() { return (int)this.x; } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class FenwickTree { public void update(long[] fenwickTree,long delta,int index) { index += 1; while(index < fenwickTree.length) { fenwickTree[index] += delta; index = index + (index & (-index)); } } public long prefixSum(long[] fenwickTree,int index) { long sum = 0L; index += 1; while(index > 0) { sum += fenwickTree[index]; index -= (index & (-index)); } return sum; } } class SegmentTree { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int[] input) { int np2 = nextPowerOfTwo(input.length); int[] segmentTree = new int[np2 * 2 - 1]; for(int i=0;i<segmentTree.length;i++) segmentTree[i] = Integer.MIN_VALUE; constructSegmentTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/ 2; constructSegmentTree(segmentTree,input,low,mid,2*pos + 1); constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2); segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len) { return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos) { if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MIN_VALUE; } int mid = (low+high)/2; return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1), rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2)); } } class Trie { private class TrieNode { Map<Character, TrieNode> children; boolean endOfWord; public TrieNode() { children = new HashMap<>(); endOfWord = false; } } private final TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { node = new TrieNode(); current.children.put(ch, node); } current = node; } current.endOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); TrieNode node = current.children.get(ch); if (node == null) { return false; } current = node; } return current.endOfWord; } public void delete(String word) { delete(root, word, 0); } private boolean delete(TrieNode current, String word, int index) { if (index == word.length()) { if (!current.endOfWord) { return false; } current.endOfWord = false; return current.children.size() == 0; } char ch = word.charAt(index); TrieNode node = current.children.get(ch); if (node == null) { return false; } boolean shouldDeleteCurrentNode = delete(node, word, index + 1); if (shouldDeleteCurrentNode) { current.children.remove(ch); return current.children.size() == 0; } return false; } } class SegmentTreeLazy { public int nextPowerOfTwo(int num) { if(num == 0) return 1; if(num > 0 && (num & (num - 1)) == 0) return num; while((num &(num - 1)) > 0) { num = num & (num - 1); } return num << 1; } public int[] createSegmentTree(int input[]) { int nextPowOfTwo = nextPowerOfTwo(input.length); int segmentTree[] = new int[nextPowOfTwo*2 -1]; for(int i=0; i < segmentTree.length; i++){ segmentTree[i] = Integer.MAX_VALUE; } constructMinSegmentTree(segmentTree, input, 0, input.length - 1, 0); return segmentTree; } private void constructMinSegmentTree(int segmentTree[], int input[], int low, int high,int pos) { if(low == high) { segmentTree[pos] = input[low]; return; } int mid = (low + high)/2; constructMinSegmentTree(segmentTree, input, low, mid, 2 * pos + 1); constructMinSegmentTree(segmentTree, input, mid + 1, high, 2 * pos + 2); segmentTree[pos] = Math.min(segmentTree[2*pos+1], segmentTree[2*pos+2]); } public void updateSegmentTreeRangeLazy(int input[], int segmentTree[], int lazy[], int startRange, int endRange, int delta) { updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, 0, input.length - 1, 0); } private void updateSegmentTreeRangeLazy(int segmentTree[], int lazy[], int startRange, int endRange, int delta, int low, int high, int pos) { if(low > high) { return; } if (lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(startRange > high || endRange < low) { return; } if(startRange <= low && endRange >= high) { segmentTree[pos] += delta; if(low != high) { lazy[2*pos + 1] += delta; lazy[2*pos + 2] += delta; } return; } int mid = (low + high)/2; updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, low, mid, 2*pos+1); updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, mid+1, high, 2*pos+2); segmentTree[pos] = Math.min(segmentTree[2*pos + 1], segmentTree[2*pos + 2]); } public int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int len) { return rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, 0, len - 1, 0); } private int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int low, int high, int pos) { if(low > high) { return Integer.MAX_VALUE; } if (lazy[pos] != 0) { segmentTree[pos] += lazy[pos]; if (low != high) { lazy[2 * pos + 1] += lazy[pos]; lazy[2 * pos + 2] += lazy[pos]; } lazy[pos] = 0; } if(qlow > high || qhigh < low) { return Integer.MAX_VALUE; } if(qlow <= low && qhigh >= high) { return segmentTree[pos]; } int mid = (low+high)/2; return Math.min(rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, low, mid, 2 * pos + 1), rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2)); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
91ae8f1060b7c1818bb0d5eec4e40cf3
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * * @author pttrung */ public class F_VK2015_Final { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[] data = new int[n]; int[] pos = new int[1000001]; Arrays.fill(pos, -1); for (int i = 0; i < n; i++) { data[i] = in.nextInt(); pos[data[i]] = i; } int[] dp = new int[n]; int result = 1; Arrays.fill(dp,1); for(int i = 0; i < n; i++){ for(int j = data[i] + data[i]; j < 1000001; j+= data[i]){ if(pos[j] != -1){ dp[pos[j]] = Math.max(dp[pos[j]], 1 + dp[i]); } } result = result < dp[i] ? dp[i] : result; } out.println(result); out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new // BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new // FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
f5ede2d7feda0dbf18f9a89fb72c70c4
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { static int n = 1+(int)1e6; static boolean[] has; static int memo[]; static int dp(int cur) { if(cur>=n || !has[cur])return -(int)1e8; if(memo[cur]!=-1)return memo[cur]; int ans = has[cur]?1:0; for(int i = cur<<1;i<n;i+=cur) { ans = Math.max(ans, 1+dp(i)); } return memo[cur] = ans; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); has = new boolean[n]; br.readLine(); StringTokenizer st = new StringTokenizer(br.readLine()); while(st.hasMoreTokens()) { has[Integer.parseInt(st.nextToken())] = true; } int ans = 0; memo = new int[n]; Arrays.fill(memo, -1); for(int i = n-1;i>0;i--) ans = Math.max(ans, dp(i)); System.out.println(ans); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
708e2399f970278459bf3ac89eef3ef5
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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 Artem Gilmudinov */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Reader in = new Reader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public void solve(int testNumber, Reader in, PrintWriter out) { int n = in.ni(); int[] a = new int[n]; Helper.fillIntArray(in, a); int max = 1_000_000; int[] res = new int[max + 1]; for (int j = n - 1; j >= 0; j--) { for (int z = a[j]; z <= max; z += a[j]) { res[a[j]] = Math.max(res[a[j]], res[z] + 1); } } int ans = 0; for (int i = 0; i <= max; i++) { ans = Math.max(ans, res[i]); } out.println(ans); } } static class Reader { private BufferedReader in; private StringTokenizer st = new StringTokenizer(""); private String delim = " "; public Reader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public String next() { if (!st.hasMoreTokens()) { st = new StringTokenizer(rl()); } return st.nextToken(delim); } public String rl() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int ni() { return Integer.parseInt(next()); } } static class Helper { public static void fillIntArray(Reader in, int[] a) { for (int i = 0; i < a.length; i++) { a[i] = in.ni(); } } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
da20472e0612d048e5c1a6dbe117ecb1
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
/*Talent is something you make bloom , instinct is something you polish*/ import java.io.*; import java.math.*; import java.util.*; public class Main { static long mod=((long)1e9)+7;//toString public static int gcd(int a,int b){if(b==0)return a;else return gcd(b,a%b);} public static long pow_mod(long x,long y){long res=1;x=x%mod;while(y > 0){if((y & 1)==1)res=(res * x)%mod;y=y>>1;x =(x * x)%mod;}return res;} public static int lower_bound(int[]arr,int val){int lo=0;int hi=arr.length-1;while(lo<hi){int mid=lo+((hi-lo+1)/2);if(arr[mid]==val){return mid;}else if(arr[mid]>val){hi=mid-1;}else lo=mid;}if(arr[lo]<=val)return lo;else return -1;} public static int upper_bound(int[]arr,int val){int lo=0;int hi=arr.length-1;while(lo<hi){int mid=lo+((hi-lo)/2);if(arr[mid]==val){return mid;}else if(arr[mid]>val){hi=mid;;}else lo=mid+1;}if(arr[lo]>=val)return lo;else return -1;} public static void main (String[] args) throws java.lang.Exception { Reader sn = new Reader(); Print p = new Print(); int n = sn.nextInt(); int l = Integer.MIN_VALUE; ArrayList<Integer> arr = new ArrayList<Integer>(); int[] count = new int[((int)1e6) + 1]; for (int i = 0; i < n; i++) { arr.add(sn.nextInt()); l = Math.max(l , arr.get(i)); count[arr.get(i)]++; } int[] dp = new int[l + 1]; int ans = 0; for (int i = 1; i <= l; i++) { dp[i] += count[i]; for (int j = i; j <= l; j += i) { if (dp[j] < dp[i]) { dp[j] = dp[i]; } } ans = Math.max(dp[i], ans); } p.printLine(Integer.toString(ans)); p.close(); } } class Pair implements Comparable<Pair> { int val; int in; Pair(int a, int b){ val=a; in=b; } @Override public int compareTo(Pair o) { if(val==o.val) return Integer.compare(in,o.in); else return Integer.compare(val,o.val); }} class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public String readWord()throws IOException { 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 int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } class Print { private final BufferedWriter bw; public Print() { bw=new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(String str)throws IOException { bw.append(str); } public void printLine(String str)throws IOException { print(str); bw.append("\n"); } public void close()throws IOException { bw.close(); }}
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
94209274acf4ff3e79fbf5e75d584300
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
//package vk2015.f; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class F { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int[] b = new int[1000001]; int[] dp = new int[1000001]; for(int v : a)b[v]++; for(int i = 1;i <= 1000000;i++){ if(b[i] == 0)continue; dp[i] = Math.max(dp[i], b[i]); for(int j = 2*i;j <= 1000000;j+=i){ if(b[j] > 0){ dp[j] = Math.max(dp[j], dp[i] + b[j]); } } } int ret = 0; for(int i = 1;i <= 1000000;i++){ ret = Math.max(ret, dp[i]); } out.println(ret); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
5cfc927afb93112657c3a3ea031db821
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; //1 //5 10 //10 9 8 10 11 public class C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int n=sc.nextInt(); int ans=1; int a[]=sc.readArray(n); int f[]=new int[1000005]; for(int i:a) f[i]++; for(int i=1;i<=a[n-1];i++) { // value i is not preseent in array so jst continue it. if(f[i]==0) continue; for(int j=2*i;j<=a[n-1];j+=i) { if(f[j]!=0) { f[j]=Math.max(f[j], f[i]+1); ans=Math.max(f[j], ans); } } } System.out.println(ans); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (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[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
b83d74bdd3227f1a6aa8e061e4aea13a
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class VkCup2015FinalsF { public static final int max = (int)1e6 + 10; public static void solve() { int n = s.nextInt(); int[] counts = new int[max]; for(int i = 0; i < n; i++) { int val = s.nextInt(); counts[val]++; } int[] dp = new int[max]; for(int i = 1; i < max; i++) { int val = counts[i] + dp[i]; if(val != 0) { for(int j = 2 * i; j < max; j += i) { dp[j] = Integer.max(val, dp[j]); } } } int ans = 0; for(int i = 0; i < max; i++) { ans = Integer.max(ans, dp[i] + counts[i]); } out.println(ans); } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
036c3e661eb78e6eb9f376c0e37e6ff0
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; public class cliquediv { private static InputReader in; private static PrintWriter out; public static void main(String[] args) throws IOException { in = new InputReader(System.in); out = new PrintWriter(System.out, true); int n = in.nextInt(); int maxt = 1000010; int[] max = new int[maxt]; for (int i = 0; i < n; i++) { int a = in.nextInt(); max[a]++; for (int j = a; j < maxt; j += a) { max[j] = Math.max(max[j], max[a]); } } int res = 0; for (int i = 0; i < maxt; i++) res = Math.max(max[i], res); out.println(res); out.close(); System.exit(0); } 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()); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
3fee069486fd0c1f15894d5a4a1c2b57
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.awt.geom.Rectangle2D; import java.io.*; import java.math.BigInteger; import java.util.*; import sun.security.krb5.internal.crypto.dk.ArcFourCrypto; public class E { String line; StringTokenizer inputParser; BufferedReader is; FileInputStream fstream; DataInputStream in; void openInput(String file) { if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin else { try{ fstream = new FileInputStream(file); in = new DataInputStream(fstream); is = new BufferedReader(new InputStreamReader(in)); }catch(Exception e) { System.err.println(e); } } } void readNextLine() { try { line = is.readLine(); inputParser = new StringTokenizer(line, " "); //System.err.println("Input: " + line); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } int NextInt() { String n = inputParser.nextToken(); int val = Integer.parseInt(n); //System.out.println("I read this number: " + val); return val; } String NextString() { String n = inputParser.nextToken(); return n; } void closeInput() { try { is.close(); } catch (IOException e) { System.err.println("Unexpected IO ERROR: " + e); } } public static void main(String [] argv) { String filePath=null; if(argv.length>0)filePath=argv[0]; new E(filePath); } public E(String inputFile) { openInput(inputFile); StringBuilder sb = new StringBuilder(); readNextLine(); int N= NextInt(); readNextLine(); Random rgen = new Random(); int [] p = new int[N]; int [] d = new int[1000001]; for(int i=0; i<N; i++) p[i]=NextInt(); //p[i]=p[i-1]+rgen.nextInt(5);//NextInt(); for(int i=N-1; i>=0; i--) { d[p[i]]=1; for(int j=p[i]*2; j<d.length; j+=p[i]) d[p[i]]=Math.max(d[j]+1, d[p[i]]); } int ret=0; for(int i=0; i<d.length; i++) ret=Math.max(ret, d[i]); sb.append(ret); System.out.println(sb); closeInput(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
7244beb8dabf38c129b0246968bb7f32
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class p566f { public static int N; public static ArrayList<Integer> a = new ArrayList<Integer>(); public static int[] dp; public static int[] count = new int[1000010]; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); N = in.nextInt(); int max = Integer.MIN_VALUE; for (int i = 0; i < N; i++) { a.add(in.nextInt()); max = Math.max(max, a.get(i)); count[a.get(i)]++; } dp = new int[max + 1]; int res = 0; for (int i = 1; i <= max; i++) { dp[i] += count[i]; for (int j = i; j <= max; j += i) { if (dp[j] < dp[i]) { dp[j] = dp[i]; } } res = Math.max(dp[i], res); } out.println(res); out.close(); } 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
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
15dcdfc4055f3c6338b6c2dea14b8257
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CF566F { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; void solve() throws IOException { int n = nextInt(); int len = 1000010; boolean[] has = new boolean[len]; int[] dp = new int[len]; for(int i = 0; i < n; i++) { has[nextInt()] = true; } int res = 1; Arrays.fill(dp, 1); for(int i = 1; i < len; i++) { if(!has[i]) { continue; } for(int j = 2; i * j < len; j++) { if(has[i * j]) { dp[i * j] = Math.max(dp[i * j], 1 + dp[i]); } } } for(int v : dp) { res = Math.max(res, v); } out(res); } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } private void outln(Object o) { System.out.println(o); } private void out(Object o) { System.out.print(o); } public CF566F() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CF566F(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
0b066f774bf689eb7a2aa91fae209d05
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class WorkFile { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); boolean[] array = new boolean[1000005]; StringTokenizer stoken = new StringTokenizer(reader.readLine()); for (int i=0; i<n; i++) { int x = Integer.parseInt(stoken.nextToken()); array[x] = true; } int[] dp = new int[1000005]; for (int i=1; i<1000005; i++) { if (!array[i]) continue; for (int j=i*2; j<1000005; j+=i) { if (!array[j]) continue; dp[j] = Integer.max(dp[i]+1, dp[j]); } dp[i]++; } int res = 0; for (int i=0; i<1000005; i++) { res = Integer.max(res, dp[i]); } System.out.println(res); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
5b8e29582628b9593bf4e5591b197ce5
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { 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;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- static int n; public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); n=sc.i(); int arr[]=sc.arr(n); int mark[]=new int[1000001]; for(int i=n-1;i>=0;i--) { int max=0; for(int j=2;;j++) { if((long)arr[i]*j>arr[n-1]) break; max=Math.max(max,mark[arr[i]*j]); } mark[arr[i]]=max+1; } int max=0; for(int i=0;i<1000001;i++)max=Math.max(max,mark[i]); out.println(max); out.flush(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
29a7d08889ec8b56ab5073528de042a0
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class CliqueInTheDivisibiltyGraph { static BufferedReader bf; static boolean nums[] = new boolean[1000001]; static int DP[] = new int[1000001]; int getMax(int curr) { if (curr >= nums.length) return 0; if (DP[curr] != -1) return DP[curr]; int max = 0; for (int j = 2; j * curr < nums.length; j++) { if (nums[j * curr]) { max = Math.max(max, getMax(j * curr)); } } return DP[curr] = max + 1; } void solve() throws Exception { Arrays.fill(DP, -1); int n = Integer.parseInt(bf.readLine()); String[] l = bf.readLine().split(" "); for (int i = 0; i < n; i++) { nums[Integer.parseInt(l[i])] = true; } int max = 0; for (int i = 1; i < nums.length; i++) { if (nums[i]) max = Math.max(max, getMax(i)); } System.out.println(max); } public static void main(String[] args) { bf = new BufferedReader(new InputStreamReader(System.in)); try { new CliqueInTheDivisibiltyGraph().solve(); } catch (Exception e) { e.printStackTrace(); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
e0a08cca9789222368789a6bc836862d
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
/*11:21 7:50*/ import java.util.*; import java.io.*; public class p14{ static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) throws Exception{ FastReader sc = new FastReader(); int n = sc.nextInt(); int[] arr = new int[n]; int[] ind = new int[1000025]; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); ind[arr[i]] = i; } int[] dp = new int[n]; dp[0] = 0; for(int i=0;i<n;i++){ int val = arr[i]; for(int j=2*val;j<1000025;j+=val){ int k = ind[j]; if(k==0) continue; dp[k] = Math.max(dp[k], dp[i]+1); } } int ans = 0; for(int i=0;i<n;i++) ans = Math.max(ans, dp[i]+1); System.out.println(ans); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
fa500ae06f97b3d5d6af4bb81216d05e
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.io.*; public class Abc { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in = new FastReader(); int n = in.nextInt(); int ar[] = new int[1000001]; int f[] = new int[1000001]; for(int i = 0; i < n; i++) { ar[i] = in.nextInt(); f[ar[i]]++; } int maxVal = 1; for(int i = 1; i <= ar[n - 1]; i ++) { if(f[i] == 0) continue; for(int j = 2 * i; j <= ar[n - 1]; j += i) { if(f[j] != 0) { f[j] = Math.max(f[j], 1 + f[i]); maxVal = Math.max(maxVal, f[j]); } } } /*for(int i = 1; i <= ar[n - 1]; i ++) { if(f[i] != 0) System.out.print(i + " " + f[i]); } System.out.println();*/ System.out.println(maxVal); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
40af59d9b06892ddf09fb29897d45e84
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.util.*; import java.io.*; public class TaskF { private FastScanner in; private PrintWriter out; final int MAX = (int) 1e6 + 1; public void solve() throws IOException { int n = in.nextInt(); int[] res = new int[MAX]; Arrays.fill(res, 1); boolean[] have = new boolean[MAX]; for (int i = 0; i < n; i++) { have[in.nextInt()] = true; } for (int i = 1; i < MAX; i++) { if (have[i]) { int cur = i + i; while (cur < MAX) { if (have[cur]) { res[cur] = Math.max(res[cur], res[i] + 1); } cur += i; } } } int ans = -1; for (int i = 0; i < MAX; i++) { ans = Math.max(ans, res[i]); } out.println(ans); } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] arg) { new TaskF().run(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
b842078c8ce80ade5fd4da23c6e46e98
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class F extends PrintWriter { void run() { int n = nextInt(); int m = 1_000_001; int[] dp = new int[m]; int ans = 0; Arrays.fill(dp, 1); for (int i = 0; i < n; i++) { int a = nextInt(); ans = max(ans, dp[a]); for (int j = 2 * a; j < m; j += a) { dp[j] = max(dp[j], dp[a] + 1); } } println(ans); } void skip() { while (hasNext()) { next(); } } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public F(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; F solution = new F(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(F.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
008ad3730504e786e92d994117234549
train_001.jsonl
1438273200
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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 */ 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); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int MAX = (int) 1e6 + 1; int[] count = new int[MAX]; for (int i = 0; i < n; ++i) ++count[in.nextInt()]; int[] res = new int[MAX]; for (int i = 1; i < MAX; ++i) { int cur = res[i] + count[i]; for (int j = i; j < MAX; j += i) res[j] = Math.max(res[j], cur); } int ret = 0; for (int r : res) ret = Math.max(ret, r); out.println(ret); } } 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()); } } }
Java
["8\n3 4 6 8 10 18 21 24"]
1 second
["3"]
NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Java 8
standard input
[ "dp", "number theory", "math" ]
f33991da3b4a57dd6535af86edeeddc0
The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A. The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.
1,500
Print a single number — the maximum size of a clique in a divisibility graph for set A.
standard output
PASSED
8d920071fb280ec1de6207e2c63c4b41
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.*; import java.util.*; public class C implements Runnable { private MyScanner in; private PrintWriter out; private void solve() { int[][] h = new int[3][]; for (int i = 0; i < 3; ++i) { h[i] = new int[3 - i]; for (int j = 0; j < h[i].length; ++j) { h[i][j] = in.nextInt(); } } final int MAXLEN = 400000; char[][] s = new char[4][MAXLEN]; Arrays.fill(s[0], 'a'); Arrays.fill(s[1], 'a'); Arrays.fill(s[1], 0, h[0][0], 'b'); Arrays.fill(s[2], 'a'); // 3 int foundX3 = -1; for (int x = 0; x <= h[0][0]; ++x) { int y = h[0][1] - x; if (h[1][0] == h[0][0] - x + y) { foundX3 = x; Arrays.fill(s[2], h[0][0] - x, h[0][0] - x + h[0][1], 'b'); break; } } if (foundX3 == -1) { out.println(-1); return; } // 4 Arrays.fill(s[3], 'a'); int foundX42 = -1; for (int x = 0; x <= h[0][0]; ++x) { int y = h[0][2] - x; if (h[1][1] == h[0][0] - x + y) { foundX42 = x; break; } } if (foundX42 == -1) { out.println(-1); return; } int foundX43 = -1; for (int x = 0; x <= h[0][1]; ++x) { int y = h[0][2] - x; if (h[2][0] == h[0][1] - x + y) { foundX43 = x; break; } } if (foundX43 == -1) { out.println(-1); return; } boolean ansFound = false; int no3 = h[0][1] - foundX3; int no2 = h[0][0] - foundX3; for (int same = 0; same <= foundX3; ++same) { int only2 = foundX42 - same; int only3 = foundX43 - same; if (only2 < 0 || only3 < 0 || same + only2 + only3 > h[0][2]) { continue; } int left = h[0][2] - same - only2 - only3; if (same + only2 > h[0][0] || same + only3 > h[0][1]) { continue; } if (only2 > no2 || only3 > no3) { continue; } if (h[1][1] == (h[0][0] - foundX42) + only3 + left && h[2][0] == (h[0][1] - foundX43) + only2 + left) { ansFound = true; Arrays.fill(s[3], h[0][0] - foundX3, h[0][0] - foundX3 + same, 'b'); Arrays.fill(s[3], 0, only2, 'b'); Arrays.fill(s[3], h[0][0], h[0][0] + only3, 'b'); Arrays.fill(s[3], h[0][0] + h[0][1] - foundX3, h[0][0] + h[0][1] - foundX3 + left, 'b'); break; } } if (!ansFound) { out.println(-1); return; } int len = MAXLEN; while (true) { int as = 0; for (int i = 0; i < 4; ++i) { if (s[i][len - 1] == 'a') { ++as; } } if (as < 4) { break; } --len; } out.println(len); for (int i = 0; i < 4; ++i) { out.println(new String(s[i], 0, len)); } } @Override public void run() { in = new MyScanner(); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } public static void main(String[] args) { new C().run(); } class MyScanner { private BufferedReader br; private StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); return false; } } return st != null && st.hasMoreTokens(); } private String next() { while (st == null || !st.hasMoreTokens()) { try { String s = br.readLine(); if (s == null) { return null; } st = new StringTokenizer(s); } catch (IOException e) { e.printStackTrace(); return null; } } return st.nextToken(); } public String nextLine() { try { st = null; return br.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
1eb2745593f60b281e7097ac329194a3
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { char[][] pattern = { "aaab".toCharArray(), "aaba".toCharArray(), "abaa".toCharArray(), "baaa".toCharArray(), "aabb".toCharArray(), "abab".toCharArray(), "abba".toCharArray() }; public void solve(int testNumber, InputReader in, OutputWriter out) { int[] distances = IOUtils.readIntArray(in, 6); double[][] matrix = new double[6][8]; for (int i = 0; i < 6; i++) matrix[i][7] = distances[i]; matrix[2][0] = 1; matrix[4][0] = 1; matrix[5][0] = 1; matrix[1][1] = 1; matrix[3][1] = 1; matrix[5][1] = 1; matrix[0][2] = 1; matrix[3][2] = 1; matrix[4][2] = 1; matrix[0][3] = 1; matrix[1][3] = 1; matrix[2][3] = 1; matrix[1][4] = 1; matrix[2][4] = 1; matrix[3][4] = 1; matrix[4][4] = 1; matrix[0][5] = 1; matrix[2][5] = 1; matrix[3][5] = 1; matrix[5][5] = 1; matrix[0][6] = 1; matrix[1][6] = 1; matrix[4][6] = 1; matrix[5][6] = 1; for (int i = 0; i < 6; i++) { int row = i; for (int j = i + 1; j < 6; j++) { if (Math.abs(matrix[row][i]) < Math.abs(matrix[j][i])) row = j; } for (int j = i; j < 8; j++) { double temp = matrix[row][j]; matrix[row][j] = matrix[i][j]; matrix[i][j] = temp; } for (int j = 7; j >= i; j--) matrix[i][j] /= matrix[i][i]; for (int j = 0; j < 6; j++) { if (i == j) continue; for (int k = 7; k >= i; k--) matrix[j][k] -= matrix[i][k] * matrix[j][i]; } } double[] result = new double[7]; for (int i = 0; i < 6; i++) result[i] = matrix[i][7]; double min = Double.POSITIVE_INFINITY; for (int i = 0; i < 4; i++) min = Math.min(min, result[i]); for (int i = 0; i < 4; i++) result[i] -= min; for (int i = 4; i < 7; i++) result[i] += min; int[] answer = new int[7]; for (int i = 0; i < 7; i++) { if (Math.abs(result[i] - Math.round(result[i])) > 1e-7) { out.printLine(-1); return; } answer[i] = (int) (result[i] + .5); if (answer[i] < 0) { out.printLine(-1); return; } } StringBuilder[] strings = new StringBuilder[4]; for (int i = 0; i < 4; i++) strings[i] = new StringBuilder(); for (int i = 0; i < 7; i++) { for (int j = 0; j < answer[i]; j++) { for (int k = 0; k < 4; k++) strings[k].append(pattern[i][k]); } } out.printLine(strings[0].length()); for (StringBuilder builder : strings) out.printLine(builder); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 readInt() { 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
8cdb9afdfb759c4bbe5a4d35e689dd02
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author niyaznigmatul */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); FastPrinter out = new FastPrinter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, FastScanner in, FastPrinter out) { int[][] d = new int[4][4]; for (int i = 0; i < 4; i++) { for (int j = i + 1; j < 4; j++) { d[i][j] = d[j][i] = in.nextInt(); } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { if (d[i][k] + d[k][j] < d[i][j] || (d[i][j] & 1) != (d[i][k] + d[k][j] & 1)) { out.println(-1); return; } } } } int sum = d[0][2]; int dif = d[1][2] - d[0][1]; int d1 = (sum + dif) / 2; int d2 = (sum - dif) / 2; int b1 = d[1][3] - d[0][1] + d[2][3] - d1 - d2; int b2 = d1 + d2 + d[0][3] - d[2][3]; int b3 = d[0][1] + d[0][3] - d[1][3]; if (d1 < 0 || d2 < 0 || d2 > d[0][1] || (b1 & 1) == 1 || (b2 & 1) == 1 || (b3 & 1) == 1) { out.println(-1); return; } b1 /= 2; b2 /= 2; b3 /= 2; for (int e1 = 0; e1 <= 1000000; e1++) { int e4 = e1 - b1; if (e4 < 0 || e4 > d2) { continue; } int e2 = b2 - e4; if (e2 < 0 || e2 > d1) { continue; } int e3 = b3 - e4; if (e3 < 0 || e3 > d[0][1] - d2) { continue; } int len = e1 + d1 + d[0][1]; out.println(len); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append('a'); } out.println(sb); sb.setLength(0); for (int i = 0; i < len; i++) { sb.append(i < len - d[0][1] ? 'a' : 'b'); } out.println(sb); sb.setLength(0); for (int i = 0; i < e1; i++) { sb.append('a'); } for (int i = 0; i < d1; i++) { sb.append('b'); } for (int i = 0; i < d[0][1] - d2; i++) { sb.append('a'); } for (int i = 0; i < d2; i++) { sb.append('b'); } out.println(sb); sb.setLength(0); for (int i = 0; i < e1; i++) { sb.append('b'); } for (int i = 0; i < d1 - e2; i++) { sb.append('a'); } for (int i = 0; i < e2; i++) { sb.append('b'); } for (int i = 0; i < d[0][1] - d2 - e3; i++) { sb.append('a'); } for (int i = 0; i < e3; i++) { sb.append('b'); } for (int i = 0; i < d2 - e4; i++) { sb.append('a'); } for (int i = 0; i < e4; i++) { sb.append('b'); } out.println(sb); return; } out.println(-1); } } class FastScanner extends BufferedReader { boolean isEOF; public FastScanner(InputStream is) { super(new InputStreamReader(is)); } public int read() { try { int ret = super.read(); if (isEOF && ret < 0) { throw new InputMismatchException(); } isEOF = ret == -1; return ret; } catch (IOException e) { throw new InputMismatchException(); } } static boolean isWhiteSpace(int c) { return c >= -1 && c <= 32; } public int nextInt() { int c = read(); while (isWhiteSpace(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int ret = 0; while (!isWhiteSpace(c)) { if (c < '0' || c > '9') { throw new NumberFormatException("digit expected " + (char) c + " found"); } ret = ret * 10 + c - '0'; c = read(); } return ret * sgn; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
7e18b5f13a2bfb61920edf7893bae64b
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
//package round122; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; public class C { InputStream is; PrintWriter out; String INPUT = "10 10 8 8 8 10"; void solve() { int[] a = new int[6]; for(int i = 0;i < 6;i++)a[i] = ni(); // 12 13 14 23 24 34 // 0001 // 0010 // 0011 // 0100 // 0101 // 0110 // 0111 outer: for(int i = 1;i <= 200000;i++){ double[][] M = new double[][]{ {0, 0, 0, 1, 1, 1, 1}, {0, 1, 1, 0, 0, 1, 1}, {1, 0, 1, 0, 1, 0, 1}, {0, 1, 1, 1, 1, 0, 0}, {1, 0, 1, 1, 0, 1, 0}, {1, 1, 0, 0, 1, 1, 0}, {1, 1, 1, 1, 1, 1, 1} }; double[] v = new double[7]; for(int j = 0;j < 6;j++){ v[j] = a[j]; } v[6] = i; v = gaussianElimination(M, v); if(v == null)continue; for(int j = 0;j < 7;j++){ if(Double.isNaN(v[j]))continue outer; if(Math.abs(Math.round(v[j]) - v[j]) > 1E-8)continue outer; if(Math.round(v[j]) < 0)continue outer; } StringBuilder[] sb = new StringBuilder[4]; for(int j = 0;j < 4;j++){ sb[j] = new StringBuilder(); } for(int j = 0;j < 7;j++){ int q = (int)Math.round(v[j]); if(q > 0){ for(int k = 0;k < q;k++){ for(int l = 0;l < 4;l++){ sb[3-l].append(j+1<<31-l<0 ? 'b' : 'a'); } } } } out.println(i); for(int j = 0;j < 4;j++){ out.println(sb[j]); } return; } out.println(-1); } public double[] gaussianElimination(double[][] a, double[] c) { int n = a.length; int[] ps = new int[n]; for(int i = 0;i < n;i++)ps[i] = i; // 前進消去 for(int i = 0;i < n;i++){ int pivot = -1; int from = -1; double amax = 0; for(int j = i;j < n;j++){ if(Math.abs(a[ps[j]][i]) > amax){ amax = Math.abs(a[ps[j]][i]); pivot = ps[j]; from = j; } } if(pivot == -1)return null; int d = ps[i]; ps[i] = ps[from]; ps[from] = d; for(int j = i+1;j < n;j++){ a[ps[i]][j] /= a[ps[i]][i]; } c[ps[i]] /= a[ps[i]][i]; a[ps[i]][i] = 1.0; for(int j = i+1;j < n;j++){ for(int k = i+1;k < n;k++){ a[ps[j]][k] -= a[ps[j]][i] * a[ps[i]][k]; } c[ps[j]] -= a[ps[j]][i] * c[ps[i]]; a[ps[j]][i] = 0.0; } } // 後退差分 for(int i = n-1;i >= 0;i--){ for(int j = i-1;j >= 0;j--){ c[ps[j]] -= a[ps[j]][i] * c[ps[i]]; } } double[] ret = new double[n]; for(int i = 0;i < n;i++){ ret[i] = c[ps[i]]; } return ret; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C().run(); } public int ni() { try { int num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public long nl() { try { long num = 0; boolean minus = false; while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-')); if(num == '-'){ num = 0; minus = true; }else{ num -= '0'; } while(true){ int b = is.read(); if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } } } catch (IOException e) { } return -1; } public String ns() { try{ int b = 0; StringBuilder sb = new StringBuilder(); while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' ')); if(b == -1)return ""; sb.append((char)b); while(true){ b = is.read(); if(b == -1)return sb.toString(); if(b == '\r' || b == '\n' || b == ' ')return sb.toString(); sb.append((char)b); } } catch (IOException e) { } return ""; } public char[] ns(int n) { char[] buf = new char[n]; try{ int b = 0, p = 0; while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n')); if(b == -1)return null; buf[p++] = (char)b; while(p < n){ b = is.read(); if(b == -1 || b == ' ' || b == '\r' || b == '\n')break; buf[p++] = (char)b; } return Arrays.copyOf(buf, p); } catch (IOException e) { } return null; } double nd() { return Double.parseDouble(ns()); } boolean oj = System.getProperty("ONLINE_JUDGE") != null; void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
038d20d594780d1a1fd6c06838a5fe5d
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.awt.geom.*; import java.io.*; import java.math.*; import java.util.*; import java.util.regex.*; import static java.lang.Math.*; public class C { public static class M { // {{{ public static final boolean DETECT_OVERFLOW = false; public static long sub(long a, long b) { return add(a, neg(b)); } public static long add(long a, long b) { long r = a+b; if (DETECT_OVERFLOW && !BigInteger.valueOf(a).add(BigInteger.valueOf(b)).equals(BigInteger.valueOf(r))) { throw new ArithmeticException("Overflow: add"); } return r; } public static long mul(long a, long b) { long r = a*b; if (DETECT_OVERFLOW && !BigInteger.valueOf(a).multiply(BigInteger.valueOf(b)).equals(BigInteger.valueOf(r))) { throw new ArithmeticException("Overflow: mul"); } return r; } public static long neg(long a) { if (DETECT_OVERFLOW && a==Long.MIN_VALUE) { throw new ArithmeticException("Overflow: neg"); } return -a; } public static long gcd(long a, long b) { return b==0?a:gcd(b, a%b); } public static long lcm(long a, long b) { return mul(a, b)/gcd(a,b); } public static void swap(long[][] array, int a, int b) { long[] t = array[a]; array[a] = array[b]; array[b] = t; } int m, n; long[][] mtx; public M(long[][] mtx) { m = mtx.length; n = mtx[0].length; this.mtx = mtx; } public M mul(M operand) { long[][] result = new long[m][operand.n]; for (int k=0; k<n; k++) for (int i=0; i<m; i++) for (int j=0; j<operand.n; j++) { result[i][j] = add(result[i][j], mul(mtx[i][k], operand.mtx[k][j])); } return new M(result); } boolean neg; private int lu() { neg = false; int r = 0; int c = 0; while (r<m&&c<n) { int maxI = r; for (int i=r+1; i<m; i++) { if (abs(mtx[i][c])>abs(mtx[maxI][c])) maxI = i; } if (mtx[maxI][c]==0) { c++; continue; } if (maxI!=r) { swap(mtx, r, maxI); neg ^= true; } for (int i=r+1; i<m; i++) { if (mtx[i][c]==0) continue; long lcm = abs(lcm(mtx[i][c], mtx[r][c])); long t1 = lcm/abs(mtx[r][c]); long t2 = lcm/abs(mtx[i][c]); if ((mtx[i][c]^mtx[r][c])>=0) t2 = neg(t2); for (int j=c; j<n; j++) { mtx[i][j] = add(mul(mtx[i][j], t2), mul(mtx[r][j], t1)); } } r++; } return r; } public static int EQU_ONE_SOLUTION = 0; public static int EQU_NO_SOLUTION = -1; public static int EQU_FLOATING_SOLUTION = -2; long[] vars; public int solve() { M t = clone(); int zeroR = t.lu(); for (; zeroR>=0; zeroR--) { int r = zeroR-1; boolean allZero = true; for (int c=0; c<n-1; c++) { if (t.mtx[r][c]!=0) allZero = false; } if (!allZero) break; if (t.mtx[r][n-1]!=0) return EQU_NO_SOLUTION; } if (zeroR<n-1) return n-1-zeroR; vars = new long[zeroR]; for (int r=zeroR-1; r>=0; r--) { long constant = t.mtx[r][n-1]; for (int c=r+1; c<n-1; c++) { constant = sub(constant, mul(t.mtx[r][c], vars[c])); } if (constant%t.mtx[r][r]!=0) return EQU_FLOATING_SOLUTION; vars[r] = constant/t.mtx[r][r]; } return EQU_ONE_SOLUTION; } public M clone() { long[][] newMtx = new long[m][n]; for (int r=0; r<m; r++) for (int c=0; c<n; c++) { newMtx[r][c] = mtx[r][c]; } return new M(newMtx); } public String toString() { StringBuilder buf = new StringBuilder(); buf.append(String.format("Matrix %dx%d\n", m, n)); for (int r=0; r<m; r++) { for (int c=0; c<n; c++) { buf.append(String.format("%4d ",mtx[r][c])); } buf.append('\n'); } return buf.toString(); } } // }}} public static final char[][] TYPE = new char[7][]; public C() throws Exception { TYPE[0] = "aaab".toCharArray(); TYPE[1] = "aaba".toCharArray(); TYPE[2] = "aabb".toCharArray(); TYPE[3] = "abaa".toCharArray(); TYPE[4] = "abab".toCharArray(); TYPE[5] = "abba".toCharArray(); TYPE[6] = "abbb".toCharArray(); int[][] h = new int[4][4]; for (int i=0; i<4; i++) for (int j=i+1; j<4; j++) { h[i][j] = in.nextInt(); } long[][] equ = { { 0, 0, 0, 1, 1, 1, 1, h[0][1] }, { 0, 1, 1, 0, 0, 1, 1, h[0][2] }, { 1, 0, 1, 0, 1, 0, 1, h[0][3] }, { 0, 1, 1, 1, 1, 0, 0, h[1][2] }, { 1, 0, 1, 1, 0, 1, 0, h[1][3] }, { 1, 1, 0, 0, 1, 1, 0, h[2][3] }, { 0, 0, 0, 0, 0, 0, 1, 0 }, }; M m = new M(equ); int len = 1<<28; long[] vars = null; for (int i=0; i<=100000; i++) { m.mtx[6][7] = i; int type = m.solve(); if (type==M.EQU_ONE_SOLUTION) { boolean neg = false; int sum = 0; for (int j=0; j<m.vars.length; j++) { if (m.vars[j]<0) { neg = true; break; } sum += m.vars[j]; } if (!neg) { if (len>sum) { len = sum; vars = m.vars; } } } } if (vars!=null) { for (int i=0; i<4; i++) { for (int j=0; j<vars.length; j++) { for (int k=0; k<vars[j]; k++) { buf.append(TYPE[j][i]); } } buf.append('\n'); } System.out.println(len); } else { System.out.println(-1); } System.out.print(buf); } Scanner in = new Scanner(System.in); StringBuilder buf = new StringBuilder(); public static void main(String[] args) throws Exception { // {{{ new C(); } // }}} public static void debug(Object... arr) { // {{{ System.err.println(Arrays.deepToString(arr)); } // }}} }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
f65a73ecfb17788bfefb9391bd5951d7
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; import java.util.*; import java.util.regex.*; import java.text.*; import java.math.*; import java.awt.geom.*; public class C { public static final boolean debug = false; void pln(Object o) {System.out.println(o.toString());} void pln() {System.out.println();} void pl(Object o) {System.out.print(o.toString());} public void solve() { Scanner sc = null; if (debug) { try { sc = new Scanner(new File("C.in")); } catch (Exception e) { e.printStackTrace(); } } else { sc = new Scanner(System.in); } int h12 = sc.nextInt(); int h13 = sc.nextInt(); int h14 = sc.nextInt(); int h23 = sc.nextInt(); int h24 = sc.nextInt(); int h34 = sc.nextInt(); int[] n = new int[10]; // n1=0, n2, n3, n4, n5, n6, n7; n[1] = 0; n[2]=-(h23-h13-h12); n[3]=-(h24-h14-h12); n[4]=h24+h23-h14-h13; n[5]=-(h34-h14-h13); n[6]=h34+h23-h14-h12; n[7]=h34+h24-h13-h12; int nr = 0; for (int i=1; i<=7; i++) { if (n[i] % 2 != 0) { pln("-1"); return; } n[i] /= 2; } int min0 = Math.min(n[4], Math.min(n[6], n[7])); if (min0 < 0) { n[1] -= min0; } n[2] -= n[1]; n[3] -= n[1]; n[4] += n[1]; n[5] -= n[1]; n[6] += n[1]; n[7] += n[1]; for (int i=1; i<=7; i++) { if (n[i] < 0) { pln("-1"); return; } nr += n[i]; } pln(nr); // s1 for (int i=0; i<n[1]; i++) pl("a"); for (int i=0; i<n[2]; i++) pl("a"); for (int i=0; i<n[3]; i++) pl("a"); for (int i=0; i<n[4]; i++) pl("a"); for (int i=0; i<n[5]; i++) pl("a"); for (int i=0; i<n[6]; i++) pl("a"); for (int i=0; i<n[7]; i++) pl("a"); pln(); // s2 for (int i=0; i<n[1]; i++) pl("b"); for (int i=0; i<n[2]; i++) pl("b"); for (int i=0; i<n[3]; i++) pl("b"); for (int i=0; i<n[4]; i++) pl("b"); for (int i=0; i<n[5]; i++) pl("a"); for (int i=0; i<n[6]; i++) pl("a"); for (int i=0; i<n[7]; i++) pl("a"); pln(); // s3 for (int i=0; i<n[1]; i++) pl("b"); for (int i=0; i<n[2]; i++) pl("b"); for (int i=0; i<n[3]; i++) pl("a"); for (int i=0; i<n[4]; i++) pl("a"); for (int i=0; i<n[5]; i++) pl("b"); for (int i=0; i<n[6]; i++) pl("b"); for (int i=0; i<n[7]; i++) pl("a"); pln(); // s4 for (int i=0; i<n[1]; i++) pl("b"); for (int i=0; i<n[2]; i++) pl("a"); for (int i=0; i<n[3]; i++) pl("b"); for (int i=0; i<n[4]; i++) pl("a"); for (int i=0; i<n[5]; i++) pl("b"); for (int i=0; i<n[6]; i++) pl("a"); for (int i=0; i<n[7]; i++) pl("b"); pln(); // pw.close(); } public static void main(String[] args) { C t = new C(); t.solve(); } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
657f570bf8458521e5ef138e73deccdd
train_001.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int[] d = new int[6]; int[][] v = new int[4][4]; int vid = 0; for (int i = 0; i < 4; ++i) { for (int j = i + 1; j < 4; ++j) { d[vid] = in.nextInt(); v[i][j] = v[j][i] = vid++; } } int[][] eq = new int[6][7]; for (int set = 1; set < 15; set += 2) { for (int i = 0; i < 4; ++i) { for (int j = i + 1; j < 4; ++j) { if (((set & (1 << i)) == 0) ^ ((set & (1 << j)) == 0)) eq[v[i][j]][set / 2] = 1; } } } int[] u = new int[7]; Arrays.fill(u, -1); for (int i = 0; i < 6; ++i) { int j; for (j = 0; j < 7; ++j) if (u[j] < 0 && eq[i][j] != 0) { break; } if (j >= 7) { throw new RuntimeException(); } u[j] = i; for (int ii = 0; ii < 6; ++ii) if (ii != i) { int dd = -eq[ii][j]; int mby = eq[i][j]; for (int k = 0; k < 7; ++k) eq[ii][k] = eq[ii][k] * mby + eq[i][k] * dd; d[ii] = d[ii] * mby + d[i] * dd; } } int[] vv = new int[7]; int bsum = Integer.MAX_VALUE; int[] bestvv = new int[7]; for (int v6 = 0; v6 <= 100000; ++v6) { vv[6] = v6; boolean ok = true; for (int i = 0; i < 6; ++i) { int a = d[u[i]] - v6 * eq[u[i]][6]; int b = eq[u[i]][i]; if (a % b != 0) { ok = false; break; } vv[i] = a / b; if (vv[i] < 0) { ok = false; break; } } if (ok) { int sum = 0; for (int x : vv) sum += x; if (sum < bsum) { bsum = sum; System.arraycopy(vv, 0, bestvv, 0, 7); } } } if (bsum == Integer.MAX_VALUE) { out.println(-1); } else { out.println(bsum); for (int r = 0; r < 4; ++r) { int[] tmp = bestvv.clone(); int tmpPos = 0; for (int i = 0; i < bsum; ++i) { while (tmp[tmpPos] == 0) ++tmpPos; --tmp[tmpPos]; if (((tmpPos * 2 + 1) & (1 << r)) != 0) out.print('a'); else out.print('b'); } out.println(); } } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "constructive algorithms", "greedy", "math", "matrices" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len — the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
2ac09be60b267d3004df75a93131bf71
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[100001]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); ArrayList<Integer> al = new ArrayList(1); for (int i = 0; i < n; i++) { int xx = sc.nextInt(); if (!hm.containsKey(xx)) { hm.put(xx, 1); al.add(xx); } else { hm.replace(xx, hm.get(xx) + 1); } } int x[] = new int[al.size()]; for (int i = 0; i < al.size(); i++) { x[i] = al.get(i); } Arrays.sort(x); arr[x[0]] = hm.get(x[0]); for (int i = 1; i < al.size(); i++) { arr[x[i]] = hm.get(x[i]) + arr[x[i - 1]]; } int q = sc.nextInt(); for (int i = 0; i < q; i++) { int in = sc.nextInt(); if (in >= x[x.length - 1]) { System.out.println(arr[x[x.length-1]]); } else if (in < x[0]) { System.out.println("0"); } else if (arr[in] != 0) { System.out.println(arr[in]); } else { if (in - x[0] <= x[x.length - 1] - in) { for (int j = 0; j < x.length; j++) { if (in < x[j]) { System.out.println(arr[x[j-1]]); break; } } } else { for (int j = x.length - 1; j >= 0; j--) { if (in > x[j]) { System.out.println(arr[x[j]] ); break; } } } } } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
4f914fd87931da1d99a8de3f53d83611
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int arr[] = new int[100001]; HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); ArrayList<Integer> al = new ArrayList(1); for (int i = 0; i < n; i++) { int xx = sc.nextInt(); if (!hm.containsKey(xx)) { hm.put(xx, 1); al.add(xx); } arr[xx]++; } int x[] = new int[al.size()]; for (int i = 0; i < al.size(); i++) { x[i] = al.get(i); } Arrays.sort(x); for (int i = 1; i < al.size(); i++) { arr[x[i]] += arr[x[i - 1]]; } int q = sc.nextInt(); for (int i = 0; i < q; i++) { int in = sc.nextInt(); if (in >= x[x.length - 1]) { System.out.println(arr[x[x.length-1]]); } else if (in < x[0]) { System.out.println("0"); } else if (arr[in] != 0) { System.out.println(arr[in]); } else { int low=0; int high=x.length-1; while(low<high){ int rate=0; if(((low+high)*1.0/2)/(int)((low+high)*1.0/2)!=1){rate=((low+high)/2)+1;} else{rate=(low+high)/2;} // System.out.println(low+" "+high+" "+rate+" "+input); if(high==low+1){ if(in>=x[high]){System.out.println(arr[x[high]]); } else{System.out.println(arr[x[low]]); } break; } else if(x[rate]==in){System.out.println(arr[x[rate]]);break;} else if(x[rate]>in){high =rate;} else if(x[rate]<in){low =rate;} } if(low==high){System.out.println(arr[x[low]]);} } } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
33a7e202200fa0872b0ec2224997b00c
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java .util.*; import java .io.*; public class Main { public static void main(String[] args) throws IOException { Scanner sc =new Scanner(System.in); int n=sc.nextInt(); int []x=new int [100001]; for (int i=0;i<n;++i) x[sc.nextInt()]++; for (int i =1;i<100000;++i) x[i]=x[i-1]+x[i]; int n1 =sc.nextInt(); for (int i=0;i<n1;++i) { int b=sc.nextInt(),c; if (b>=100000) c=n; else c=x[b]; System.out.println(c); } } 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 boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
da6b5279a3d7a5987b3b00f599059c1b
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Bb { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(); int[]p=new int [100001]; for(int i=0;i<n;i++) { p[sc.nextInt()]++; } for(int i=1;i<100001;i++) { p[i]+=p[i-1]; } int q=sc.nextInt(); while(q-->0) { int m=Math.min(100000, sc.nextInt()); System.out.println(p[m]); } } public static void shuffle(int[]a) { for(int i=0;i<a.length;i++) { int x=(int)(Math.random()*a.length); int temp=a[i]; a[i]=a[x]; a[x]=temp; }} static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader( s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
0c62b15723a3e1fb7f2ae56e00935454
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author surya */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = Integer.parseInt(in.readLine()); StringTokenizer st = new StringTokenizer(in.readLine()); int shops[] = new int[n]; for (int i = 0; i < n; i++) { shops[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(shops); int q = Integer.parseInt(in.readLine()); for (int i = 0; i < q; i++) { int coins = Integer.parseInt(in.readLine()); int search = binSearch(shops, coins); if (search != -1) { out.println(search + 1); } else { out.println(0); } } } int binSearch(int arr[], int target) { int l = 0; int r = arr.length - 1; int ans = -1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] <= target) { ans = mid; l = mid + 1; } else { r = mid - 1; } } return ans; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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++]; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
1a57e484162a96303b10224d36b50c1f
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.util.Scanner; import java.util.Arrays; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] search = new int[100000]; int n = input.nextInt(); int[] shops = new int[n]; for( int i=0; i<=n-1; i++) shops[i] = input.nextInt(); Arrays.sort(shops); int count = 0; for( int i=0; i<=n-2; i++) { count++; for( int j=shops[i]; j<=shops[i+1]-1; j++) search[j] = count; } for( int i=shops[n-1]; i<=100000-1; i++) search[i] = n; int m = input.nextInt(); int[] coins = new int[m]; for( int i=0; i<=m-1; i++) { coins[i] = input.nextInt(); if(coins[i]>=100000) System.out.println(n); else System.out.println(search[coins[i]]); } /*quickSort(shops,0,shops.length-1); for( int i=0; i<=m-1; i++) System.out.println(binarySearch(coins[i],shops));*/ } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
f342b93c0a8b1ab8f679299b03ed06a9
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.util.Arrays; import java.util.Map; import java.util.Scanner; /** * Created by Kafukaaa on 16/9/25. */ public class InterestingDrink { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = scanner.nextInt(); } Arrays.sort(x); int max = x[n-1]; int min = x[0]; int q = scanner.nextInt(); for (int i = 0; i < q; i++) { int answer = 0; int m = scanner.nextInt(); if (m < min) { System.out.println(0); } else if (m >= max) { System.out.println(n); } else { int start = 0; int end = n-1; if (n == 2){ answer = 1; }else { while (true) { if (start+1 == end) { if (m >= x[end]) { answer = end+1; }else { answer = start+1; } break; }else if (m < x[(start + end + 1) / 2]) { end = (start+end) / 2; }else if (m >= x[(start + end + 1) / 2]){ start = (start+end)/2; } } } System.out.println(answer); } } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
e343aad40767895659d602c8c8e61872
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.util.*; public class Solution { public static void main(String args[]) { Scanner s = new Scanner(System.in); int numShops = s.nextInt(); int shops[] = new int[numShops]; for(int i = 0; i < numShops; i++) { shops[i] = s.nextInt(); } Arrays.sort(shops); int numDays = s.nextInt(); for(int i = 0; i < numDays; i++) { int coins = s.nextInt(); if(coins < shops[0]) { System.out.println(0); } else if(coins >= shops[numShops-1]) { System.out.println(numShops); } else { int index = runBinarySearchIteratively(shops, coins); System.out.println(index + 1); } } } public static int runBinarySearchIteratively(int[] sortedArray, int key) { int low = 0; int high = sortedArray.length - 1; while (low != high - 1) { int mid = (low + high) / 2; if (sortedArray[mid] <= key) { low = mid; } else { high = mid; } } return low; } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
185cfdd43877923964feb751a4d7759d
train_001.jsonl
1470933300
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class hgfkuyf { public static int upperBound(int[] array, int value) { int low = 0; int length= array.length; int high = length; while (low < high) { final int mid = (low + high) / 2; if (value >= array[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int arr[]=new int [n]; // long brr[]=new long [10000000]; for (int i = 0; i < n; i++) { arr[i]=s.nextInt(); } Arrays.sort(arr); int q=s.nextInt(); while (q-->0){ int a=s.nextInt(); System.out.println(upperBound(arr,a)); } } }
Java
["5\n3 10 8 6 11\n4\n1\n10\n3\n11"]
2 seconds
["0\n4\n1\n5"]
NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop.
Java 8
standard input
[ "dp", "binary search", "implementation" ]
80a03e6d513f4051175cd5cd1dea33b4
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1 ≤ xi ≤ 100 000) — prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1 ≤ mi ≤ 109) — the number of coins Vasiliy can spent on the i-th day.
1,100
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
standard output
PASSED
ad2c9a92041a2db3572b0268cbabc13c
train_001.jsonl
1553267100
For a given set of two-dimensional points $$$S$$$, let's denote its extension $$$E(S)$$$ as the result of the following algorithm:Create another set of two-dimensional points $$$R$$$, which is initially equal to $$$S$$$. Then, while there exist four numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ such that $$$(x_1, y_1) \in R$$$, $$$(x_1, y_2) \in R$$$, $$$(x_2, y_1) \in R$$$ and $$$(x_2, y_2) \notin R$$$, add $$$(x_2, y_2)$$$ to $$$R$$$. When it is impossible to find such four integers, let $$$R$$$ be the result of the algorithm.Now for the problem itself. You are given a set of two-dimensional points $$$S$$$, which is initially empty. You have to process two types of queries: add some point to $$$S$$$, or remove some point from it. After each query you have to compute the size of $$$E(S)$$$.
1024 megabytes
import java.io.*; import java.util.*; public class F { public static void main(String[] args) throws IOException { try (Input input = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) { int n = input.nextInt(); final class Coordinate { private final int axis, value; private Coordinate(int axis, int value) { this.axis = axis; this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; Coordinate that = (Coordinate) o; return axis == that.axis && value == that.value; } @Override public int hashCode() { return Objects.hash(axis, value); } } final class Point { private final int x, y; private Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; Point point = (Point) o; return x == point.x && y == point.y; } @Override public int hashCode() { return Objects.hash(x, y); } } Map<Coordinate, Integer> coordToIndex = new HashMap<>(); final int MAX_COORDS = 600_000; int[] axis = new int[MAX_COORDS]; Point[] points = new Point[n]; for (int i = 0; i < n; i++) { int[] coords = new int[2]; for (int j = 0; j < 2; j++) { Coordinate c = new Coordinate(j, input.nextInt()); int index = coordToIndex.getOrDefault(c, coordToIndex.size()); if (index == coordToIndex.size()) { coordToIndex.put(c, index); axis[index] = j; } coords[j] = index; } points[i] = new Point(coords[0], coords[1]); } int totalCoords = coordToIndex.size(); class DSU { private int[] roots = new int[totalCoords]; { for (int i = 0; i < totalCoords; i++) { roots[i] = i; } } private int[] heights = new int[totalCoords]; { for (int i = 0; i < totalCoords; i++) { heights[i] = 1; } } private int[] x = new int[totalCoords]; private int[] y = new int[totalCoords]; { for (int i = 0; i < totalCoords; i++) { x[i] = 1 - axis[i]; y[i] = axis[i]; } } private long extensionSize = 0; private int findRoot(int x) { return x == roots[x] ? x : findRoot(roots[x]); } private int[] operations = new int[n]; private boolean[] increasedHeight = new boolean[n]; private int operationCount = 0; boolean unite(int a, int b) { a = findRoot(a); b = findRoot(b); if (a == b) { return false; } if (heights[a] > heights[b]) { int t = a; a = b; b = t; } if (heights[a] == heights[b]) { increasedHeight[operationCount] = true; heights[b]++; } else { increasedHeight[operationCount] = false; } operations[operationCount++] = a; extensionSize -= (long)x[a] * y[a] + (long)x[b] * y[b]; roots[a] = b; x[b] += x[a]; y[b] += y[a]; extensionSize += (long)x[b] * y[b]; return true; } void undoLastUnion() { int a = operations[--operationCount]; int b = roots[a]; if (increasedHeight[operationCount]) { heights[b]--; } extensionSize -= (long)x[b] * y[b]; x[b] -= x[a]; y[b] -= y[a]; roots[a] = a; extensionSize += (long)x[a] * y[a] + (long)x[b] * y[b]; } } class SegmentTree { int size = 1; { while (size <= n) { size *= 2; } } private List[] p = new List[2 * size]; { for (int i = 0; i < p.length; i++) { p[i] = new ArrayList<Point>(); } } private void add(int l, int r, Point point) { for (l += size, r += size; l < r; l /= 2, r /= 2) { if (l % 2 == 1) { p[l++].add(point); } if (r % 2 == 1) { p[--r].add(point); } } } private void findExtensionSizes(int node, DSU dsu) { int newUnions = 0; for (Object o : p[node]) { Point point = (Point)o; if (dsu.unite(point.x, point.y)) { newUnions++; } } if (node >= size) { if (node - size < n) { writer.print(dsu.extensionSize + " "); } } else { findExtensionSizes(2 * node, dsu); findExtensionSizes(2 * node + 1, dsu); } for (int i = 0; i < newUnions; i++) { dsu.undoLastUnion(); } } private void findExtensionSizes() { findExtensionSizes(1, new DSU()); } } SegmentTree segmentTree = new SegmentTree(); Map<Point, Integer> pointSet = new HashMap<>(); for (int i = 0; i < n; i++) { if (pointSet.containsKey(points[i])) { segmentTree.add(pointSet.get(points[i]), i, points[i]); pointSet.remove(points[i]); } else { pointSet.put(points[i], i); } } for (Map.Entry<Point, Integer> entry : pointSet.entrySet()) { segmentTree.add(entry.getValue(), n, entry.getKey()); } segmentTree.findExtensionSizes(); } } interface Input extends Closeable { String next() throws IOException; default int nextInt() throws IOException { return Integer.parseInt(next()); } default long nextLong() throws IOException { return Long.parseLong(next()); } } private static class StandardInput implements Input { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer stringTokenizer; @Override public void close() throws IOException { reader.close(); } @Override public String next() throws IOException { if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } } }
Java
["7\n1 1\n1 2\n2 1\n2 2\n1 2\n1 3\n2 1"]
3.5 seconds
["1 2 4 4 4 6 3"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer" ]
feff009596baf8e2d7f1aac36b2f077e
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each containing two integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le 3 \cdot 10^5$$$), denoting $$$i$$$-th query as follows: if $$$(x_i, y_i) \in S$$$, erase it from $$$S$$$, otherwise insert $$$(x_i, y_i)$$$ into $$$S$$$.
2,600
Print $$$q$$$ integers. $$$i$$$-th integer should be equal to the size of $$$E(S)$$$ after processing first $$$i$$$ queries.
standard output
PASSED
595257a7532e602a075d1b6052afe126
train_001.jsonl
1553267100
For a given set of two-dimensional points $$$S$$$, let's denote its extension $$$E(S)$$$ as the result of the following algorithm:Create another set of two-dimensional points $$$R$$$, which is initially equal to $$$S$$$. Then, while there exist four numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ such that $$$(x_1, y_1) \in R$$$, $$$(x_1, y_2) \in R$$$, $$$(x_2, y_1) \in R$$$ and $$$(x_2, y_2) \notin R$$$, add $$$(x_2, y_2)$$$ to $$$R$$$. When it is impossible to find such four integers, let $$$R$$$ be the result of the algorithm.Now for the problem itself. You are given a set of two-dimensional points $$$S$$$, which is initially empty. You have to process two types of queries: add some point to $$$S$$$, or remove some point from it. After each query you have to compute the size of $$$E(S)$$$.
1024 megabytes
import java.util.*; import java.io.*; import java.text.*; //Solution Credits: Taranpreet Singh public class Main{ //SOLUTION BEGIN void pre() throws Exception{} TreeSet<Point>[] tr; int[] set; long[] szx, szy; void solve(int TC) throws Exception{ int n = ni(); int[][] p = new int[n][];int c = 0; TreeMap<Point, Integer> map = new TreeMap<>(); for(int i = 0; i< n; i++){ Point pt = new Point(ni(), ni()); if(map.containsKey(pt)){ p[map.get(pt)][3] = i-1; map.remove(pt); }else{ map.put(pt, c); p[c++] = new int[]{pt.x,pt.y, i, n-1}; } } set = new int[2*MX];szx = new long[2*MX];szy = new long[2*MX]; for(int i = 0; i< set.length; i++){ set[i] = i; szx[i] = (i< MX?1:0); szy[i] = 1-szx[i]; } tr = new TreeSet[4*n]; for(int i = 0; i< tr.length; i++)tr[i] = new TreeSet<>(); for(int i = 0; i< c; i++)add(p[i][2], p[i][3], 0, n-1, 1, new Point(p[i][0], p[i][1])); solve(1, 0, n-1); } void add(int l, int r, int ll, int rr, int i, Point p){ if(l==ll && r==rr){ tr[i].add(p); return; } int mid = (ll+rr)/2; if(r<=mid)add(l, r, ll, mid, i<<1, p); else if(l>mid)add(l,r,mid+1,rr,i<<1|1,p); else{ add(l,mid,ll,mid,i<<1,p); add(mid+1,r,mid+1,rr,i<<1|1,p); } } int find(int[] set, int x){ return set[x]==x?x:find(set, set[x]); } long ans = 0; void union(int[] set, long[] szx, long[] szy, int x, int y, Stack<Integer> s){ x = find(set, x);y = find(set, y); if(x==y)return; if(szx[x]+szy[x]<szx[y]+szy[y]){ int t = x;x = y;y = t; } set[y] = x; ans += szx[x]*szy[y]+szx[y]*szy[x]; szx[x] += szx[y]; szy[x] += szy[y]; s.push(y); } void undo(Stack<Integer> s){ while(!s.isEmpty()){ int y = s.pop(), x = set[y]; szx[x] -= szx[y]; szy[x] -= szy[y]; ans -= szx[x]*szy[y]+szx[y]*szy[x]; set[y] = y; } } void solve(int i, int l, int r){ // pni(i+" "+l+" "+r); Stack<Integer> s = new Stack<>(); long aa = ans; for(Point p:tr[i]) union(set, szx, szy, p.x, p.y+MX,s); int mid = (l+r)/2; if(l==r)p(ans+" "); else{ solve(i<<1, l, mid); solve(i<<1|1, mid+1,r); } undo(s);ans = aa; } class Point implements Comparable<Point>{ int x, y; public Point(int x, int y){ this.x= x;this.y = y; } public int compareTo(Point p){ if(x!=p.x)return Integer.compare(x,p.x); return Integer.compare(y,p.y); } } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long mod = (long)1e9+7, IINF = (long)1e18; final int INF = (int)1e9, MX = (int)3e5+2; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.1415926535897932384626433832792884197169399375105820974944, eps = 1e-8; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC)?ni():1; //Solution Credits: Taranpreet Singh pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["7\n1 1\n1 2\n2 1\n2 2\n1 2\n1 3\n2 1"]
3.5 seconds
["1 2 4 4 4 6 3"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer" ]
feff009596baf8e2d7f1aac36b2f077e
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each containing two integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le 3 \cdot 10^5$$$), denoting $$$i$$$-th query as follows: if $$$(x_i, y_i) \in S$$$, erase it from $$$S$$$, otherwise insert $$$(x_i, y_i)$$$ into $$$S$$$.
2,600
Print $$$q$$$ integers. $$$i$$$-th integer should be equal to the size of $$$E(S)$$$ after processing first $$$i$$$ queries.
standard output
PASSED
3c3f26357ab217c8133d78c13b43781f
train_001.jsonl
1553267100
For a given set of two-dimensional points $$$S$$$, let's denote its extension $$$E(S)$$$ as the result of the following algorithm:Create another set of two-dimensional points $$$R$$$, which is initially equal to $$$S$$$. Then, while there exist four numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ such that $$$(x_1, y_1) \in R$$$, $$$(x_1, y_2) \in R$$$, $$$(x_2, y_1) \in R$$$ and $$$(x_2, y_2) \notin R$$$, add $$$(x_2, y_2)$$$ to $$$R$$$. When it is impossible to find such four integers, let $$$R$$$ be the result of the algorithm.Now for the problem itself. You are given a set of two-dimensional points $$$S$$$, which is initially empty. You have to process two types of queries: add some point to $$$S$$$, or remove some point from it. After each query you have to compute the size of $$$E(S)$$$.
1024 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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() { 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); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<27).start(); } class Move { int child, par, prevRank; Move(int a, int b, int c) { child = a; par = b; prevRank = c; } } class Edge { int u, v; Edge(int a, int b) { u = a; v = b; } } int find(int i) { if(par[i] == i) return i; return find(par[i]); } void rollback(LinkedList<Move> list) { while(list.size() > 0) { Move m = list.getLast(); int child = m.child; int parent = m.par; cntX[parent] -= cntX[child]; cntY[parent] -= cntY[child]; cans -= cntX[parent] * cntY[child] + cntX[child] * cntY[parent]; rank[parent] = m.prevRank; par[child] = child; list.removeLast(); } } void combine(int u, int v, LinkedList<Move> list) { cans += cntX[u] * cntY[v] + cntX[v] * cntY[u]; if(rank[u] > rank[v]) { list.add(new Move(v, u, rank[u])); cntX[u] += cntX[v]; cntY[u] += cntY[v]; par[v] = u; } else { list.add(new Move(u, v, rank[v])); cntX[v] += cntX[u]; cntY[v] += cntY[u]; if(rank[v] == rank[u]) rank[v]++; par[u] = v; } } void solve(int low, int high, int pos) { LinkedList<Move> list = new LinkedList<>(); for(Edge e : segTree[pos]) { int u = find(e.u); int v = find(e.v); if(u != v) { combine(u, v, list); } } if(low != high) { int mid = (low + high) >> 1; solve(low, mid, 2 * pos + 1); solve(mid + 1, high, 2 * pos + 2); } else ans[low] = cans; rollback(list); } void addEdge(int low, int high, int pos, int l, int r, Edge e) { if(low > r || high < l) return; if(low >= l && high <= r) { segTree[pos].add(e); return; } int mid = (low + high) >> 1; addEdge(low, mid, 2 * pos + 1, l, r, e); addEdge(mid + 1, high, 2 * pos + 2, l, r, e); } long cans = 0; ArrayList<Edge> segTree[]; long ans[]; long cntX[], cntY[]; int par[], rank[]; public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int q = sc.nextInt(); segTree = new ArrayList[4 * q]; for(int i = 0; i < 4 * q; ++i) { segTree[i] = new ArrayList<>(); } TreeMap<Integer, Integer> map[] = new TreeMap[300000]; for(int i = 0; i < 300000; ++i) map[i] = new TreeMap<>(); for(int x = 0; x < q; ++x) { int indx = sc.nextInt() - 1; int indy = sc.nextInt() + 299999; if(map[indx].get(indy) != null) { addEdge(0, q - 1, 0, map[indx].get(indy), x - 1, new Edge(indx, indy)); map[indx].remove(indy); } else map[indx].put(indy, x); } for(int i = 0; i < 300000; ++i) { for(int j : map[i].keySet()) addEdge(0, q - 1, 0, map[i].get(j), q - 1, new Edge(i, j)); } ans = new long[q]; cntX = new long[600000]; cntY = new long[600000]; par = new int[600000]; rank = new int[600000]; for(int i = 0; i < 600000; ++i) { rank[i] = 0; par[i] = i; if(i < 300000) cntX[i] = 1; else cntY[i] = 1; } solve(0, q - 1, 0); for(long i : ans) w.print(i + " "); w.close(); } }
Java
["7\n1 1\n1 2\n2 1\n2 2\n1 2\n1 3\n2 1"]
3.5 seconds
["1 2 4 4 4 6 3"]
null
Java 8
standard input
[ "data structures", "dsu", "divide and conquer" ]
feff009596baf8e2d7f1aac36b2f077e
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow, each containing two integers $$$x_i$$$, $$$y_i$$$ ($$$1 \le x_i, y_i \le 3 \cdot 10^5$$$), denoting $$$i$$$-th query as follows: if $$$(x_i, y_i) \in S$$$, erase it from $$$S$$$, otherwise insert $$$(x_i, y_i)$$$ into $$$S$$$.
2,600
Print $$$q$$$ integers. $$$i$$$-th integer should be equal to the size of $$$E(S)$$$ after processing first $$$i$$$ queries.
standard output