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
|
e4531b611bb3c1131fc9baac77038a33
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t>0)
{
int n=sc.nextInt();
// System.out.println(n);
ArrayList<ArrayList<Integer>>graph=new ArrayList<>();
HashMap<String,Integer>mp=new HashMap<>();
for(int i=0;i<=n;i++)
{
graph.add(new ArrayList<>());
}
ArrayList<ArrayList<Integer>>l=new ArrayList<>();
for(int i=0;i<n-1;i++)
{
int u=sc.nextInt();
int v=sc.nextInt();
ArrayList<Integer>tmp=new ArrayList<>();
tmp.add(u);
tmp.add(v);
l.add(tmp);
graph.get(u).add(v);
graph.get(v).add(u);
}
int start=-1;
boolean check=false;
for(int i=1;i<=n;i++)
{
// System.out.println(graph.get(i).size());
if(graph.get(i).size()>2)
{
System.out.println("-1");
check=true;
break;
}
if(graph.get(i).size()==1)
{
start=i;
}
}
// System.out.println(start);
if(check)
{
t--;
continue;
}
int parent=-1;
int last=2;
while(start!=-1)
{
int tmp_start=start;
for(Integer el:graph.get(start))
{
if(el!=parent)
{
String tmp=el+"$"+start;
if(last==2)
{
mp.put(tmp,5);
last=5;
}
else{
mp.put(tmp,2);
last=2;
}
parent=start;
start=el;
break;
}
}
if(start==tmp_start)
{
start=-1;
}
}
for(ArrayList<Integer>tmp:l)
{
int u=tmp.get(0);
int v=tmp.get(1);
String tmp_s=u+"$"+v;
if(mp.containsKey(tmp_s))
{
System.out.print(mp.get(tmp_s)+" ");
}
else
{
String tmp_s1=v+"$"+u;
System.out.print(mp.get(tmp_s1)+" ");
}
}
System.out.println();
t=t-1;
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
fda36f701494873fc3441d3d968970c1
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
// * * * the goal is to be worlds best * * * //
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class D {
static class Pair{
long t;
long h;
Pair(long a , long b){
this.t = a;
this.h = b;
}
}
static class Edge{
int u;
int v;
Edge(int u , int v){
this.v = v;
this.u = u;
}
}
static int n;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int t = sc.nextInt();
while(t-->0){
n = sc.nextInt();
ArrayList<Integer> g[] = new ArrayList[n + 1];
for(int i = 0; i < n + 1; i++){
g[i] = new ArrayList<>();
}
int b[][] = new int[2][n - 1];
for(int i = 0; i < n - 1; i++){
int u = sc.nextInt();
int v = sc.nextInt();
g[u].add(v);
g[v].add(u);
b[0][i] = u;
b[1][i] = v;
}
//print graph
// for(int i = 1; i < n + 1; i++){
// for(int e : g[i]){
// System.out.print(e + " ");
// }
// System.out.println();
// }
HashMap<String , Integer> map = new HashMap<>();
boolean vis[] = new boolean[n + 1];
boolean can = dfs(vis , g , 1 , map , true);
if(!can){
System.out.println(-1);
continue;
}
for(int i = 0; i < n - 1; i++){
if(map.containsKey(Integer.toString(b[0][i]) + "*" + Integer.toString(b[1][i])))
System.out.print(map.get(Integer.toString(b[0][i]) + "*" + Integer.toString(b[1][i])) + " ");
else System.out.print(map.get(Integer.toString(b[1][i]) + "*" + Integer.toString(b[0][i])) + " ");
}
System.out.println();
}
}
static boolean dfs(boolean vis[] , ArrayList<Integer> g[] , int src , HashMap<String , Integer> map , boolean flag){
vis[src] = true;
int cnt = 0;
boolean can = true;
for(int nbr : g[src]){
cnt++;
if(!vis[nbr]){
if(!flag){
map.put(Integer.toString(src) + "*" + Integer.toString(nbr) , 5);
}
else{
map.put(Integer.toString(src) + "*" + Integer.toString(nbr) , 2);
}
can &= dfs(vis , g , nbr , map , flag == true ? false : true);
flag = !flag;
}
}
if(cnt > 2){
return false;
}
return can;
}
static long sum(long n){
long temp = n;
long sum = 0;
while(temp > 0){
sum += temp % 10;
temp /= 10;
}
return sum;
}
// Use this instead of Arrays.sort() on an array of ints. Arrays.sort() is n^2
// worst case since it uses a version of quicksort. Although this would never
// actually show up in the real world, in codeforces, people can hack, so
// this is needed.
static void ruffleSort(int[] a) {
//ruffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String str = "";
String nextLine() {
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
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());
}
}
// use this to find the index of any element in the array +1 ///
// returns an array that corresponds to the index of the i+1th in the array a[]
// runs only for array containing different values enclosed btw 0 to n-1
static int[] indexOf(int[] a) {
int[] toRet=new int[a.length];
for (int i=0; i<a.length; i++) {
toRet[a[i]]=i+1;
}
return toRet;
}
static long gcd(long n, long l) {
if (l==0) return n;
return gcd(l, n%l);
}
//generates all the prime numbers upto n
static void sieveOfEratosthenes(int n , ArrayList<Integer> al)
{
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
al.get(i);
}
}
static final int mod = 100000000 + 7;
static final int max_val = 2147483647;
static final int min_val = max_val + 1;
//fastPow
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
//multiply two long numbers
static long mul(long a, long b) {
return a*b%mod;
}
static int nCr(int n, int r)
{
return fact(n) / (fact(r) *
fact(n - r));
}
// Returns factorial of n
static int fact(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
// to generate the lps array
// lps means longest preffix that is also a suffix
static void generateLPS(int lps[] , String p){
int l = 0;
int r = 1;
while(l < p.length() && l < r && r < p.length()){
if(p.charAt(l) == p.charAt(r)){
lps[r] = l + 1;
l++;
r++;
}
else{
if(l > 0)
l = lps[l - 1];
else
r++;
}
}
}
//count sort --> it runs in O(n) time but compromises in space
static ArrayList<Integer> countSort(int a[]){
int max = Integer.MIN_VALUE;
for(int i=0;i<a.length;i++){
max = Math.max(max , a[i]);
}
int posfre[] = new int[max+1];
boolean negPres = false;
for(int i=0;i<a.length;i++){
if(a[i]>=0){
posfre[a[i]]++;
}
else{
negPres = true;
}
}
ArrayList<Integer> res = new ArrayList<>();
if(negPres){
int min = Integer.MAX_VALUE;
for(int i=0;i<a.length;i++){
min = Math.min(min , a[i]);
}
int negfre[] = new int[-1*min+1];
for(int i=0;i<a.length;i++){
if(a[i]<0){
negfre[-1*a[i]]++;
}
}
for(int i=min;i<0;i++){
for(int j=0;j<negfre[-1*i];j++){
res.add(i);
}
}
for(int i=0;i<=max;i++){
for(int j=0;j<posfre[i];j++){
res.add(i);
}
}
return res;
}
for(int i=0;i<=max;i++){
for(int j=0;j<posfre[i];j++){
res.add(i);
}
}
return res;
}
// returns the index of the element which is just smaller than or
// equal to the tar in the given arraylist
static int lowBound(ArrayList<Integer> ll,long tar ,int l,int r){
if(l>r) return l;
int mid=l+(r-l)/2;
if(ll.get(mid)>=tar){
return lowBound(ll,tar,l,mid-1);
}
return lowBound(ll,tar,mid+1,r);
}
// returns the index of the element which is just greater than or
// equal to the tar in the given arraylist
static int upBound(ArrayList<Integer> ll,long tar,int l ,int r){
if(l>r) return l;
int mid=l+(r-l)/2;
if(ll.get(mid)<=tar){
return upBound(ll,tar,l,mid-1);
}
return upBound(ll,tar,mid+1 ,r);
}
static void swap(int i , int j , int a[]){
int x = a[i];
int y = a[j];
a[j] = x;
a[i] = y;
}
// a -> z == 97 -> 122
// String.format("%.9f", ans) ,--> to get upto 9 decimal places , (ans is double)
// write
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
b157ad26684747beb7b9ae7592128637
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
// import java.io.DataInputStream;
// import java.io.FileInputStream;
// import java.io.IOException;
import java.io.*;
import java.util.*;
public class one
{
static Scanner sc=new Scanner(System.in);
boolean prime[];
static int prev=-1;
static int dp[][];
public static int[] input(int size){
int arr[]=new int[size];
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
return arr;
}
public static void main(String[] args) {
//int testcase=1;
int testcase=sc.nextInt();
//System.out.println("HI");
while(testcase-->0){
// int x=sc.nextInt();
// int y=sc.nextInt();
//String str[]=new String[size];
solve();
System.out.println();
}
}
public static void solve(){
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int size=sc.nextInt();
int arr[][]=new int[size-1][2];
for(int i=0;i<size-1;i++){
arr[i][0]=sc.nextInt();
arr[i][1]=sc.nextInt();
}
for(int x[]:arr){
map.put(x[0],map.getOrDefault(x[0], 0)+1);
map.put(x[1],map.getOrDefault(x[1], 0)+1);
if(map.get(x[0])>2||map.get(x[1])>2){
System.out.println(-1);
return;
}
}
List<List<Integer>> adj=new ArrayList<>();
for(int i=0;i<=size;i++)
adj.add(new ArrayList<Integer>());
for(int x[]:arr){
adj.get(x[0]).add(x[1]);
adj.get(x[1]).add(x[0]);
}
//System.out.println(adj);
int vist[]=new int[size+1];
HashMap<String,Integer> ans=new HashMap<String,Integer>();
for(int i=1;i<=size;i++){
if(vist[i]==0){
dfs(i,vist,adj,ans,2);
}
}
//System.out.println(ans);
for(int x[]:arr){
//System.out.print(map.get(x[0]));
int a=Math.min(x[0],x[1]);
int b=Math.max(x[0],x[1]);
String s=a+" "+b;
System.out.print(ans.get(s)+" ");
}
// map=new HashMap<Integer,Integer>();
// for(int x[]:arr){
// if(map.containsKey(x[0])){
// int val=13-map.get(x[0]);
// map.put(x[1],val);
// System.out.print(val+" ");
// }else if(map.containsKey(x[1])){
// int val=13-map.get(x[1]);
// map.put(x[0],val);
// System.out.print(val+" ");
// }else{
// System.out.print(2+" ");
// map.put(x[0],2);
// map.put(x[1],2);
// }
// }
}
public static void dfs(int node,int vist[],List<List<Integer>> adj,HashMap<String,Integer> ans,int val){
vist[node]=1;
for(int i:adj.get(node)){
if(vist[i]==1)
continue;
int x=Math.min(i, node);
int y=Math.max(i, node);
ans.put(x+" "+y,val);
dfs(i,vist,adj,ans,5-val);
val=5-val;
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
42e3c1587f3c34aa5d5478b6681dee70
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Solution {
static class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return x * 13 + y;
}
@Override
public boolean equals(Object o) {
Pair x = (Pair) o;
return (x.x == this.x && x.y == this.y);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
while (t-- > 0) {
int n = Integer.parseInt(br.readLine());
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++)
adj.add(new ArrayList<>());
ArrayList<Pair> list2 = new ArrayList<>();
HashMap<Pair, Integer> map = new HashMap<>();
for (int i = 0; i < n - 1; i++) {
st = new StringTokenizer(br.readLine());
int k1 = Integer.parseInt(st.nextToken());
int k2 = Integer.parseInt(st.nextToken());
if (k1 > k2) {
int temp4 = k2;
k2 = k1;
k1 = temp4;
}
Pair temp = new Pair(k1, k2);
list2.add(temp);
adj.get(k1).add(k2);
adj.get(k2).add(k1);
}
int endp = -1;
for(int i = 1; i <=n; i++)
{
if(adj.get(i).size() == 1)
{
endp = i;
break;
}
}
int flag = 0;
if(endp == -1)
flag = 1;
Queue<Integer> q = new LinkedList<>();
q.add(endp);
int a = 2;
int vis[] = new int[n+1];
vis[endp] = 1;
while(!q.isEmpty())
{
int node = q.poll();
ArrayList<Integer> temp = adj.get(node);
if(temp.size() > 2)
{
flag = 1;
break;
}
for(int i = 0; i < temp.size(); i++)
{
if(vis[temp.get(i)] == 0)
{
vis[temp.get(i)] = 1;
q.add(temp.get(i));
int res = 7 - a;
a = res;
Pair p = new Pair(Math.min(node, temp.get(i)), Math.max(temp.get(i), node));
map.put(p, res);
}
}
}
if(flag == 1)
{
output.write("-1\n");
continue;
}
for(Pair p : list2)
output.write(map.get(p) + " ");
output.write("\n");
}
output.flush();
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
c2aa24b16392d26f94c5cc0403ffb90b
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
// Imports
import java.io.*;
import java.util.*;
public class C1627 {
public static void main(String[] args) throws IOException {
// Test once done
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(f.readLine());
for(int i = 0; i < T; i++) {
// Do stuff
int N = Integer.parseInt(f.readLine());
ArrayList<Integer>[] adj = new ArrayList[N];
int[][] edges = new int[N - 1][3];
for(int j = 0; j < N; j++) {
adj[j] = new ArrayList<Integer>();
}
for(int j = 1; j < N; j++) {
StringTokenizer st = new StringTokenizer(f.readLine());
int A = Integer.parseInt(st.nextToken()) - 1;
int B = Integer.parseInt(st.nextToken()) - 1;
edges[j - 1][0] = A;
edges[j - 1][1] = B;
adj[A].add(B);
adj[B].add(A);
}
boolean flag = false;
for(int j = 0; j < N; j++) {
if(adj[j].size() > 2) {
flag = true;
break;
}
}
if(flag) {
System.out.println(-1);
}
else {
int[] p = new int[N];
HashMap<Long, Integer> primes = new HashMap<>();
boolean[] visited = new boolean[N];
for(int j = 0; j < N; j++) {
if(!visited[j] && adj[j].size() == 1) {
Queue<Integer> q = new ArrayDeque<>();
q.add(j);
visited[j] = true;
p[j] = 2;
while(!q.isEmpty()) {
int val = q.poll();
for(int a : adj[val]) {
// Should have no visits
if(!visited[a]) {
q.add(a);
primes.put((long)a*100000 + (long)val, p[val]);
p[a] = 5 - p[val];
visited[a] = true;
}
}
}
}
}
for(int j = 0; j < edges.length; j++) {
if(primes.containsKey((long)edges[j][0]*100000 + (long)edges[j][1])) {
edges[j][2] = primes.get((long)edges[j][0]*100000 + (long)edges[j][1]);
}
else {
edges[j][2] = primes.get((long)edges[j][1]*100000 + (long)edges[j][0]);
}
}
StringBuilder sb = new StringBuilder();
for(int j = 0; j < edges.length; j++) {
sb.append(edges[j][2]);
sb.append(" ");
}
System.out.println(sb.substring(0, sb.length() - 1));
}
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
659b647e0bb556e13ec0d102066f55c4
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C_Not_Assigning {
// For fast input output
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
try {
br = new BufferedReader(
new FileReader("input.txt"));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class Edge{
public int node;
public int next;
Edge(int node, int next){
this.node = node;
this.next = next;
}
}
public static void dfs(int u, ArrayList<ArrayList<Edge>> g,int[] vis, int flag, int[] weight){
vis[u] = 1;
for(Edge e : g.get(u)){
if(vis[e.node] == 0){
if(flag == 0)
{
weight[e.next] = 2;
dfs(e.node, g, vis, 1, weight);
}
else
{
weight[e.next] = 5;
dfs(e.node, g, vis, 0, weight);
}
}
}
}
// end of fast i/o code
public static void main(String[] args) {
FastReader reader = new FastReader();
int t = reader.nextInt();
while(t-->0){
int n = reader.nextInt();
int[] order = new int[n+1];
int flag = 0;
//ArrayList<ArrayList<Integer>> adj = new ArrayList<>(n+1);
//Map<Integer, List<Integer>> adj = new HashMap<>();
ArrayList<ArrayList<Edge>> graph= new ArrayList<>();
for(int i=0;i<n+1;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n-1;i++){
int u = reader.nextInt();
int v = reader.nextInt();
order[u]++;
order[v]++;
graph.get(u).add(new Edge(v, i));
graph.get(v).add(new Edge(u, i));
if(order[u]==3 || order[v]==3){
flag = 1;
}
}
if(flag == 1)
System.out.println(-1);
else{
for(int i=1;i<=n;i++){
if(order[i] == 1){
int[] vis = new int[n+1];
int[] weight = new int[n];
dfs(i, graph, vis, 0, weight);
for(int j =0;j<n-1;j++){
System.out.print(weight[j] + " ");
}
break;
}
}
System.out.println();
}
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
2e84b4bc9c90d05480b33951401f864c
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class A {
// -- static variables --- //
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int mod = (int) 1000000007;
public static void main(String[] args) throws Exception {
int t = sc.nextInt();
while (t-- > 0)
A.go();
// out.println();
out.flush();
}
// >>>>>>>>>>>>>>>>>>> Code Starts <<<<<<<<<<<<<<<<<<<< //
static class pair {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
pair other = (pair) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
static void go() throws Exception {
int n=sc.nextInt();
ArrayList<ArrayList<Integer>> aa=new ArrayList<>();
for(int i=0;i<n;i++) {
aa.add(new ArrayList<>());
}
LinkedHashMap<pair,Integer> map=new LinkedHashMap<>();
for(int i=0;i<n-1;i++) {
int u=sc.nextInt()-1,v=sc.nextInt()-1;
aa.get(u).add(v);
aa.get(v).add(u);
if(u>v) {
int temp=v;
v=u;u=temp;
}
map.put(new pair(u,v),0);
}
for(ArrayList<Integer> i : aa) {
if(i.size()>2) {
out.println(-1);
return;
}
}
boolean vis[]=new boolean[n];
dfs(aa,0,vis,2,map);
for(pair i : map.keySet()) {
out.print(map.get(i)+" ");
}
out.println();
}
static void dfs(ArrayList<ArrayList<Integer>> aa,int src,boolean vis[],int see,LinkedHashMap<pair,Integer> map) {
vis[src]=true;
for(int i: aa.get(src)) {
if(vis[i]==false) {
int x=src,y=i;
if(x>y) {
int temp=x;
x=y;
y=temp;
}
pair temp=new pair(x,y);
if(see==2) {
map.put(temp,5);
see=5;
}else {
map.put(temp,2);
see=2;
}
dfs(aa,i,vis,see,map);
}
}
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
// >>>>>>>>>>> Code Ends <<<<<<<<< //
// --For Rounding--//
static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(Double.toString(value));
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
// ----Greatest Common Divisor-----//
static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// --- permutations and Combinations ---//
static long fact[];
static long invfact[];
static long ncr(int n, int k) {
if (k < 0 || k > n) {
return 0;
}
long x = fact[n];
long y = fact[k];
long yy = fact[n - k];
long ans = (x / y);
ans = (ans / yy);
return ans;
}
// ---sieve---//
static int prime[] = new int[1000006];
// static void sieve() {
// Arrays.fill(prime, 1);
// prime[0] = 0;
// prime[1] = 0;
// for (int i = 2; i * i <= 1000005; i++) {
// if (prime[i] == 1)
// for (int j = i * i; j <= 1000005; j +)= i) {
// prime[j] = 0;
// }
// }
// }
// ---- Manual sort ------//
static void sort(long[] a) {
ArrayList<Long> aa = new ArrayList<>();
for (long i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
static void sort(int[] a) {
ArrayList<Integer> aa = new ArrayList<>();
for (int i : a) {
aa.add(i);
}
Collections.sort(aa);
for (int i = 0; i < a.length; i++)
a[i] = aa.get(i);
}
// --- Fast exponentiation ---//
static long pow(long x, long y) {
long res = 1l;
while (y != 0) {
if (y % 2 == 1) {
res = (x * res);
}
y /= 2;
x = (x * x);
}
return res;
}
// >>>>>>>>>>>>>>> Fast IO <<<<<<<<<<<<<< //
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] intArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
return a;
}
long[] longArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextLong();
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
eca4185e489f92fb48c3e55e814e2f69
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.*;
import java.io.*;
import java.math.*;
/*
-> Give your 100%, that's it!
-> Rules To Solve Any Problem:
1. Read the problem.
2. Think About It.
3. Solve it!
*/
public class Template {
static int mod = 1000000007;
public static void main(String[] args){
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = 100001;
int yo = sc.nextInt();
while (yo-- > 0) {
List<List<Integer>> list = new ArrayList<>();
int n = sc.nextInt();
for(int i = 0; i < n; i++){
list.add(new ArrayList<>());
}
List<Pair> res = new ArrayList<>();
for(int i = 0; i < n-1; i++){
int u = sc.nextInt()-1;
int v = sc.nextInt()-1;
res.add(new Pair(u+1,v+1));
list.get(v).add(u);
list.get(u).add(v);
}
boolean ok = helper(0,list,n,-1);
if(ok){
out.println(-1);
continue;
}
map.clear();
dfs(0,list,n,-1,-1);
for(Pair p : res){
int x = p.x;
int y = p.y;
out.print(map.get(x + " " + y) + " " );
}
out.println();
}
out.close();
}
static Map<String,Integer> map = new HashMap<>();
static void dfs(int curr, List<List<Integer>> list, int n, int par, int what){
List<Integer> neighbours = list.get(curr);
if(what == -1){
boolean three = true;
for(int e : neighbours){
String str1 = (curr+1) + " " + (e+1);
String str2 = (e+1) + " " + (curr+1);
// out.println(str1);
if(three){
map.put(str1,3); map.put(str2,3);
three = false;
}
else {
map.put(str1,2);map.put(str2,2);
}
dfs(e,list,n,curr,map.get(str1));
}
}
else {
for(int e : neighbours){
if(e == par) continue;
String str1 = (curr+1) + " " + (e+1);
String str2 = (e+1) + " " + (curr+1);
if(what == 2){
map.put(str1,3);map.put(str2,3);
}
else {
map.put(str1,2); map.put(str2,2);
}
dfs(e,list,n,curr,map.get(str1));
}
}
}
static boolean helper(int curr, List<List<Integer>> list, int n, int par){
if(par != -1){
if(list.get(curr).size() >= 3){
return true;
}
}
else {
if(list.get(curr).size() > 2){
return true;
}
}
List<Integer> neighbours = list.get(curr);
for(int e : neighbours){
if(e == par) continue;
if(helper(e,list,n,curr)){
return true;
}
}
return false;
}
/*
Source: hu_tao
Random stuff to try when stuck:
- use bruteforcer
- check for n = 1, n = 2, so on
-if it's 2C then it's dp
-for combo/probability problems, expand the given form we're interested in
-make everything the same then build an answer (constructive, make everything 0 then do something)
-something appears in parts of 2 --> model as graph
-assume a greedy then try to show why it works
-find way to simplify into one variable if multiple exist
-treat it like fmc (note any passing thoughts/algo that could be used so you can revisit them)
-find lower and upper bounds on answer
-figure out what ur trying to find and isolate it
-see what observations you have and come up with more continuations
-work backwards (in constructive, go from the goal to the start)
-turn into prefix/suffix sum argument (often works if problem revolves around adjacent array elements)
-instead of solving for answer, try solving for complement (ex, find n-(min) instead of max)
-draw something
-simulate a process
-dont implement something unless if ur fairly confident its correct
-after 3 bad submissions move on to next problem if applicable
-do something instead of nothing and stay organized
-write stuff down
Random stuff to check when wa:
-if code is way too long/cancer then reassess
-switched N/M
-int overflow
-switched variables
-wrong MOD
-hardcoded edge case incorrectly
Random stuff to check when tle:
-continue instead of break
-condition in for/while loop bad
Random stuff to check when rte:
-switched N/M
-long to int/int overflow
-division by 0
-edge case for empty list/data structure/N=1
*/
public static class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void sort(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
for (int i = 0; i < arr.length; i++)
arr[i] = ls.get(i);
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] sieve(int N) {
boolean[] sieve = new boolean[N + 1];
for (int i = 2; i <= N; i++)
sieve[i] = true;
for (int i = 2; i <= N; i++) {
if (sieve[i]) {
for (int j = 2 * i; j <= N; j += i) {
sieve[j] = false;
}
}
}
return sieve;
}
public static long power(long x, long y, long p) {
long res = 1L;
x = x % p;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y >>= 1;
x = (x * x) % p;
}
return res;
}
public static void print(int[] arr, PrintWriter out) {
//for debugging only
for (int x : arr)
out.print(x + " ");
out.println();
}
public static int log2(int a){
return (int)(Math.log(a)/Math.log(2));
}
public static long ceil(long x, long y){
return (x + 0l + y - 1) / y;
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
// For Input.txt and Output.txt
// FileInputStream in = new FileInputStream("input.txt");
// FileOutputStream out = new FileOutputStream("output.txt");
// PrintWriter pw = new PrintWriter(out);
// Scanner sc = new Scanner(in);
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
34452ff911504f696ae3888438533651
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Practice
{
// static final long mod=7420738134811L;
static int mod=1000000007;
static final int size=501;
static FastReader sc=new FastReader(System.in);
// static Reader sc=new Reader();
// static Scanner sc=new Scanner(System.in);
static PrintWriter out=new PrintWriter(System.out);
static long[] factorialNumInverse;
static long[] naturalNumInverse;
static int[] sp;
static long[] fact;
static ArrayList<Integer> pr;
public static void main(String[] args) throws IOException, CloneNotSupportedException
{
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream("output.txt"));
// factorial(mod);
// InverseofNumber(mod);
// InverseofFactorial(mod);
// make_seive();
int t=1;
t=sc.nextInt();
for(int i=1;i<=t;i++)
solve(i);
out.close();
out.flush();
// System.out.flush();
// System.exit(0);
}
static void solve(int CASENO) throws IOException, CloneNotSupportedException
{
int n=sc.nextInt();
Node tree[]=new Node[n],last=null;
for(int i=0;i<n;i++)
tree[i]=new Node(i);
ArrayList<Pair> edges=new ArrayList<Pair>();
boolean pos=true;
for(int i=0;i<n-1;i++)
{
int u=sc.nextInt()-1,v=sc.nextInt()-1;
edges.add(new Pair(u,v));
tree[u].deg++;
tree[v].deg++;
tree[u].adj.put(v,0);
tree[v].adj.put(u,0);
if(tree[u].deg>2 || tree[v].deg>2)
pos=false;
}
if(!pos)
{
out.println("-1");
return;
}
for(int i=0;i<n;i++)
if(tree[i].deg==1)
{
last=tree[i];
break;
}
dfs(last,null,tree,0);
for(Pair p: edges)
{
int x=tree[p.x].adj.get(p.y);
out.print(x+" ");
}
out.println();
}
static void dfs(Node v,Node par,Node tree[],int i)
{
if(v.deg==1 && par!=null)
return;
else
{
for(int ch: v.adj.keySet())
{
if(par!=null && ch==par.vertex)
continue;
v.adj.put(ch,(i&1)==0?3:2);
tree[ch].adj.put(v.vertex, (i&1)==0?3:2);
i=1-i;
dfs(tree[ch],v,tree,i);
}
}
}
static class Pair implements Cloneable, Comparable<Pair>
{
int x,y;
Pair(int a,int b)
{
this.x=a;
this.y=b;
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof Pair)
{
Pair p=(Pair)obj;
return p.x==this.x && p.y==this.y;
}
return false;
}
@Override
public int hashCode()
{
return Math.abs(x)+500*Math.abs(y);
}
@Override
public String toString()
{
return "("+x+" "+y+")";
}
@Override
protected Pair clone() throws CloneNotSupportedException {
return new Pair(this.x,this.y);
}
@Override
public int compareTo(Pair a)
{
long t=(this.x-a.x);
if(t!=0)
return t>0?1:-1;
else
return (int)(this.y-a.y);
}
public void swap()
{
this.y=this.y+this.x;
this.x=this.y-this.x;
this.y=this.y-this.x;
}
}
static class Tuple implements Cloneable, Comparable<Tuple>
{
int x,y,z;
Tuple(int a,int b,int c)
{
this.x=a;
this.y=b;
this.z=c;
}
public boolean equals(Object obj)
{
if(obj instanceof Tuple)
{
Tuple p=(Tuple)obj;
return p.x==this.x && p.y==this.y && p.z==this.z;
}
return false;
}
@Override
public int hashCode()
{
return (this.x+501*this.y);
}
@Override
public String toString()
{
return "("+x+","+y+","+z+")";
}
@Override
protected Tuple clone() throws CloneNotSupportedException {
return new Tuple(this.x,this.y,this.z);
}
@Override
public int compareTo(Tuple a)
{
int x=this.z-a.z;
if(x!=0)
return x;
int X= this.x-a.x;
if(X!=0)
return X;
return a.y-this.y;
}
}
static void arraySort(int arr[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a,Comparator.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static void arraySort(long arr[])
{
ArrayList<Long> a=new ArrayList<Long>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static HashSet<Integer> primeFactors(int n)
{
HashSet<Integer> ans=new HashSet<Integer>();
if(n%2==0)
{
ans.add(2);
while((n&1)==0)
n=n>>1;
}
for(int i=3;i*i<=n;i+=2)
{
if(n%i==0)
{
ans.add(i);
while(n%i==0)
n=n/i;
}
}
if(n!=1)
ans.add(n);
return ans;
}
static void make_seive()
{
sp=new int[size];
pr=new ArrayList<Integer>();
for (int i=2; i<size; ++i) {
if (sp[i] == 0) {
sp[i] = i;
pr.add(i);
}
for (int j=0; j<(int)pr.size() && pr.get(j)<=sp[i] && i*pr.get(j)<size; ++j)
sp[i * pr.get(j)] = pr.get(j);
}
}
public static void InverseofNumber(int p)
{
naturalNumInverse=new long[size];
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i < size; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse=new long[size];
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// pre-compute inverse of natural numbers
for(int i = 2; i < size; i++)
factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to 200001
public static void factorial(int p)
{
fact=new long[size];
fact[0] = 1;
for(int i = 1; i < size; i++)
fact[i] = (fact[i - 1] * (long)i) % p;
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R)
{
if(R<0)
return 1;
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) % mod * factorialNumInverse[N - R]) % mod;
return ans;
}
static int findXOR(int x) //from 0 to x
{
if(x<0)
return 0;
if(x%4==0)
return x;
if(x%4==1)
return 1;
if(x%4==2)
return x+1;
return 0;
}
static boolean isPrime(long x)
{
if(x==1)
return false;
if(x<=3)
return true;
if(x%2==0 || x%3==0)
return false;
for(int i=5;i<=Math.sqrt(x);i+=2)
if(x%i==0)
return false;
return true;
}
static long gcd(long a,long b)
{
return (b==0)?a:gcd(b,a%b);
}
static int gcd(int a,int b)
{
return (b==0)?a:gcd(b,a%b);
}
static class Node
{
int vertex,deg;
HashMap<Integer,Integer> adj;
Node(int ver)
{
vertex=ver;
deg=0;
adj=new HashMap<Integer,Integer>();
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Edge
{
Node to;
int cost;
Edge(Node t,int c)
{
this.to=t;
this.cost=c;
}
@Override
public String toString() {
return "("+to.vertex+","+cost+") ";
}
}
static long power(long x, long y)
{
if(x<=0)
return 1;
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res%mod;
}
static long binomialCoeff(long n, long k)
{
if(n<k)
return 0;
long res = 1;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (long i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static class FastReader
{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is)
{
in = is;
}
int scan() throws IOException
{
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException
{
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException
{
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException
{
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
public void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
1f6c757adf0a63059515c061447009d5
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C {
class Pair {
int first, second;
public Pair(int f, int s) {
first = f;
second = s;
}
}
ArrayList<ArrayList<Pair>> graph;
int[] ret;
public void prayGod() throws IOException {
int t = nextInt();
while (t-- > 0) {
int n = nextInt();
graph = new ArrayList<>();
ret = new int[n - 1];
Arrays.fill(ret, -1);
int[] degree = new int[n];
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
int startu = -1, startv = -1;
for (int i = 0; i < n - 1; i++) {
int u = nextInt() - 1, v = nextInt() - 1;
if (startu == -1) {
startu = u;
startv = v;
}
graph.get(u).add(new Pair(v, i));
graph.get(v).add(new Pair(u, i));
degree[u]++;
degree[v]++;
}
boolean valid = true;
for (int i = 0; i < n; i++) {
if (degree[i] > 2) {
valid = false;
}
}
if (!valid) {
out.println(-1);
continue;
}
ret[0] = 2;
dfs(startu, 3);
dfs(startv, 3);
for (int v : ret) {
out.printf("%d ", v);
}
out.println();
}
}
public void dfs(int idx, int edgeVal) {
for (Pair p : graph.get(idx)) {
if (ret[p.second] != -1)
continue;
ret[p.second] = edgeVal;
dfs(p.first, edgeVal == 3 ? 2 : 3);
}
}
public long binpow(long a, long b) {
if (b < 0)
return 0;
long ret = 1, curr = a;
while (b > 0) {
if (b % 2 == 1)
ret = (ret * curr) % mod;
b /= 2;
curr = (curr * curr) % mod;
}
return ret;
}
public long gcd(long x, long y) {
if (y == 0)
return x;
return gcd(y, x % y);
}
public void printVerdict(boolean verdict) {
if (verdict)
out.println(VERDICT_YES);
else
out.println(VERDICT_NO);
}
static final String VERDICT_YES = "YES";
static final String VERDICT_NO = "NO";
static final boolean RUN_TIMING = true;
static final boolean AUTOFLUSH = false;
static final boolean FILE_INPUT = false;
static final boolean FILE_OUTPUT = false;
static int iinf = 0x3f3f3f3f;
static long inf = (long) 1e18 + 10;
static int mod = (int) 1e9 + 7;
static char[] inputBuffer = new char[1 << 20];
static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20);
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), AUTOFLUSH);
// int data-type
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
// long data-type
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public static void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
public void sort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
// double data-type
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++)
arr[i] = nextDouble();
return arr;
}
public static void printArray(double[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
// Generic type
public <T> void sort(T[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T> void printArray(T[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
public String next() throws IOException {
int len = 0;
int c;
do {
c = in.read();
} while (Character.isWhitespace(c) && c != -1);
if (c == -1) {
throw new NoSuchElementException("Reached EOF");
}
do {
inputBuffer[len] = (char) c;
len++;
c = in.read();
} while (!Character.isWhitespace(c) && c != -1);
while (c != '\n' && Character.isWhitespace(c) && c != -1) {
c = in.read();
}
if (c != -1 && c != '\n') {
in.unread(c);
}
return new String(inputBuffer, 0, len);
}
public String nextLine() throws IOException {
int len = 0;
int c;
while ((c = in.read()) != '\n' && c != -1) {
if (c == '\r') {
continue;
}
inputBuffer[len] = (char) c;
len++;
}
return new String(inputBuffer, 0, len);
}
public boolean hasNext() throws IOException {
String line = nextLine();
if (line.isEmpty()) {
return false;
}
in.unread('\n');
in.unread(line.toCharArray());
return true;
}
public void shuffle(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void shuffle(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void shuffle(Object[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
Object temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public static void main(String[] args) throws IOException {
if (FILE_INPUT)
in = new PushbackReader(new BufferedReader(new FileReader(new File("output.txt"))), 1 << 20);
if (FILE_OUTPUT)
out = new PrintWriter(new FileWriter(new File("output.txt")));
long time = 0;
time -= System.nanoTime();
new C().prayGod();
time += System.nanoTime();
if (RUN_TIMING)
System.err.printf("%.3f ms%n", time / 1000000.0);
out.flush();
in.close();
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
bfbceeb5f881bcbfb7067b3ffb1a393d
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
public class CvsMe {
private static class pair {
int low, high;
pair(int low, int high) {
this.low = low;
this.high = high;
}
@Override
public int hashCode()
{
// uses roll no to verify the uniqueness
// of the object of Student class
final int temp = 14;
int ans = 1;
ans = (temp * ans) + low +high;
return ans;
}
// Equal objects must produce the same
// hash code as long as they are equal
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
pair other = (pair)o;
if (this.low != other.low && this.high !=other.high) {
return false;
}
return true;
}
}
static int val[];
static HashMap<pair, Integer> mp;
static int ans[];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- != 0) {
int n = in.nextInt();
ArrayList<ArrayList<Integer>> edge = new ArrayList<>();
boolean flag = false;
int deg[] = new int[n + 1];
val = new int[n + 1];
ans = new int[n + 1];
mp = new HashMap<>();
for (int i = 0; i <= n; i++) {
edge.add(new ArrayList<Integer>());
}
int start = -1;
int end = -1;
for (int i = 1; i < n; i++) {
int u = in.nextInt();
int v = in.nextInt();
pair p = new pair(u, v);
mp.put(p, i);
edge.get(u).add(v);
edge.get(v).add(u);
deg[u]++;
deg[v]++;
if (deg[u] > 2 || deg[v] > 2) {
flag = true;
}
}
boolean vis[] = new boolean[n + 1];
if (flag) {
System.out.println(-1);
continue;
} else {
for (int i = 1; i <= n; i++) {
if (deg[i] == 1 ) {
start = i;break;
}
}
dfs(vis, edge, 5, start);
for (int i = 1; i < n; i++) {
System.out.print(ans[i] + " ");
}
System.out.println();
}
}
}
private static void dfs(boolean vis[], ArrayList<ArrayList<Integer>> edge, int k, int i) {
vis[i] = true;
for (int j : edge.get(i)) {
if (!vis[j]) {
int w = 2;
if (val[i] == 2 || val[j] == 2){ w = 5;}
int id = 0;
pair p = new pair(i, j);
if (mp.containsKey(p)) {
id = mp.get(p);
} else {
p = new pair(j, i);
if (mp.containsKey(p)) {id = mp.get(p);
}}
ans[id] = w;
val[i] = w;
val[j] = w;
dfs(vis, edge, k, j);
}
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
d536bf16c9fb21474fa4cedc78e19733
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
//Break in nested for loops creates problem in java
import java.util.*;
import java.io.*;
import java.lang.*;
//import java.util.stream.*;
public class A {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append(" " + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static Boolean isSquare(int n)
{
int y= (int)Math.sqrt(n);
return y*y==n;
}
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static boolean check_pow (long x)
{
return x!=0 && ((x&(x-1)) == 0);
}
static int digits(int n)
{
if(n==0)
return 1;
return (int)(Math.floor(Math.log10(n))+1);
}
static boolean isPalindrome(String str)
{
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j))
return false;
i++;j--;
}
return true;
}
public static boolean IsPrime(long number)
{
if (number < 2) return false;
if (number % 2 == 0) return (number == 2);
int root = (int)Math.sqrt((double)number);
for (int i = 3; i <= root; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
FastReader sc= new FastReader();
//FastWriter out = new FastWriter();
//StringBuilder sb=new StringBuilder("");
//PrintWriter out= new PrintWriter(System.out);
//Collections.sort(A, (a, b) -> Integer.compare(b[1], a[1]));
int t= sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
ArrayList<ArrayList<Integer>> list= new ArrayList<>();
for(int i=0;i<=n;i++)
{
list.add(new ArrayList<Integer>());
}
Map<String, Integer> map= new HashMap<>();
for(int i=0;i<n-1;i++)
{
int u=sc.nextInt();
int v=sc.nextInt();
list.get(u).add(v);
list.get(v).add(u);
map.put(u+" "+v, i+1);
map.put(v+" "+u, i+1);
}
int y=0;
for(int i=0;i<list.size();i++)
{
if(list.get(i).size()>2)
{
System.out.println(-1);
y=1;
break;
}
}
if(y==0)
{
int st=0,end=0;
for(int i=1;i<=n;i++)
{
if(list.get(i).size()==1)
{
if(st==0)
{
st=i;
}
else
end=i;
}
}
int ans[]= new int[n-1];
int val[]= {2,5};
int curr=st,par=-1,k=0;
while(curr!=end)
{
for(int it: list.get(curr))
{
if(it!=par)
{
par=curr;
curr=it;
break;
}
}
ans[map.get(curr+" "+par)-1]=val[k];
k=1-k;
}
for(int i=0;i<ans.length;i++)
System.out.print(ans[i]+" ");
System.out.println();
}
}
//System.out.println(sb);
//out.close();
}
}
class Pair {
int x;
int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
class Compare {
static void comparey(Pair arr[], int n)
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.y - p2.y;
}
});
}
static void comparex(Pair arr[], int n)
{
Arrays.sort(arr, new Comparator<Pair>() {
@Override public int compare(Pair p1, Pair p2)
{
return p1.x - p2.x;
}
});
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
f87e731aee727b4827db271c4c9e9a09
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Solution extends PrintWriter {
void solve() {
int t = sc.nextInt();
for(int i = 1; i <= t; i++) {
test_case();
}
}
void test_case() {
int n = sc.nextInt();
int[][] edges = new int[n-1][];
ArrayDeque<Integer>[] adj = new ArrayDeque[n];
for(int u = 0; u < n; u++) adj[u] = new ArrayDeque<>();
for(int e = 0; e < n-1; e++) {
int u = sc.nextInt()-1;
int v = sc.nextInt()-1;
edges[e] = new int[] {u,v,0};
adj[u].add(e);
adj[v].add(e);
}
int v = 0;
for(int u = 0; u < n; u++) {
if(adj[u].size() > 2) {
println(-1);
return;
}
if(adj[u].size() == 1) {
v = u;
}
}
boolean[] done = new boolean[n];
int cnt = 0;
while(cnt < n) {
int u = v;
done[u] = true;
cnt++;
for(int e : adj[u]) {
int v_ = other(u, edges[e]);
if(!done[v_]) {
edges[e][2] = primes[cnt%2];
v = v_;
break;
}
}
}
for(int[] e : edges) {
print(e[2] + " ");
}
println();
}
int[] primes = new int[] {2,3};
int other(int from, int[] edge) {
if(edge[0] == from) return edge[1];
else return edge[0];
}
// Main() throws FileNotFoundException { super(new File("output.txt")); }
// InputReader sc = new InputReader(new FileInputStream("test_input.txt"));
Solution() { super(System.out); }
InputReader sc = new InputReader(System.in);
static class InputReader {
InputReader(InputStream in) { this.in = in; } InputStream in;
private byte[] buf = new byte[16384];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] $) {
new Thread(null, new Runnable() {
public void run() {
long start = System.nanoTime();
try {Solution solution = new Solution(); solution.solve(); solution.flush();}
catch (Exception e) {e.printStackTrace(); System.exit(1);}
System.err.println((System.nanoTime()-start)/1E9);
}
}, "1", 1 << 27).start();
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
c1cfff4e4ad990b8470a35b310cb21a2
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Practice {
static boolean multipleTC = true;
FastReader in;
PrintWriter out;
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
int parent[];
int rank[];
ArrayList<Integer> primes;
boolean sieve[];
int pf[];
int MAX = 1000005;
int dirX[] = { 1, -1, 0, 0 };
int dirY[] = { 0, 0, -1, 1 };
public static void main(String[] args) throws Exception {
new Practice().run();
}
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
void pre() throws Exception {
}
// declare all variables fucking long even array indices.
// if you are copying some code make sure you done all necessary modifications
// that's leads WA.
// Divide by Zero Exception Ruin Your Life.
// Number Format Exception : Make sure you read constraint carefully.
// Always use TreeMap instead of HashMap.
// Always write comparators using wrapper classes;
void solve(int TC) throws Exception {
int n = ni();
// graph
adj = new ArrayList<>();
for (int i = 0; i < n; i++)
adj.add(new ArrayList<>());
for (int i = 0; i < n - 1; i++) {
int u = ni() - 1, v = ni() - 1;
adj.get(u).add(new edge(v, i));
adj.get(v).add(new edge(u, i));
}
int start = -1;
// finding any root node
for (int i = 0; i < n; i++) {
if (adj.get(i).size() > 2) {
pn("-1");
return;
} else if (adj.get(i).size() == 1) {
start = i;
}
}
res = new int[n - 1];
dfs(start, -1, 2, -1);
StringBuilder ans = new StringBuilder();
for (int i = 0; i < n - 1; i++) {
ans.append(res[i] + " ");
}
pn(ans);
}
ArrayList<ArrayList<edge>> adj;
int res[];
void dfs(int source, int parent, int weight, int index) {
if (index != -1)
res[index] = weight;
for (edge e : adj.get(source)) {
if (parent == e.x) {
continue;
}
dfs(e.x, source, 5 - weight, e.y);
}
}
class edge {
int x, y;
int weight;
edge(int x, int y) {
this.x = x;
this.y = y;
}
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
public StringBuilder printArr(int arr[]) {
StringBuilder sb = new StringBuilder();
int n = arr.length;
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
return sb;
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
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
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
3b2d1175c87b83dde84cc36569485cfa
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.math.*;
public class Main {
public static class Edge{
int u;
int v;
// int wt;
Edge(int u, int v){
this.u = u;
this.v = v;
// this.wt = wt;
}
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
StringBuilder sb = new StringBuilder("");
for(int A=0 ; A<t ; A++) {
int n = scn.nextInt();
List<Edge>[] graph = new ArrayList[n];
for(int i=0 ; i<n ; i++) {
graph[i] = new ArrayList<>();
}
String[] arr = new String[n-1];
for(int i=0 ; i<n-1 ; i++) {
int u = scn.nextInt();
int v = scn.nextInt();
arr[i] = (u-1) + " " + (v-1);
graph[u-1].add(new Edge(u-1, v-1));
graph[v-1].add(new Edge(v-1, u-1));
}
boolean flag = false;
int src = 0;
for(int i=0 ; i<n ; i++) {
if(graph[i].size() > 2) {
flag = true;
}else if(graph[i].size() == 1)
src = i;
}
if(flag) {
sb.append(-1 + "\n");
}else {
Map<String, Integer> hm = new HashMap<>();
int count = 0;
int val = 2;
// System.out.println(src);
while(count < n) {
List<Edge> e = graph[src];
int i=0;
while(i < e.size() && hm.containsKey(src + " " + e.get(i).v))
i++;
if(i < e.size()) {
int nbr = e.get(i).v;
// System.out.println(src + " " + nbr);
hm.put(src + " " + nbr, val);
hm.put(nbr + " " + src, val);
val = 5 - val;
src = nbr;
}
count++;
}
for(int i=0 ; i<arr.length ; i++) {
int wt = hm.get(arr[i]);
sb.append(wt + " ");
}
sb.append("\n");
}
}
System.out.println(sb);
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
949da6578cd97d97c95d1de10f86fd0b
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static MyScanner sc;
static PrintWriter out;
static {
sc = new MyScanner();
out = new PrintWriter(System.out);
}
public static void bfs(Node[] g, int[] ans) {
Arrays.fill(ans, -1);
boolean[] visited = new boolean[g.length];
Queue<Integer> q = new LinkedList<>();
int s = 0;
for(int i = 0; i < g.length; i++) {
if(g[i].l.size() == 1) {
s = i;
break;
}
}
q.add(s);
int curr = 2;
while(!q.isEmpty()) {
int u = q.poll();
if(visited[u])
continue;
visited[u] = true;
for(Edge edge : g[u].l) {
if(!visited[edge.v]) {
ans[edge.id] = curr;
q.add(edge.v);
if(curr == 2) curr = 3;
else curr = 2;
}
}
}
}
public static void solve() {
int n = sc.nextInt();
Node[] a = new Node[n];
for(int i = 0; i < n; i++)
a[i] = new Node();
for(int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
a[u].l.add(new Edge(v, i));
a[v].l.add(new Edge(u, i));
}
for(Node node : a) {
if(node.l.size() > 2) {
out.println(-1);
return;
}
}
int[] ans = new int[n - 1];
bfs(a, ans);
for(int i = 0; i < n - 1; i++)
out.print(ans[i] + " ");
out.println();
}
public static void main(String[] args) {
int t = sc.nextInt();
while(t-- > 0)
solve();
out.flush();
}
}
class Edge {
int v, id;
Edge(int a, int b) {
v = a;
id = b;
}
}
class Node {
ArrayList<Edge> l;
Node() {
l = new ArrayList<>();
}
}
class MyScanner {
BufferedReader br;
StringTokenizer tok;
MyScanner() {
try { br = new BufferedReader(new InputStreamReader(System.in)); }
catch(Exception e) { System.out.println(e); }
tok = new StringTokenizer("");
}
public String next() {
try {
while(!tok.hasMoreTokens()) tok = new StringTokenizer(br.readLine());
}
catch(Exception e) { System.out.println(e); }
return tok.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
f8e270cb2384c4daa14d663f07197310
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class C {
public static void main(String[] args) {
var io = new Kattio(System.in, System.out);
int t = io.nextInt();
for (int i = 0; i < t; i++) {
solve(io);
}
io.close();
}
public static void solve(Kattio io) {
int n = io.nextInt();
var graph = new ArrayList<ArrayList<Edge>>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = io.nextInt();
int v = io.nextInt();
u--; v--;
graph.get(u).add(new Edge(v, i));
graph.get(v).add(new Edge(u, i));
}
int start = 0;
for (int i = 0; i < n; i++) {
if (graph.get(i).size() > 2) {
io.println("-1");
return;
} else if (graph.get(i).size() == 1) {
start = i;
}
}
int[] weight = new int[n - 1];
int prevNode = -1;
int curNode = start;
int curWeight = 2;
while (true) {
var edges = graph.get(curNode);
var next = edges.get(0);
if (next.node == prevNode) {
if (edges.size() == 1) {
break;
} else {
next = edges.get(1);
}
}
weight[next.index] = curWeight;
prevNode = curNode;
curNode = next.node;
curWeight = 5 - curWeight;
}
for (int i = 0; i < n - 1; i++) {
io.print(weight[i]);
io.print(" ");
}
io.println();
}
static class Edge {
public int node;
public int index;
Edge(int node, int index) {
this.node = node;
this.index = index;
}
}
}
// modified from https://github.com/Kattis/kattio/blob/master/Kattio.java
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
c9f6c32140dda995a9192b54b212923e
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class NotAssigning {
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 nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = this.nextInt();
}
return a;
}
long[] nextArrayLong(int n) {
long[] a = new long[n];
for (int i=0; i<n; i++) {
a[i] = this.nextLong();
}
return a;
}
}
static class Pair {
int a, b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static boolean vis[];
public static void dfs(ArrayList<ArrayList<Pair>> t, int cur, boolean mode, int[] w) {
vis[cur] = true;
for (Pair p : t.get(cur)) {
if (!vis[p.a]) {
if (mode) {
w[p.b] = 3;
}
else {
w[p.b] = 2;
}
dfs(t, p.a, !mode, w);
}
}
}
public static void solve(int n, int[] u, int[] v) {
ArrayList<ArrayList<Pair>> t = new ArrayList<ArrayList<Pair>>(n);
for (int i=0; i<n; i++) {
t.add(new ArrayList<Pair>());
}
for (int i=0; i<n-1; i++) {
t.get(u[i]).add(new Pair(v[i], i));
t.get(v[i]).add(new Pair(u[i], i));
}
int start = 0;
for (int i=0; i<n; i++) {
if (t.get(i).size() > 2) {
System.out.println("-1");
return;
}
if (t.get(i).size() == 1) {
start = i;
}
}
vis = new boolean[n];
int[] w = new int[n-1];
dfs(t, start, false, w);
StringBuilder ans = new StringBuilder();
for (int i=0; i<n-1; i++) {
ans.append(w[i]).append(" ");
}
System.out.println(ans);
}
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
int[] u = new int[n-1];
int[] v = new int[n-1];
for (int i=0; i<n-1; i++) {
u[i] = in.nextInt()-1;
v[i] = in.nextInt()-1;
}
solve(n, u, v);
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
8d5e90dea6f4513653e5fe96f3213be1
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
public class C {
static Scanner sc;
static void solve() {
int n = sc.nextInt();
int[] degree = new int[n+1];
List<int[]>[] adj = new List[n+1];
for(int i = 0; i < n+1; i++) adj[i] = new ArrayList<>();
int[] weights = new int[n];
boolean df = false;
for(int i = 0; i < n-1; i++) {
int u = sc.nextInt(), v = sc.nextInt();
adj[u].add(new int[]{v, i});
adj[v].add(new int[]{u, i});
degree[u]++;
degree[v]++;
if((degree[u] > 2 || degree[v] > 2) && !df) {
System.out.println(-1);
df = true;
}
}
if(df) return;
int start = 0;
for(int i = 1; i < n+1; i++) {
if(degree[i] == 1) {
start = i;
break;
}
}
int prev = start;
int weight = 2;
for(int i = 0; i < n-1; i++) {
for(int[] p : adj[start]) {
if(p[0] != prev) {
weights[p[1]] = weight;
if(weight == 2) {
weight = 3;
}
else {
weight = 2;
}
prev = start;
start = p[0];
break;
}
}
}
for(int i = 0; i < n-1; i++) {
System.out.print(weights[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
solve();
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
0fc1bb4e46b0cd1987721dd2521127ee
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-->0){
solve(sc);
}
}
public static void solve(FastReader sc){
int n = sc.nextInt();
ArrayList<ArrayList<Edge>> graph = new ArrayList<ArrayList<Edge>>();
for(int i = 0;i<n;++i){
graph.add(new ArrayList<>());
}
for(int i = 0;i<n-1;++i){
int u = sc.nextInt();
int v = sc.nextInt();
u--;
v--;
graph.get(u).add(new Edge(v, i));
graph.get(v).add(new Edge(u, i));
}
int start = 0;
for(int i = 0;i<n;++i){
if(graph.get(i).size()>2){
out.println(-1);out.flush();return;
}else if(graph.get(i).size()==1){
start=i;
}
}
int val=2;
int [] wgt = new int[n-1];
int curr = graph.get(start).get(0).node;
wgt[graph.get(start).get(0).idx] = val;
val=5;
while(true){
ArrayList<Edge> list = graph.get(curr);
if(list.size()==1){
break;
}else{
for(Edge el : list){
if(wgt[el.idx]==0){
wgt[el.idx] = val;
val = 7-val;
curr = el.node;
}
}
}
}
for(int el : wgt){
out.print(el + " ");
}
out.println();
out.flush();
}
static class Edge {
int node;
int idx;
Edge(int src, int nbr) {
this.node = src;
this.idx = nbr;
}
}
/*
int [] arr = new int[n];
for(int i = 0;i<n;++i){
arr[i] = sc.nextInt();
}
*/
static void mysort(int[] arr) {
for(int i=0;i<arr.length;i++) {
int rand = (int) (Math.random() * arr.length);
int loc = arr[rand];
arr[rand] = arr[i];
arr[i] = loc;
}
Arrays.sort(arr);
}
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
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
e150f2ac5230bea303b1284dfe5c50b3
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class NotAssigning {
static class Edge {
int v, i;
public Edge(int v, int i) {
this.v = v; this.i = i;
}
}
static boolean[] edgeDone;
static int[] edgeLabel;
static ArrayList<ArrayList<Edge>> adj;
static void dfs(int v, int lastEdge) {
for(Edge e : adj.get(v)) {
if(edgeDone[e.i])
continue;
edgeDone[e.i] = true;
if(lastEdge == 2) {
edgeLabel[e.i] = 29;
dfs(e.v, 29);
} else {
edgeLabel[e.i] = 2;
dfs(e.v,2);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer st = new StringTokenizer(br.readLine());
int t = Integer.parseInt(st.nextToken());
for(int test = 0; test < t; test++) {
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
adj = new ArrayList<ArrayList<Edge>>();
for(int i = 0; i < n; i++)
adj.add(new ArrayList<Edge>());
for(int i = 0; i < n-1; i++) {
st = new StringTokenizer(br.readLine());
int v = Integer.parseInt(st.nextToken())-1;
int u = Integer.parseInt(st.nextToken())-1;
adj.get(v).add(new Edge(u,i));
adj.get(u).add(new Edge(v,i));
}
boolean possible = true;
int leaf = 0;
for(int i = 0; i < n; i++) {
if(adj.get(i).size() > 2) {
possible = false;
break;
}
if(adj.get(i).size() == 1)
leaf = i;
}
if(!possible) {
pw.println(-1);
continue;
}
edgeDone = new boolean[n-1];
edgeLabel = new int[n-1];
dfs(leaf,2);
for(int i = 0; i < n-2; i++)
pw.print(edgeLabel[i] + " ");
pw.print(edgeLabel[n-2]);
pw.println();
}
pw.close();
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
08284196c024db3e187961493eaedcc9
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class CF766 {
static FastScanner fs;
static FastWriter fw;
static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;
private static final int iMax = (int) (1e9), iMin = (int) (-1e9);
private static final long lMax = (int) (1e16), lMin = (int) (-1e16);
private static final int mod = (int) (1e9 + 7);
private static List<ArrayList<Integer>> adjList;
private static Pair[] data;
private static Map<Pair<Integer, Integer>, Integer> map;
public static void main(String[] args) throws IOException {
fs = new FastScanner();
fw = new FastWriter();
int t = 1;
t = fs.nextInt();
while (t-- > 0) {
solve();
}
fw.out.close();
}
private static void solve() {
int n = fs.nextInt();
data = new Pair[n - 1];
for (int i = 0; i < (n - 1); i++) {
int u = fs.nextInt() - 1, v = fs.nextInt() - 1;
int min = Math.min(u, v);
int max = Math.max(u, v);
data[i] = new Pair(min, max);
}
map = new HashMap<>();
adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (int i = 0; i < (n - 1); i++) {
addEdge(data[i].first, data[i].second);
}
for (int i = 0; i < n; i++) {
if (adjList.get(i).size() > 2) {
fw.out.println(-1);
return;
}
}
int lNode = lastNode(0, 0);
util(lNode, adjList.get(lNode).get(0), 2);
Integer[] result = new Integer[n - 1];
for (int i = 0; i < (n - 1); i++) {
result[i] = map.get(data[i]);
}
displayArr(result);
}
private static void addEdge(int u, int v) {
adjList.get(u).add(v);
adjList.get(v).add(u);
}
private static int lastNode(int curr, int prev) {
if (adjList.get(curr).size() == 1)
return curr;
if (adjList.get(curr).get(0) != prev)
return lastNode(adjList.get(curr).get(0), curr);
return lastNode(adjList.get(curr).get(1), curr);
}
private static void util(int parent, int curr, int num) {
int min = Math.min(parent, curr);
int max = Math.max(parent, curr);
map.put(new Pair<>(min, max), num);
if (adjList.get(curr).size() == 1)
return;
int next = (num == 2 ? 3 : 2);
if (adjList.get(curr).get(0) != parent)
util(curr, adjList.get(curr).get(0), next);
else
util(curr, adjList.get(curr).get(1), next);
}
private static class UnionFind {
private final int[] parent;
private final int[] rank;
UnionFind(int n) {
parent = new int[n + 5];
rank = new int[n + 5];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
private int find(int i) {
if (parent[i] == i)
return i;
return parent[i] = find(parent[i]);
}
private void union(int a, int b) {
a = find(a);
b = find(b);
if (a != b) {
if (rank[a] < rank[b]) {
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
if (rank[a] == rank[b])
rank[a]++;
}
}
}
private static int gcd(int a, int b) {
return (b == 0 ? a : gcd(b, a % b));
}
private static long pow(long a, long b) {
long result = 1;
while (b > 0) {
if ((b & 1L) == 1) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static int ceilDiv(int a, int b) {
return ((a + b - 1) / b);
}
private static List<Integer> primes(int n) {
boolean[] primeArr = new boolean[n + 5];
Arrays.fill(primeArr, true);
for (int i = 2; (i * i) <= n; i++) {
if (primeArr[i]) {
for (int j = i * i; j <= n; j += i) {
primeArr[j] = false;
}
}
}
List<Integer> primeList = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (primeArr[i])
primeList.add(i);
}
return primeList;
}
private static class Pair<U extends Integer, V extends Integer> {
private final U first;
private final V second;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
private Pair(U ff, V ss) {
this.first = ff;
this.second = ss;
}
}
private static <T> void randomizeArr(T[] arr, int n) {
Random r = new Random();
for (int i = (n - 1); i > 0; i--) {
int j = r.nextInt(i + 1);
swap(arr, i, j);
}
}
private static Integer[] readIntArray(int n) {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = fs.nextInt();
return arr;
}
private static List<Integer> readIntList(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(fs.nextInt());
return list;
}
private static <T> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static <T> void displayArr(T[] arr) {
for (T x : arr)
fw.out.print(x + " ");
fw.out.println();
}
private static <T> void displayList(List<T> list) {
for (T x : list)
fw.out.print(x + " ");
fw.out.println();
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner() throws IOException {
if (checkOnlineJudge)
this.br = new BufferedReader(new FileReader("src/input.txt"));
else
this.br = new BufferedReader(new InputStreamReader(System.in));
this.st = new StringTokenizer("");
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException err) {
err.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st.hasMoreTokens()) {
return st.nextToken("").trim();
}
try {
return br.readLine().trim();
} catch (IOException err) {
err.printStackTrace();
}
return "";
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
private static class FastWriter {
PrintWriter out;
FastWriter() throws IOException {
if (checkOnlineJudge)
out = new PrintWriter(new FileWriter("src/output.txt"));
else
out = new PrintWriter(System.out);
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
ea9ae576dacd2c8fc87b742da7bfb9e5
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static PrintWriter out;
static Kioken sc;
public static void main(String[] args) throws FileNotFoundException {
boolean t = true;
boolean f = false;
if (f) {
out = new PrintWriter("output.txt");
sc = new Kioken("input.txt");
} else {
out = new PrintWriter((System.out));
sc = new Kioken();
}
int tt = 1;
tt = sc.nextInt();
while (tt-- > 0) {
solve();
}
out.flush();
out.close();
}
static boolean flag = false;
static List<int[]>[] ans;
public static void dfs(int index, boolean[] visited, int parent, int val, List<Integer>[] ll){
if(visited[index]){
return;
}
List<Integer> l1 = ll[index];
// out.println(" == " + l1 + " " + index);
if(l1.size() > 2){
flag = true;
return;
}
visited[index] = true;
for(int k: l1){
if(visited[k] == false){
// out.println(visited[k] + " " + index + " " + k + " " + val);
ans[index].add(new int[]{k, val});
ans[k].add(new int[]{index, val});
dfs(k, visited, index, (val == 2) ? 5 : 2, ll);
}
}
}
public static void solve() {
int n = sc.nextInt();
List<Integer>[] ll = new List[n + 1];
// out.println(" mm " + n);
for (int i = 0; i <= n; i++) {
ll[i] = new ArrayList<>();
}
int[][] store = new int[n][2];
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
store[i][0] = u;
store[i][1] = v;
// out.println(" === " + u + " " + v);
int mm = Math.min(u, v);
int mx = Math.max(u, v);
// out.println(" u " + v + " " + u);
ll[mm].add(mx);
ll[mx].add(mm);
// ll[v].add(u)
}
int two = 2;
int prime = 5;
flag = false;
ans = new List[n+1];
int[] arr = new int[n + 1];
for(int i = 0; i <= n; i++){
ans[i] = new ArrayList<>();
}
boolean[] visited = new boolean[n+1];
List<Integer> one = ll[1];
if(one.size() > 2){
out.println(-1);
return;
}
// out.println(" -- " + one);
visited[1] = true;
for(int i = 0; i < one.size(); i++){
if(i == 0){
ans[1].add(new int[]{one.get(i), 2});
ans[one.get(i)].add(new int[]{1, 2});
dfs(one.get(i), visited, -1, 5, ll);
}else{
ans[1].add(new int[]{one.get(i), 5});
ans[one.get(i)].add(new int[]{1, 5});
dfs(one.get(i), visited, -1, 2, ll);
}
}
if (flag) {
out.println(-1);
return;
}
for(int i = 0; i < n-1; i++){
// out.println(" -- ");
int u = store[i][0];
int v = store[i][1];
// out.println(" uu " + u + " " + v);
if(u == 0 || v == 0){
continue;
}
int mm = Math.min(u, v);
int mx = Math.max(u, v);
List<int[]> vv = ans[mm];
// for(int[] ii:vv){
// out.println(Arrays.toString(ii));
// }
if(vv == null){
continue;
}
for(int[] j: vv){
if(j[0] == mx){
out.print(j[1]+ " ");
break;
}
}
}
out.println();
}
public static long gcd(long a, long b) {
while (b != 0) {
long rem = a % b;
a = b;
b = rem;
}
return a;
}
public static long leftShift(long a) {
return (long) Math.pow(2, a);
}
public static void reverse(int[] arr) {
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = temp;
}
return;
}
public static int lower_bound(ArrayList<Integer> ar, int k) {
int s = 0, e = ar.size();
while (s != e) {
int mid = s + e >> 1;
if (ar.get(mid) <= k) {
s = mid + 1;
} else {
e = mid;
}
}
return Math.abs(s) - 1;
}
public static int upper_bound(ArrayList<Integer> ar, int k) {
int s = 0;
int e = ar.size();
while (s != e) {
int mid = s + e >> 1;
if (ar.get(mid) < k) {
s = mid + 1;
} else {
e = mid;
}
}
if (s == ar.size()) {
return -1;
}
return s;
}
static class Kioken {
// FileInputStream br = new FileInputStream("input.txt");
BufferedReader br;
StringTokenizer st;
Kioken(String filename) {
try {
FileReader fr = new FileReader(filename);
br = new BufferedReader(fr);
st = new StringTokenizer("");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Kioken() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public String next() {
while (!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public boolean hasNext() {
String next = null;
try {
next = br.readLine();
} catch (Exception e) {
}
if (next == null || next.length() == 0) {
return false;
}
st = new StringTokenizer(next);
return true;
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
5871f3afcf7534cf9b451868642afeab
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class q3 {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// public static long mod = 1000000007;
public static void solve() throws Exception {
String[] parts = br.readLine().split(" ");
int n = Integer.parseInt(parts[0]);
int[][] arr = new int[n - 1][2];
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for(int i = 0;i < n;i++) graph.add(new ArrayList<>());
boolean flag = true;
int[] count = new int[n];
for(int i = 0;i < n - 1;i++){
parts = br.readLine().split(" ");
int u = Integer.parseInt(parts[0]) - 1;
int v = Integer.parseInt(parts[1]) - 1;
arr[i][0] = u;
arr[i][1] = v;
count[u]++;
count[v]++;
if(count[u] > 2 || count[v] > 2) flag = false;
graph.get(u).add(v);
graph.get(v).add(u);
}
if(!flag){
System.out.println(-1);
return;
}
int src = 0;
for(int i = 0;i < n;i++){
if(count[i] == 1){
src = i;
break;
}
}
HashMap<String,Integer> map = new HashMap<>();
Queue<int[]> que = new LinkedList<>();
boolean[] vis = new boolean[n];
vis[src] = true;
que.add(new int[]{graph.get(src).get(0),2});
vis[graph.get(src).get(0)] = true;
map.put(src + " " + graph.get(src).get(0),2);
while(que.size() > 0){
int[] rem = que.remove();
for(int nbr : graph.get(rem[0])){
if(vis[nbr]) continue;
vis[nbr] = true;
if(rem[1] == 2){
que.add(new int[]{nbr,5});
map.put(rem[0] + " " + nbr,5);
}else{
map.put(rem[0] + " " + nbr,2);
que.add(new int[]{nbr,2});
}
}
}
StringBuilder ans = new StringBuilder();
for(int[] val : arr){
String str = val[0] + " " + val[1];
// System.out.print(str);
if(map.containsKey(str)) ans.append(map.get(str)).append(" ");
else{
ans.append(map.get(val[1] + " " + val[0])).append(" ");
}
}
System.out.println(ans);
}
public static void main(String[] args) throws Exception {
seive(200000);
int tests = Integer.parseInt(br.readLine());
for (int test = 1; test <= tests; test++) {
solve();
}
}
public static ArrayList<Integer> primes;
public static void seive(int n){
primes = new ArrayList<>();
boolean[] arr = new boolean[n + 1];
Arrays.fill(arr,true);
for(int i = 2;i * i <= n;i++){
if(arr[i]) {
for (int j = i * i; j <= n; j += i) {
arr[j] = false;
}
}
}
for(int i = 3;i <= n - 10;i++) if(arr[i] && arr[i + 2]) primes.add(i);
}
// public static void sort(int[] arr){
// ArrayList<Integer> temp = new ArrayList<>();
// for(int val : arr) temp.add(val);
//
// Collections.sort(temp);
//
// for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i);
// }
// public static void sort(long[] arr){
// ArrayList<Long> temp = new ArrayList<>();
// for(long val : arr) temp.add(val);
//
// Collections.sort(temp);
//
// for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i);
// }
//
// public static long power(long a,long b,long mod){
// if(b == 0) return 1;
//
// long p = power(a,b / 2,mod);
// p = (p * p) % mod;
//
// if(b % 2 == 1) return (p * a) % mod;
// return p;
// }
// public static long modDivide(long a,long b,long mod){
// return ((a % mod) * (power(b,mod - 2,mod) % mod)) % mod;
// }
//
// public static int GCD(int a,int b){
// return b == 0 ? a : GCD(b,a % b);
// }
// public static long GCD(long a,long b){
// return b == 0 ? a : GCD(b,a % b);
// }
//
// public static int LCM(int a,int b){
// return a * b / GCD(a,b);
// }
// public static long LCM(long a,long b){
// return a * b / GCD(a,b);
// }
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 11
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
3ee9a2386d8c5cf01583d89dd7561f15
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class Round766C {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Round766C sol = new Round766C();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n) or matrix(n, 2) for graph edges, pairs, ...
int n;
int[][] e;
void getInput() {
n = in.nextInt();
e = in.nextMatrix(n-1, 2, -1);
}
void printOutput() {
if(ans == null)
out.println(-1);
else
out.printlnAns(ans);
}
static class Edge{
int u, v;
int id, weight;
public Edge(int u, int v, int id) {
this.u = u;
this.v = v;
this.id = id;
this.weight = -1;
}
}
Edge[][] neighbors;
int[] ans;
void solve(){
// // the only possible way is 2 and another prime
ans = null;
int[] deg = new int[n];
for(int i=0; i<e.length; i++) {
deg[e[i][0]]++;
deg[e[i][1]]++;
}
for(int i=0; i<n; i++)
if(deg[i] >= 3)
return;
int root = 0;
for(int i=0; i<n; i++)
if(deg[i] == 1) {
root = i;
break;
}
neighbors = new Edge[n][];
for(int i=0; i<n; i++)
neighbors[i] = new Edge[deg[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
Edge edge = new Edge(u, v, i);
neighbors[u][--deg[u]] = edge;
neighbors[v][--deg[v]] = edge;
}
dfs(root, -1, true);
ans = new int[e.length];
for(int i=0; i<n; i++)
for(Edge edge: neighbors[i])
ans[edge.id] = edge.weight;
}
void dfs(int curr, int parent, boolean parity) {
for(Edge edge: neighbors[curr]) {
int next = edge.u == curr? edge.v: edge.u;
if(next == parent)
continue;
edge.weight = parity? 2: 3;
dfs(next, curr, !parity);
}
}
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 17
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
a2202357960fe0a0c32662c929b4dd12
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
*
* @author eslam
*/
public class Solution {
// Beginning of the solution
static Kattio input = new Kattio();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>();
static ArrayList<LinkedList<String>> allprems = new ArrayList<>();
static ArrayList<Long> luc = new ArrayList<>();
static long mod = (long) (1e9 + 7);
static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}};
static long dp[][][];
static double cmp = 1e-7;
static final double pi = 3.14159265359;
static int[] ans;
public static void main(String[] args) throws IOException {
// Kattio input = new Kattio("input");
// BufferedWriter log = new BufferedWriter(new FileWriter(f));
int test = input.nextInt();
loop:
for (int co = 1; co <= test; co++) {
int n = input.nextInt();
ArrayList<Integer> a[] = new ArrayList[n + 1];
TreeMap<pair, Integer> edges = new TreeMap<>(cmpPair());
ans = new int[n - 1];
for (int i = 0; i <= n; i++) {
a[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
edges.put(new pair(Math.max(x, y), Math.min(x, y)), i);
}
for (int i = 0; i <= n; i++) {
if (a[i].size() > 2) {
log.write("-1\n");
continue loop;
}
}
dfs(1, a, new boolean[n + 1], true, edges);
for (int i = 0; i < n - 1; i++) {
log.write(ans[i] + " ");
}
log.write("\n");
}
log.flush();
}
static void dfs(int node, ArrayList<Integer> g[], boolean vi[], boolean ca, TreeMap<pair, Integer> edges) {
vi[node] = true;
for (Integer ch : g[node]) {
if (!vi[ch]) {
if (ca) {
ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 2;
} else {
ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 5;
}
dfs(ch, g, vi, !ca, edges);
ca = !ca;
}
}
}
static long f(long x) {
return (long) ((x * (x + 1) / 2) % mod);
}
static long Sub(long x, long y) {
long z = x - y;
if (z < 0) {
z += mod;
}
return z;
}
static long add(long a, long b) {
a += b;
if (a >= mod) {
a -= mod;
}
return a;
}
static long mul(long a, long b) {
return (long) ((long) a * b % mod);
}
static long powlog(long base, long power) {
if (power == 0) {
return 1;
}
long x = powlog(base, power / 2);
x = mul(x, x);
if ((power & 1) == 1) {
x = mul(x, base);
}
return x;
}
static long modinv(long x) {
return fast_pow(x, mod - 2, mod);
}
static long Div(long x, long y) {
return mul(x, modinv(y));
}
static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) {
vi[r][c] = true;
for (int i = 0; i < 4; i++) {
int nr = grid[0][i] + r;
int nc = grid[1][i] + c;
if (isValid(nr, nc, a.length, a[0].length)) {
if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) {
floodFill(nr, nc, a, vi, w, d);
}
}
}
}
static boolean isdigit(char ch) {
return ch >= '0' && ch <= '9';
}
static boolean lochar(char ch) {
return ch >= 'a' && ch <= 'z';
}
static boolean cachar(char ch) {
return ch >= 'A' && ch <= 'Z';
}
static class Pa {
long x;
long y;
public Pa(long x, long y) {
this.x = x;
this.y = y;
}
}
static long sqrt(long v) {
long max = (long) 4e9;
long min = 0;
long ans = 0;
while (max >= min) {
long mid = (max + min) / 2;
if (mid * mid > v) {
max = mid - 1;
} else {
ans = mid;
min = mid + 1;
}
}
return ans;
}
static long cbrt(long v) {
long max = (long) 3e6;
long min = 0;
long ans = 0;
while (max >= min) {
long mid = (max + min) / 2;
if (mid * mid > v) {
max = mid - 1;
} else {
ans = mid;
min = mid + 1;
}
}
return ans;
}
static void prefixSum2D(long arr[][]) {
for (int i = 0; i < arr.length; i++) {
prefixSum(arr[i]);
}
for (int i = 0; i < arr[0].length; i++) {
for (int j = 1; j < arr.length; j++) {
arr[j][i] += arr[j - 1][i];
}
}
}
public static long baseToDecimal(String w, long base) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(base, l);
r = r + x;
l++;
}
return r;
}
static int bs(int v, ArrayList<Integer> a) {
int max = a.size() - 1;
int min = 0;
int ans = 0;
while (max >= min) {
int mid = (max + min) / 2;
if (a.get(mid) >= v) {
ans = a.size() - mid;
max = mid - 1;
} else {
min = mid + 1;
}
}
return ans;
}
static Comparator<tri> cmpTri() {
Comparator<tri> c = new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.z > o2.z) {
return 1;
} else if (o1.z < o2.z) {
return -1;
} else {
return 0;
}
}
}
}
};
return c;
}
static Comparator<pair> cmpPair2() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.x > o2.x) {
return -1;
} else if (o1.x < o2.x) {
return 1;
} else {
return 0;
}
}
}
};
return c;
}
static Comparator<pair> cmpPair() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.x > o2.x) {
return -1;
} else if (o1.x < o2.x) {
return 1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
}
};
return c;
}
static class rec {
long x1;
long x2;
long y1;
long y2;
public rec(long x1, long y1, long x2, long y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public long getArea() {
return (x2 - x1) * (y2 - y1);
}
}
static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) {
return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1];
}
public static int[][] bfs(int i, int j, String w[]) {
Queue<pair> q = new ArrayDeque<>();
q.add(new pair(i, j));
int dis[][] = new int[w.length][w[0].length()];
for (int k = 0; k < w.length; k++) {
Arrays.fill(dis[k], -1);
}
dis[i][j] = 0;
while (!q.isEmpty()) {
pair p = q.poll();
int cost = dis[p.x][p.y];
for (int k = 0; k < 4; k++) {
int nx = p.x + grid[0][k];
int ny = p.y + grid[1][k];
if (isValid(nx, ny, w.length, w[0].length())) {
if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') {
q.add(new pair(nx, ny));
dis[nx][ny] = cost + 1;
}
}
}
}
return dis;
}
public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException {
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
while (q-- > 0) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
}
}
public static boolean isValid(int i, int j, int n, int m) {
return (i > -1 && i < n) && (j > -1 && j < m);
}
// present in the left and right indices
public static int[] swap(int data[], int left, int right) {
// Swap the data
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// Return the updated array
return data;
}
// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static int[] reverse(int data[], int left, int right) {
// Reverse the sub-array
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
// Return the updated array
return data;
}
// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(int data[]) {
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.length <= 1) {
return false;
}
int last = data.length - 2;
// find the longest non-increasing suffix
// and find the pivot
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
// If there is no increasing pair
// there is no higher order permutation
if (last < 0) {
return false;
}
int nextGreater = data.length - 1;
// Find the rightmost successor to the pivot
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
// Swap the successor and the pivot
data = swap(data, nextGreater, last);
// Reverse the suffix
data = reverse(data, last + 1, data.length - 1);
// Return true as the next_permutation is done
return true;
}
// public static pair[] dijkstra(int node, ArrayList<pair> a[]) {
// PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() {
// @Override
// public int compare(tri o1, tri o2) {
// if (o1.y > o2.y) {
// return 1;
// } else if (o1.y < o2.y) {
// return -1;
// } else {
// return 0;
// }
// }
// });
// q.add(new tri(node, 0, -1));
// pair distance[] = new pair[a.length];
// while (!q.isEmpty()) {
// tri p = q.poll();
// int cost = p.y;
// if (distance[p.x] != null) {
// continue;
// }
// distance[p.x] = new pair(p.z, cost);
// ArrayList<pair> nodes = a[p.x];
// for (pair node1 : nodes) {
// if (distance[node1.x] == null) {
// tri pa = new tri(node1.x, cost + node1.y, p.x);
// q.add(pa);
// }
// }
// }
// return distance;
// }
public static String revs(String w) {
String ans = "";
for (int i = w.length() - 1; i > -1; i--) {
ans += w.charAt(i);
}
return ans;
}
public static boolean isPalindrome(String w) {
for (int i = 0; i < w.length() / 2; i++) {
if (w.charAt(i) != w.charAt(w.length() - i - 1)) {
return false;
}
}
return true;
}
public static void getPowerSet(Queue<Integer> a) {
int n = a.poll();
if (!a.isEmpty()) {
getPowerSet(a);
}
int s = powerSet.size();
for (int i = 0; i < s; i++) {
ArrayList<Integer> ne = new ArrayList<>();
ne.add(n);
for (int j = 0; j < powerSet.get(i).size(); j++) {
ne.add(powerSet.get(i).get(j));
}
powerSet.add(ne);
}
ArrayList<Integer> p = new ArrayList<>();
p.add(n);
powerSet.add(p);
}
public static int getlo(int va) {
int v = 1;
while (v <= va) {
if ((va&v) != 0) {
return v;
}
v <<= 1;
}
return 0;
}
static long fast_pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a) % mod;
p /= 2;
} else {
res = (res * a) % mod;
p--;
}
}
return res;
}
public static int countPrimeInRange(int n, boolean isPrime[]) {
int cnt = 0;
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * 2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
cnt++;
}
}
return cnt;
}
public static void create(long num) {
luc.add(num);
if (num > power(10, 9)) {
return;
}
create(num * 10 + 4);
create(num * 10 + 7);
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static long round(long a, long b) {
if (a < 0) {
return (a - b / 2) / b;
}
return (a + b / 2) / b;
}
public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) {
if (l.size() == st.size()) {
allprems.add(l);
}
for (int i = 0; i < st.size(); i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<String> nl = new LinkedList<>();
for (String x : l) {
nl.add(x);
}
nl.add(st.get(i));
allPremutationsst(nl, visited, st);
visited[i] = false;
}
}
}
public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) {
if (l.size() == a.length) {
allprem.add(l);
}
for (int i = 0; i < a.length; i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<Integer> nl = new LinkedList<>();
for (Integer x : l) {
nl.add(x);
}
nl.add(a[i]);
allPremutations(nl, visited, a);
visited[i] = false;
}
}
}
public static int binarySearch(long[] a, long value) {
int l = 0;
int r = a.length - 1;
while (l <= r) {
int m = (l + r) / 2;
if (a[m] == value) {
return m;
} else if (a[m] > value) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
}
public static void reverse(int l, int r, char ch[]) {
for (int i = 0; i < r / 2; i++) {
char c = ch[i];
ch[i] = ch[r - i - 1];
ch[r - i - 1] = c;
}
}
public static long logK(long v, long k) {
int ans = 0;
while (v > 1) {
ans++;
v /= k;
}
return ans;
}
public static long power(long a, long p) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a);
p /= 2;
} else {
res = (res * a);
p--;
}
}
return res;
}
public static long get(long max, long x) {
if (x == 1) {
return max;
}
int cnt = 0;
while (max > 0) {
cnt++;
max /= x;
}
return cnt;
}
public static int numOF0(long v) {
long x = 1;
int cnt = 0;
while (x <= v) {
if ((x & v) == 0) {
cnt++;
}
x <<= 1;
}
return cnt;
}
public static int log2(double n) {
int cnt = 0;
while (n > 1) {
n /= 2;
cnt++;
}
return cnt;
}
public static int[] bfs(int node, ArrayList<Integer> a[]) {
Queue<Integer> q = new LinkedList<>();
q.add(node);
int distances[] = new int[a.length];
Arrays.fill(distances, -1);
distances[node] = 0;
while (!q.isEmpty()) {
int parent = q.poll();
ArrayList<Integer> nodes = a[parent];
int cost = distances[parent];
for (Integer node1 : nodes) {
if (distances[node1] == -1) {
q.add(node1);
distances[node1] = cost + 1;
}
}
}
return distances;
}
public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) {
boolean ca = true;
while (n % 2 == 0) {
if (ca) {
if (h.get(2) == null) {
h.put(2, new ArrayList<>());
}
h.get(2).add(ind);
ca = false;
}
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
ca = true;
while (n % i == 0) {
if (ca) {
if (h.get(i) == null) {
h.put(i, new ArrayList<>());
}
h.get(i).add(ind);
ca = false;
}
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
if (h.get(n) == null) {
h.put(n, new ArrayList<>());
}
h.get(n).add(ind);
}
}
// end of solution
public static BigInteger ff(long n) {
if (n <= 1) {
return BigInteger.ONE;
}
long t = n - 1;
BigInteger b = new BigInteger(t + "");
BigInteger ans = new BigInteger(n + "");
while (t > 1) {
ans = ans.multiply(b);
b = b.subtract(BigInteger.ONE);
t--;
}
return ans;
}
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n = mod((mod(n, mod) * mod(t, mod)), mod);
t--;
}
return n;
}
public static long rev(long n) {
long t = n;
long ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y;
long z;
public tri(int x, int y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (long i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(long[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(long[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalAnyBase(long n, long base) {
String w = "";
while (n > 0) {
w = n % base + w;
n /= base;
}
return w;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void print(long[] a) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class gepair {
long x;
long y;
public gepair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pair {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pai {
long x;
int y;
public pai(long x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(int a, int b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName));
}
// returns null if no more input
String nextLine() {
String str = "";
try {
str = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(r.readLine());
}
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 17
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
40c206f1ea47a3653af50e95fdecf023
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
public class K {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
while (t-- > 0) {
int n = s.nextInt();
List<Edge>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = s.nextInt();
int v = s.nextInt();
u -= 1;
v -= 1;
adj[u].add(new Edge(v, i));
adj[v].add(new Edge(u, i));
}
int start = 0;
boolean flag = false;
for (int i = 0; i < n; i++) {
if (adj[i].size() > 2) {
flag = true;
break;
} else if (adj[i].size() == 1) {
start = i;
}
}
if (flag) {
System.out.println("-1");
continue;
}
int[] weight = new int[n - 1];
int prev = -1, cur = start, curw = 2;
while (true) {
List<Edge> l = adj[cur];
Edge next = l.get(0);
if (next.to == prev) {
if (l.size() == 1) break;
else next = l.get(1);
}
weight[next.index] = curw;
prev = cur;
cur = next.to;
curw = 5 - curw;
}
StringBuilder sb=new StringBuilder();
for(int i=0;i<weight.length;i++)
{
sb.append(weight[i]+" ");
}
System.out.println(sb);
}
}
}
class Edge {
int to;
int index;
public Edge(int to, int index) {
this.to = to;
this.index = index;
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 17
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
3c677ff120be1ef0409f267d2e08fc20
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class CF1627C {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8);
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
int n = scanner.nextInt();
int[][] uv = new int[n - 1][2];
for (int j = 0; j < n - 1; j++) {
uv[j][0] = scanner.nextInt();
uv[j][1] = scanner.nextInt();
}
System.out.println(solve(n, uv));
}
}
private static String solve(int n, int[][] uv) {
// 无向图
Map<Integer, Map<Integer, Integer>> adj = new HashMap<>();
for (int[] tuple : uv) {
int u = tuple[0];
int v = tuple[1];
adj.computeIfAbsent(u, key -> new HashMap<>()).put(v, -1);
adj.computeIfAbsent(v, key -> new HashMap<>()).put(u, -1);
}
// 不存在三个质数,任意两个之和也是质数
for (int i = 1; i <= n; i++) {
if (adj.getOrDefault(i, new HashMap<>()).size() > 2) {
return "-1";
}
}
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
// 设 (u,v) 权重为 2
int u0 = uv[0][0];
int v0 = uv[0][1];
adj.get(u0).put(v0, 2);
adj.get(v0).put(u0, 2);
queue.add(u0);
queue.add(v0);
visited.add(u0);
visited.add(v0);
boolean is2 = true;
while (!queue.isEmpty()) {
is2 = !is2;
int size = queue.size();
for (int i = 0; i < size; i++) {
int cur = queue.remove();
for (int next : adj.get(cur).keySet()) {
if (!visited.contains(next)) {
visited.add(next);
adj.get(cur).put(next, is2 ? 2 : 3);
adj.get(next).put(cur, is2 ? 2 : 3);
queue.add(next);
}
}
}
}
List<String> resList = new ArrayList<>();
for (int[] tuple : uv) {
int u = tuple[0];
int v = tuple[1];
resList.add(String.valueOf(adj.get(u).get(v)));
}
return String.join(" ", resList);
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 17
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
06455041de6175fe9dffade4a35981d1
|
train_109.jsonl
|
1642257300
|
You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime. Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class codeforces1627C {
public static void main(String[] args) throws IOException {
FastReader in = new FastReader();
int numCases = in.nextInt();
StringBuilder ans = new StringBuilder();
while (numCases-->0)
{
int n = in.nextInt();
var adj = new ArrayList<ArrayList<Edge>>();
int [] deg = new int[n];
for (int i = 0; i<n;i++)
{
adj.add(new ArrayList<>());
}
for (int i = 0; i<n-1;i++)
{
int a = in.nextInt()-1;
int b = in.nextInt()-1;
adj.get(a).add(new Edge(b,i));
adj.get(b).add(new Edge(a,i));
deg[a]++;
deg[b]++;
}
boolean ok = true;
int start = -1;
for (int i = 0; i<n;i++)
{
if (deg[i]>2) ok = false;
else if (deg[i]==1) start = i;
}
if (ok)
{
int [] w = new int[n-1];
int prev = -1;
int curr = start;
int currW = 3;
boolean bo = true;
while (bo)
{
var edges = adj.get(curr);
var next = edges.get(0);
if (next.a==prev)
{
if (edges.size()==1) break;
else next = edges.get(1);
}
w[next.b] = currW;
prev = curr;
curr = next.a;
currW = 5-currW;
}
for (int i = 0; i<n-1;i++)
{
ans.append(w[i]+" ");
}
ans.append("\n");
}
else ans.append("-1\n");
}
System.out.println(ans);
}
static class Edge
{
int a;
int b;
Edge(int a, int b)
{
this.a = a;
this.b = b;
}
}
static class FastReader {
StringTokenizer st;
BufferedReader br;
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 s = "";
while (st == null || st.hasMoreElements()) {
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return s;
}
}
}
|
Java
|
["3\n2\n1 2\n4\n1 3\n4 3\n2 1\n7\n1 2\n1 3\n3 4\n3 5\n6 2\n7 2"]
|
1.5 seconds
|
["17\n2 5 11\n-1"]
|
NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime. The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.
|
Java 17
|
standard input
|
[
"constructive algorithms",
"dfs and similar",
"number theory",
"trees"
] |
0639fbeb3a5be67a4c0beeffe8f5d43b
|
The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
| 1,400
|
For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.
|
standard output
| |
PASSED
|
897e7216252ce38cdf60d06dcb52b1d7
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
// package c1627;
import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
//
// Codeforces Round #766 (Div. 2) 2022-01-15 06:35
// D. Not Adding
// https://codeforces.com/contest/1627/problem/D
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You have an array a_1, a_2, ..., a_n consisting of n integers. You are allowed to perform the
// following operation on it:
// * Choose two elements from the array a_i and a_j (i != j) such that \gcd(a_i, a_j) is not
// present in the array, and add \gcd(a_i, a_j) to the end of the array. Here \gcd(x, y) denotes
// <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">greatest common divisor
// (GCD)</a> of integers x and y.
//
// Note that the array changes after each operation, and the subsequent operations are performed on
// the new array.
//
// What is the number of times you can perform the operation on the array?
//
// Input
//
// The first line consists of a single integer n (2 <= n <= 10^6).
//
// The second line consists of n integers a_1, a_2, ..., a_n (1 <= a_i <= 10^6). All a_i are .
//
// Output
//
// Output a single line containing one integer-- the maximum number of times the operation can be
// performed on the given array.
//
// Example
/*
input:
5
4 20 1 25 30
output:
3
input:
3
6 10 15
output:
4
*/
// Note
//
// In the first example, one of the ways to perform maximum number of operations on the array is:
// * Pick i = 1, j= 5 and add \gcd(a_1, a_5) = \gcd(4, 30) = 2 to the array.
// * Pick i = 2, j= 4 and add \gcd(a_2, a_4) = \gcd(20, 25) = 5 to the array.
// * Pick i = 2, j= 5 and add \gcd(a_2, a_5) = \gcd(20, 30) = 10 to the array.
//
// It can be proved that there is no way to perform more than 3 operations on the original array.
//
// In the second example one can add 3, then 1, then 5, and 2.
//
public class C1627D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static int solve(int[] a) {
int n = a.length;
if (n == 1000000) {
// Based on the problem, all number are unique so whole [1,10^6] appear, nothing to add.
return 0;
}
int max = a[0];
// Normalize by dividing global GCD
int global = a[0];
for (int v : a) {
max = Math.max(max, v);
global = gcd(global, v);
}
if (global > 1) {
for (int i = 0; i < n; i++) {
a[i] /= global;
}
max /= global;
}
// Now the global common divisor is 1
boolean[] used = new boolean[max+1];
for (int v : a) {
used[v] = true;
}
int ans = 0;
if (global == 1 && !used[1]) {
used[1] = true;
ans++;
}
/* The alternative approach that leads to TLE
// gcds[w] is the GCD of all multiples of w in a
int[] gcds = new int[max+1];
for (int v : a) {
// Note that it takes 1500 ms to get factors for all numbers in [1,1000000].
List<Integer> factors = getFactors(v);
// System.out.format("%8s -> %s\n", v, common.Utils.traceListInt(factors));
for (int w : factors) {
// v is a multiple of w in input array
if (w != 1 && !used[w]) {
gcds[w] = gcd(v, gcds[w]);
myAssert(gcds[w] != 0);
// Collect new number as we proceed to be efficient
if (!used[gcds[w]]) {
used[gcds[w]] = true;
ans++;
}
}
}
}
*/
// For each v in [2, max] not yet used, compute the GCD of all its multiples.
// If such GCD is not used, add it.
// Note that check for v * 2, v * 3, ... in used[] is twice faster than the
// alternative getFactors() for all number in a.
for (int v = 2; v <= max; v++) {
if (used[v]) {
continue;
}
int g = 0;
int w = v + v;
while (w <= max) {
if (used[w]) {
g = gcd(w, g);
if (g == v) {
break;
}
}
w += v;
}
if (g != 0 && !used[g]) {
ans++;
used[g] = true;
}
}
return ans;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
final static List<Integer> PRIMES = Arrays.asList(
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,
127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,
251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,
389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,
541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,
677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,
839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997);
public static List<int[]> getPrimeFactorization(int k) {
List<int[]> ans = new ArrayList<>();
int r = (int) Math.sqrt(k) + 1;
for (int p : PRIMES) {
if (p > r) {
break;
}
int exp = 0;
while (k % p == 0) {
exp++;
k /= p;
}
if (exp > 0) {
ans.add(new int[] {p, exp});
}
}
if (k != 1) {
ans.add(new int[] {k, 1});
}
return ans;
}
// Gets all factors based on prime factorization
public static List<Integer> getFactors(List<int[]> pes) {
List<Integer> factors = new ArrayList<>();
factors.add(1);
for (int[] v : pes) {
int p = v[0];
int w = 1;
int size = factors.size();
for (int e = 1; e <= v[1]; e++) {
w *= p;
for (int i = 0; i < size; i++) {
factors.add(factors.get(i) * w);
}
}
}
Collections.sort(factors);
return factors;
}
public static List<Integer> getFactors(int k) {
return getFactors(getPrimeFactorization(k));
}
static int solveNaive(int[] a) {
int max = a[0];
for (int v : a) {
max = Math.max(max, v);
}
boolean[] used = new boolean[max + 1];
for (int v : a) {
used[v] = true;
}
List<Integer> nums = new ArrayList<>();
for (int v : a) {
nums.add(v);
}
List<Integer> added = new ArrayList<>();
int ans = 0;
while (true) {
List<Integer> next = new ArrayList<>();
for (int i = 0; i < nums.size(); i++) {
for (int j = i+1; j < nums.size(); j++) {
int w = gcd(nums.get(i), nums.get(j));
if (!used[w]) {
// System.out.format(" %6d <- %d %d\n", w, nums.get(i), nums.get(j));
next.add(w);
used[w] = true;
}
}
}
if (next.isEmpty()) {
break;
}
ans += next.size();
nums.addAll(next);
added.addAll(next);
}
Collections.sort(added);
// System.out.format("Added %s\n", Utils.traceListInt(added));
return ans;
}
static void doTest() {
long t0 = System.currentTimeMillis();
myAssert(solve(new int[] {6, 10, 15}) == 4);
myAssert(solve(new int[] {4,20,1,25,30}) == 3);
myAssert(solve(new int[] {406284, 209708, 105841, 629228, 479827, 607173}) == 3);
for (int t = 0; t < 10; t++) {
int n = 990000;
Set<Integer> nums = new HashSet<>();
while (nums.size() < n) {
nums.add(1 + RAND.nextInt(1000000));
}
int[] arr = new int[n];
int idx = 0;
for (int v : nums) {
arr[idx++] = v;
}
// System.out.format("arr: %s\n", Arrays.toString(arr));
int ans = solve(arr);
System.out.println(ans);
if (n <= 1000) {
int exp = solveNaive(arr);
if (exp != ans) {
System.out.format("Expected " + exp);
System.exit(0);
}
}
}
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
// doTest();
Scanner in = getInputScanner();
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int ans = solve(a);
System.out.println(ans);
in.close();
}
static Scanner getInputScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName();
final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in");
return fin.exists() ? new Scanner(fin) : new Scanner(System.in);
} catch (Exception e) {
return new Scanner(System.in);
}
}
static String trace(int[] a) {
StringBuilder sb = new StringBuilder();
for (int v : a) {
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(v);
}
return sb.toString();
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9bcbf157721404282573133e86913e81
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
// package c1627;
import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
//
// Codeforces Round #766 (Div. 2) 2022-01-15 06:35
// D. Not Adding
// https://codeforces.com/contest/1627/problem/D
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You have an array a_1, a_2, ..., a_n consisting of n integers. You are allowed to perform the
// following operation on it:
// * Choose two elements from the array a_i and a_j (i != j) such that \gcd(a_i, a_j) is not
// present in the array, and add \gcd(a_i, a_j) to the end of the array. Here \gcd(x, y) denotes
// <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">greatest common divisor
// (GCD)</a> of integers x and y.
//
// Note that the array changes after each operation, and the subsequent operations are performed on
// the new array.
//
// What is the number of times you can perform the operation on the array?
//
// Input
//
// The first line consists of a single integer n (2 <= n <= 10^6).
//
// The second line consists of n integers a_1, a_2, ..., a_n (1 <= a_i <= 10^6). All a_i are .
//
// Output
//
// Output a single line containing one integer-- the maximum number of times the operation can be
// performed on the given array.
//
// Example
/*
input:
5
4 20 1 25 30
output:
3
input:
3
6 10 15
output:
4
*/
// Note
//
// In the first example, one of the ways to perform maximum number of operations on the array is:
// * Pick i = 1, j= 5 and add \gcd(a_1, a_5) = \gcd(4, 30) = 2 to the array.
// * Pick i = 2, j= 4 and add \gcd(a_2, a_4) = \gcd(20, 25) = 5 to the array.
// * Pick i = 2, j= 5 and add \gcd(a_2, a_5) = \gcd(20, 30) = 10 to the array.
//
// It can be proved that there is no way to perform more than 3 operations on the original array.
//
// In the second example one can add 3, then 1, then 5, and 2.
//
public class C1627D {
static final int MOD = 998244353;
static final Random RAND = new Random();
final static List<Integer> PRIMES = Arrays.asList(
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,
127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,
251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,
389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,
541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,
677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,
839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997);
static int solve(int[] a) {
int n = a.length;
if (n == 1000000) {
// Based on the problem, all number are unique so whole [1,10^6] appear, nothing to add.
return 0;
}
int max = a[0];
// Normalize by dividing global GCD
int global = a[0];
for (int v : a) {
max = Math.max(max, v);
global = gcd(global, v);
}
if (global > 1) {
for (int i = 0; i < n; i++) {
a[i] /= global;
}
max /= global;
}
// Now the global common divisor is 1
boolean[] used = new boolean[max+1];
for (int v : a) {
used[v] = true;
}
int ans = 0;
if (global == 1 && !used[1]) {
used[1] = true;
ans++;
}
/*
// gcds[w] is the GCD of all multiples of w in a
int[] gcds = new int[max+1];
for (int v : a) {
// Note that it takes 1500 ms to get factors for all numbers in [1,1000000].
// It is about half the time as compare to the naive iteration over all numbers in a.
List<Integer> factors = getFactors(v);
// System.out.format("%8s -> %s\n", v, common.Utils.traceListInt(factors));
for (int w : factors) {
// v is a multiple of w in input array
if (w != 1 && !used[w]) {
gcds[w] = gcd(v, gcds[w]);
myAssert(gcds[w] != 0);
// Collect new number as we proceed to be efficient
if (!used[gcds[w]]) {
used[gcds[w]] = true;
ans++;
}
}
}
}
*/
for (int v = 2; v <= max; v++) {
if (used[v]) {
continue;
}
int g = 0;
int w = v + v;
while (w <= max) {
if (used[w]) {
g = gcd(w, g);
if (g == v) {
break;
}
}
w += v;
}
if (g != 0 && !used[g]) {
ans++;
used[g] = true;
}
}
return ans;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static List<int[]> getPrimeFactorization(int k) {
List<int[]> ans = new ArrayList<>();
int r = (int) Math.sqrt(k) + 1;
for (int p : PRIMES) {
if (p > r) {
break;
}
int exp = 0;
while (k % p == 0) {
exp++;
k /= p;
}
if (exp > 0) {
ans.add(new int[] {p, exp});
}
}
if (k != 1) {
ans.add(new int[] {k, 1});
}
return ans;
}
// Gets all factors based on prime factorization
public static List<Integer> getFactors(List<int[]> pes) {
List<Integer> factors = new ArrayList<>();
factors.add(1);
for (int[] v : pes) {
int p = v[0];
int w = 1;
int size = factors.size();
for (int e = 1; e <= v[1]; e++) {
w *= p;
for (int i = 0; i < size; i++) {
factors.add(factors.get(i) * w);
}
}
}
Collections.sort(factors);
return factors;
}
public static List<Integer> getFactors(int k) {
return getFactors(getPrimeFactorization(k));
}
static int solveNaive(int[] a) {
int max = a[0];
for (int v : a) {
max = Math.max(max, v);
}
boolean[] used = new boolean[max + 1];
for (int v : a) {
used[v] = true;
}
List<Integer> nums = new ArrayList<>();
for (int v : a) {
nums.add(v);
}
List<Integer> added = new ArrayList<>();
int ans = 0;
while (true) {
List<Integer> next = new ArrayList<>();
for (int i = 0; i < nums.size(); i++) {
for (int j = i+1; j < nums.size(); j++) {
int w = gcd(nums.get(i), nums.get(j));
if (!used[w]) {
// System.out.format(" %6d <- %d %d\n", w, nums.get(i), nums.get(j));
next.add(w);
used[w] = true;
}
}
}
if (next.isEmpty()) {
break;
}
ans += next.size();
nums.addAll(next);
added.addAll(next);
}
Collections.sort(added);
// System.out.format("Added %s\n", Utils.traceListInt(added));
return ans;
}
static void doTest() {
long t0 = System.currentTimeMillis();
// System.out.println(solve(new int[] {6, 10, 15}));
// System.out.println(solve(new int[] {4,20,1,25,30}));
// System.out.println(solve(new int[] {406284, 209708, 105841, 629228, 479827, 607173}));
for (int t = 0; t < 10; t++) {
int n = 300000;
Set<Integer> nums = new HashSet<>();
while (nums.size() < n) {
nums.add(1 + RAND.nextInt(1000000));
}
int[] arr = new int[n];
int idx = 0;
for (int v : nums) {
arr[idx++] = v;
}
// System.out.format("arr: %s\n", Arrays.toString(arr));
int ans = solve(arr);
System.out.println(ans);
if (n <= 1000) {
int exp = solveNaive(arr);
if (exp != ans) {
System.out.format("Expected " + exp);
System.exit(0);
}
}
}
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
// doTest();
Scanner in = getInputScanner();
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int ans = solve(a);
System.out.println(ans);
in.close();
}
static Scanner getInputScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName();
final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in");
return fin.exists() ? new Scanner(fin) : new Scanner(System.in);
} catch (Exception e) {
return new Scanner(System.in);
}
}
static String trace(int[] a) {
StringBuilder sb = new StringBuilder();
for (int v : a) {
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(v);
}
return sb.toString();
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
47e619e229eb36d5b48b0f8f98677178
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Solution{
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static int max = (int)1e6+1;
public static void main(String[] args){
boolean[] used = new boolean[max];
FastReader in = new FastReader();
int n = in.nextInt();
for(int i=0;i<n;i++){
int num = in.nextInt();
used[num] = true;
}
int ans = 0;
for(int i=max-1;i>=1;i--){
if(used[i]) continue;
int g = 0;
for(int j=i;j<max;j+=i){
if(used[j]){
g = gcd(g,j);
}
}
if(g==i){
used[i]= true;
ans++;
}
}
System.out.println(ans);
}
public static int gcd(int a,int b){
return a==0? b: gcd(b%a,a);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
0a7c579b8787b5cfb6163bd78dc701f5
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
public static int gcd(int x, int y) {
int temp;
while (y > 0) {
x %= y;
temp = x;
x = y;
y = temp;
}
return x;
}
public static void main(String[] args) {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i) a[i] = sc.nextInt();
int max_a = 0;
for (int i = 0; i < n; ++i) max_a = Math.max(max_a, a[i]);
boolean[] reach = new boolean[max_a + 1];
for (int i = 0; i < n; ++i) reach[a[i]] = true;
for (int i = max_a; i >= 1; --i) {
if (reach[i]) continue;
int g = 0;
for (int divisor = i + i; divisor <= max_a; divisor += i) {
if (reach[divisor]) g = gcd(g, divisor);
}
if (g == i) reach[i] = true;
}
int allReach = 0;
for (int i = 0; i <= max_a; ++i) if (reach[i]) allReach++;
out.println(allReach - n);
out.flush();
}
static class Scanner {
BufferedReader in;
StringTokenizer st;
public Scanner() {
this.in = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(FileReader f) {
this.in = new BufferedReader(f);
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public void close() throws IOException {
in.close();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
26839a9a0a526712262f2785ad148e99
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DNotAdding solver = new DNotAdding();
solver.solve(1, in, out);
out.close();
}
static class DNotAdding {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
boolean[] vis = new boolean[1000001];
for (int a : arr) {
vis[a] = true;
}
long count = 0;
for (int i = (1000000) / 2; i >= 2; i--) {
int g = 0;
if (vis[i]) continue;
for (int j = i * 2; j <= 1000000; j += i) {
if (vis[j]) {
g = (gcd(g, j / i));
}
}
if (g == 1) {
count++;
vis[i] = true;
}
}
if (!vis[1]) count++;
out.println(count);
}
int gcd(int a, int b) {
return b == 0 ? (a < 0 ? -a : a) : gcd(b, a % b);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
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(long i) {
writer.println(i);
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
c363de60b2d7f54d77f2dc27fe6a40ac
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DNotAdding solver = new DNotAdding();
solver.solve(1, in, out);
out.close();
}
static class DNotAdding {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] arr = in.nextIntArray(n);
boolean[] vis = new boolean[1000001];
for (int a : arr) {
vis[a] = true;
}
long count = 0;
for (int i = (1000000) / 2; i >= 2; i--) {
int g = 0;
if (vis[i]) continue;
for (int j = i * 2; j <= 1000000; j += i) {
if (vis[j]) {
g = (gcd(g, j / i));
}
}
if (g == 1) {
count++;
vis[i] = true;
}
}
if (!vis[1]) count++;
out.println(count);
}
int gcd(int a, int b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0)
return b;
return gcd(b % a, a);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int nextInt() {
return Integer.parseInt(next());
}
}
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(long i) {
writer.println(i);
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
29b4a0adfada387156059c637691b145
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int maks = 0;
int present[] = new int[1000001];
for (int j = 0; j < n; j++) {
int a = scan.nextInt();
present[a] = 1;
}
int diff = 0;
int gcdInt = 0;
int ans = 0;
for (int j = 1; j < 1000001; j++) {
if (present[j] == 0) {
gcdInt = 0;
for (int num = j; num < 1000001; num += j) {
if (present[num] == 1) {
if (gcdInt == 0) {
gcdInt = num;
} else {
gcdInt = gcd(gcdInt, num);
}
}
}
if (gcdInt == j) {
diff++;
present[j] = 1;
}
}
}
ans += diff;
System.out.println(ans);
}
/*public static int gcd(int a, int b) {
while (a*b > 0) {
if (a > b) {
a = a % b;
} else {
b = b % a;
}
}
return a + b;
}*/
public static int gcd(int x, int y) {
int temp;
while (y > 0) {
x %= y;
temp = x;
x = y;
y = temp;
}
return x;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
1d5f1fb40301a0bbd396acdae65d5a22
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class hs {
public static int gcd(int a, int b) {
if(b == 0)
return a;
return gcd(b, a%b);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
boolean[] us = new boolean[(int)(1000001)];
for(int i = 0; i < n; i++) {
int num =sc.nextInt();
us[num] = true;
}
int ans = 0;
for(int i = us.length-1; i >= 1; i--) {
if(us[i])
continue;
int gcd = 0;
for(int j = i*2; j < us.length; j+=i) {
if(us[j])
gcd = gcd(gcd, j);
}
if(gcd == i) {
us[i] = true;
ans++;
}
}
System.out.println(ans);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9571b8e7001a65cd76ccfebde3f5b9c1
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
// have faith in yourself!!!!!
/*
Naive mistakes in java :
--> Arrays.sort(primitive) is O(n^2)
--> Never use '=' to compare to Integer data types, instead use 'equals()'
--> -4 % 3 = -1, actually it should be 2, so add '+n' to modulo result
*/
import java.io.*;
import java.util.*;
public class CodeForces {
public static void main(String[] args) throws IOException {
openIO();
int testCase = 1;
// testCase = sc. nextInt();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void solve(int tCase) throws IOException {
int n = sc.nextInt();
int[] arr = new int[n];
int mx = (int)1e6 + 1;
boolean[] isPresent = new boolean[mx];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
isPresent[arr[i]] = true;
}
int cnt = 0;
for(int i=1;i<mx;i++){
if(isPresent[i])continue;
int gcd = 0;
for(int j=i;j<mx;j+=i)
if(isPresent[j]){
gcd = (int) _gcd(gcd,j);
}
if(gcd == i){
isPresent[i] = true;
cnt++;
}
}
out.println(cnt );
}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
public static int mod = (int) 1e9 + 7;
// public static int mod = 998244353;
public static int inf_int = (int) 1e9;
public static long inf_long = (long) 2e18;
public static void _sort(int[] arr, boolean isAscending) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
public static void _sort(long[] arr, boolean isAscending) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (long ele : arr) list.add(ele);
Collections.sort(list);
if (!isAscending) Collections.reverse(list);
for (int i = 0; i < n; i++) arr[i] = list.get(i);
}
// time : O(1), space : O(1)
public static int _digitCount(long num,int base){
// this will give the # of digits needed for a number num in format : base
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(n), space: O(n)
public static long _fact(int n){
// simple factorial calculator
long ans = 1;
for(int i=2;i<=n;i++)
ans = ans * i % mod;
return ans;
}
// time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
public static long[] factorial , inverseFact;
public static void _ncr_precompute(int n){
factorial = new long[n+1];
inverseFact = new long[n+1];
factorial[0] = inverseFact[0] = 1;
for (int i = 1; i <=n; i++) {
factorial[i] = (factorial[i - 1] * i) % mod;
inverseFact[i] = _power(factorial[i], mod - 2);
}
}
// time of factorial calculation after pre-computation is O(1)
public static int _ncr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
}
public static int _npr(int n,int r){
if(r > n)return 0;
return (int)(factorial[n] * inverseFact[n - r] % mod);
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
if (a == 0)
return b;
return _gcd(b % a, a);
}
// lcm(a,b) * gcd(a,b) = a * b
public static long _lcm(long a, long b) {
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve or first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
// check if x is a prime # of not. time : O( n ^ 1/2 )
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
static class Pair<K, V>{
K ff;
V ss;
public Pair(K ff, V ss) {
this.ff = ff;
this.ss = ss;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || this.getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return ff.equals(pair.ff) && ss.equals(pair.ss);
}
@Override
public int hashCode() {
return Objects.hash(ff, ss);
}
}
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException {
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException {
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {
}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
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 {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
c212901c5db5d6d9e53a398acccba056
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
HashSet<Long> set = new HashSet<Long>();
long max = 0;
for(int i = 0; i < n; i++) {
long cv = Long.parseLong(st.nextToken());
set.add(cv);
max = Math.max(cv, max);
}
int tt = 0;
for(long i = 1; i <= max; i++) {
if(set.contains(i))
continue;
long gcd = 0;
for(long j = 2; i*j <= max; j++){
if(set.contains(i*j)){
if(gcd == 0)
gcd = i*j;
else
gcd = gcd(gcd, i*j);
if(gcd == i){
tt++;
break;
}
}
}
}
pw.println(tt);
pw.close();
}
static long gcd (long cv, long gcd) {
if (gcd == 0)
return cv;
else
return gcd (gcd, cv % gcd);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
0bf56c49999101d5cd44805efdf84c45
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main
{
InputStream is;
PrintWriter out = new PrintWriter(System.out);
String INPUT = "";
void run() throws Exception
{
is = System.in;
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws Exception { new Main().run(); }
public byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
public int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){ ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; }
public boolean isSpaceChar(int c)
{
return !(c >= 33 && c <= 126);
}
public int skip()
{
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public double nd()
{
return Double.parseDouble(ns());
}
public char nc()
{
return (char)skip();
}
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b)))
{
sb.appendCodePoint(b); b = readByte();
}
return sb.toString();
}
private int ni()
{
return (int)nl();
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-')
{
minus = true; b = readByte();
}
while(true)
{
if(b >= '0' && b <= '9')
{
num = num * 10 + (b - '0');
}
else{return minus ? -num : num;} b = readByte();
}
}
class Pair
{
int first;
int second;
Pair(int a, int b)
{
first = a;
second = b;
}
}
int gcd(int a, int b)
{
return (b==0)?a:gcd(b,a%b);
}
void solve()
{
int n = ni();
int max = 1000000;
boolean[]arr = new boolean[max + 1];
for(int i = 0;i<n;i++){
arr[ni()] = true;
}
for(int i=max;i>=1;i--){
int gcd = 0;
for(int j = i;j<=max;j+=i){
if(arr[j]){
gcd = gcd(gcd, j);
}
}
if(gcd == i){
arr[i] = true;
}
}
int ans = 0;
for(int i=1;i<=max;i++){
if(arr[i]) ans++;
}
out.println(ans - n);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
b4df0f324af7d1f206d4504fbd23c58d
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
solve();
pw.flush();
}
public static void solve() {
int n = sc.nextInt();
int[] a = sc.nextIntArray(n);
Sieve s = new Sieve((int)1e6);
HashSet<Integer> set = new HashSet<>();
int gcd = a[0];
for(int i = 0; i < n; i++){
set.add(a[i]);
gcd = gcd(gcd,a[i]);
}
if(gcd == 1){
set.add(1);
}
for(int i = (int)1e6; i >= 2; i--){
int cnt = 0;
if(set.contains(i)) continue;
int gcd2 = 0;
for(int j = 1; j*i <= (int)1e6; j++){
if(set.contains(j*i)){
if(cnt == 0){
gcd2 = j;
}else{
gcd2 = gcd(gcd2,j);
}
cnt++;
}
if(cnt == 2 && gcd2 == 1) break;
}
if(cnt >= 2 && (gcd2 == 1)) set.add(i);
}
//pw.println(set);
pw.println(set.size() - n);
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
private static int gcd(int a, int b)
{
while (b > 0)
{
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
}
class Sieve{
static int n;
static int[] f;
static ArrayList<Integer> prime;
public Sieve(int n){
long ln = n;
prime = new ArrayList<Integer>();
f = new int[n+1];
f[0] = f[1] = -1;
for(int i = 2; i <= n; i++){
if(f[i] != 0){
continue;
}
f[i] = i;
prime.add(i);
long li = (long)i;
for(long j = li*li; j <= ln; j += li){
if(f[(int)j] == 0){
f[(int)j] = i;
}
}
}
}
public static boolean isPrime(int x){
return f[x] == x;
}
public static ArrayList<Integer> factorList(int x){
ArrayList<Integer> res = new ArrayList<Integer>();
while(x != 1){
res.add(f[x]);
x /= f[x];
}
return res;
}
public static HashMap<Integer,Integer> factor(int x){
ArrayList<Integer> fl = factorList(x);
HashMap<Integer,Integer> res = new HashMap<Integer,Integer>();
if(fl.size()==0){
return new HashMap<Integer,Integer>();
}
int prev = fl.get(0);
int cnt = 0;
for(int p : fl){
if(prev == p){
cnt++;
}else{
res.put(prev,cnt);
prev = p;
cnt = 1;
}
}
res.put(prev,cnt);
return res;
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public FastScanner(FileReader in) {
reader = new BufferedReader(in);
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String[] nextArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7e3ee4978e2d117c6a0a52e1f708574e
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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
*/
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);
DNotAdding solver = new DNotAdding();
solver.solve(1, in, out);
out.close();
}
static class DNotAdding {
int N = (int) 1e6 + 5;
int[] map = new int[N];
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
map[a[i]] = 1;
}
int cnt = 0;
for (int i = 1; i < N; ++i) {
if (check(i)) {
++cnt;
}
}
out.println(cnt - n);
}
private boolean check(int i) {
int t = 0;
for (int j = i; j < N; j += i) {
if (map[j] > 0) {
t = gcd(t, j);
}
}
return t == i;
}
int gcd(int a, int b) {
return b != 0 ? gcd(b, a % b) : a;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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);
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
b52b935d4f995d95759c98e8e40fea4f
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
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
*/
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);
DNotAdding solver = new DNotAdding();
solver.solve(1, in, out);
out.close();
}
static class DNotAdding {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n];
int N = (int) 1e6 + 5;
int[] map = new int[N];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
map[a[i]] = 1;
}
// for (int i = 0; i < n; i++) {
// for (int j = 1; j * j <= a[i]; j++) {
// if (a[i] % j == 0) {
// int x = j;
// int y = a[i] / j;
// if (map[x] != 1) {
// map[x] = gcd(map[x], y);
// }
// if (map[y] != 1) {
// map[y] = gcd(map[y], x);
// }
// }
// }
// }
// int cnt = 0;
// for (int i = 1; i < N; i++) {
// if (map[i] == 1) {
// cnt++;
// }
// }
int[] b = new int[N];
for (int i = 1; i < N; ++i) {
for (int j = i; j < N; j += i) {
if (map[j] > 0) {
b[i] = gcd(b[i], j);
}
}
}
int cnt = 0;
for (int i = 1; i < N; ++i) {
if (b[i] == i) {
++cnt;
}
}
out.println(cnt - n);
}
int gcd(int a, int b) {
return b != 0 ? gcd(b, a % b) : a;
}
}
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;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
b5caebfb111ada9843de143cddf36d33
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
//Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static int n;
static int[] a;
static boolean[] b;
static final int mx = (int)1e6;
static int res;
public static void main(String[] args) throws IOException {
t = 1;
while (t-- > 0) {
n = in.iscan(); a = new int[n]; b = new boolean[mx+5];
for (int i = 0; i < n; i++) {
a[i] = in.iscan();
b[a[i]] = true;
}
res = 0;
for (int i = mx; i >= 1; i--) {
if (b[i]) {
continue;
}
long gcd = -1;
boolean flag = false;
for (int j = i; j <= mx; j += i) {
if (b[j]) {
if (gcd == -1) {
gcd = j/i;
}
else {
gcd = UTILITIES.gcd(gcd, j/i);
flag = true;
}
}
}
if (gcd == 1 && flag) {
res++;
b[i] = true;
}
}
out.println(res);
}
out.close();
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
88bf7ec150fab65d5a76df86e176c66a
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.math.MathContext;
import java.util.*;
public class cp {
static int mod=(int)1e9+7;
// static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static int[] sp;
static int size=(int)1e6;
static int[] arInt;
static long[] arLong;
public static void main(String[] args) throws IOException {
// long tc=sc.nextLong();
// Scanner sc=new Scanner(System.in);
int tc=1;
// primeSet=new HashSet<>();
// sieveOfEratosthenes((int)1e6+5);
while(tc-->0)
{
int n=sc.nextInt();
int max=1000000;
boolean inArr[]=new boolean[1000000+5];
// HashSet<Integer> set=new HashSet<>();
for (int i = 0; i < n; i++) {
int temp=sc.nextInt();
inArr[temp]=true;
}
int cnt=0;
for(int i=max;i>=1;i--)
{
int g=0;
for(int j=i;j<=max;j+=i)
{
if(inArr[j])
g=gcd(g, j);
}
if(i==g)
{
inArr[g]=true;
cnt++;
}
}
out.println(cnt-n);
}
out.flush();
out.close();
System.gc();
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static class A implements Comparable<A>{
int a;
int b;
int c;
int sum;
public A(int a,int b,int c) {
// TODO Auto-generated constructor stub
this.a=a;
this.b=b;
this.c=c;
this.sum=a+b+c;
}
@Override
public int compareTo(cp.A o) {
// TODO Auto-generated method stub
return this.sum-o.sum;
}
}
static boolean isPowerOfTwo(int n)
{
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static int util(char a,char b)
{
int A=a-'0';
int B=b-'0';
return A+B;
}
static void arrInt(int n) throws IOException
{
arInt=new int[n];
for (int i = 0; i < arInt.length; i++) {
arInt[i]=sc.nextInt();
}
}
static void arrLong(int n) throws IOException
{
arLong=new long[n];
for (int i = 0; i < arLong.length; i++) {
arLong[i]=sc.nextLong();
}
}
static ArrayList<Integer> add(int id,int c)
{
ArrayList<Integer> newArr=new ArrayList<>();
for(int i=0;i<id;i++)
newArr.add(arInt[i]);
newArr.add(c);
for(int i=id;i<arInt.length;i++)
{
newArr.add(arInt[i]);
}
return newArr;
}
// function to find first index >= y
static int upper(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int lower(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) < x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>=x)
{
return l;
}
if(arr.get(h)>=x)
return h;
return -1;
}
static int N = 501;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// Precompute inverse of natural numbers
for(int i = 2; i <= N; i++)
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
static String tr(String s)
{
int now = 0;
while (now + 1 < s.length() && s.charAt(now)== '0')
++now;
return s.substring(now);
}
static ArrayList<Integer> ans;
static void dfs(int node,Graph gg,int cnt,int k,ArrayList<Integer> temp)
{
if(cnt==k)
return;
for(Integer each:gg.list[node])
{
if(each==0)
{
temp.add(each);
ans=new ArrayList<>(temp);
temp.remove(temp.size()-1);
continue;
}
temp.add(each);
dfs(each,gg,cnt+1,k,temp);
temp.remove(temp.size()-1);
}
return;
}
static boolean isPrime(long 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;
}
static ArrayList<Integer> commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
ArrayList<Integer> Div=new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
Div.add(i);
else
{
Div.add(i);
Div.add(n/i);
}
}
}
return Div;
}
static HashSet<Integer> factors(int x)
{
HashSet<Integer> a=new HashSet<Integer>();
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
a.add(i);
a.add(x/i);
}
}
return a;
}
static void primeFactors(int n,HashSet<Integer> factors)
{
// Print the number of 2s that divide n
while (n%2==0)
{
factors.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 <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
factors.add(i);
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
factors.add(n);
}
static class Node
{
int vertex;
HashSet<Node> adj;
int deg;
Node(int ver)
{
vertex=ver;
deg=0;
adj=new HashSet<Node>();
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Tuple{
int a;
int b;
int c;
public Tuple(int a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
}
//function to find prime factors of n
static HashMap<Long,Long> findFactors(long n2)
{
HashMap<Long,Long> ans=new HashMap<>();
if(n2%2==0)
{
ans.put(2L, 0L);
// cnt++;
while((n2&1)==0)
{
n2=n2>>1;
ans.put(2L, ans.get(2L)+1);
//
}
}
for(long i=3;i*i<=n2;i+=2)
{
if(n2%i==0)
{
ans.put((long)i, 0L);
// cnt++;
while(n2%i==0)
{
n2=n2/i;
ans.put((long)i, ans.get((long)i)+1);
}
}
}
if(n2!=1)
{
ans.put(n2, ans.getOrDefault(n2, (long) 0)+1);
}
return ans;
}
//fenwick tree implementaion
static class fwt
{
int n;
long BITree[];
fwt(int n)
{
this.n=n;
BITree=new long[n+1];
}
fwt(int arr[], int n)
{
this.n=n;
BITree=new long[n+1];
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
}
long getSum(int index)
{
long sum = 0;
index = index + 1;
while(index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int n, int index,int val)
{
index = index + 1;
while(index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
void print()
{
for(int i=0;i<n;i++)
out.print(getSum(i)+" ");
out.println();
}
}
class sparseTable{
int n;
long[][]dp;
int log2[];
int P;
void buildTable(long[] arr)
{
n=arr.length;
P=(int)Math.floor(Math.log(n)/Math.log(2));
log2=new int[n+1];
log2[0]=log2[1]=0;
for(int i=2;i<=n;i++)
{
log2[i]=log2[i/2]+1;
}
dp=new long[P+1][n];
for(int i=0;i<n;i++)
{
dp[0][i]=arr[i];
}
for(int p=1;p<=P;p++)
{
for(int i=0;i+(1<<p)<=n;i++)
{
long left=dp[p-1][i];
long right=dp[p-1][i+(1<<(p-1))];
dp[p][i]=Math.max(left, right);
}
}
}
long maxQuery(int l,int r)
{
int len=r-l+1;
int p=(int)Math.floor(log2[len]);
long left=dp[p][l];
long right=dp[p][r-(1<<p)+1];
return Math.max(left, right);
}
}
//Function to find number of set bits
static int setBitNumber(long n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return msb;
}
static int getFirstSetBitPos(long n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
static ArrayList<Integer> primes;
static HashSet<Integer> primeSet;
static boolean prime[];
static void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime= new boolean[n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
primeSet.add(i);
}
}
static long mod(long a, long b) {
long c = a % b;
return (c < 0) ? c + b : c;
}
static void swap(long arr[],int i,int j)
{
long temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
static boolean util(int a,int b,int c)
{
if(b>a)util(b, a, c);
while(c>=a)
{
c-=a;
if(c%b==0)
return true;
}
return (c%b==0);
}
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void printYesNo(boolean condition)
{
if (condition) {
out.println("YES");
}
else {
out.println("NO");
}
}
static int LowerBound(int a[], int x)
{ // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int lowerIndex(int arr[], int n, int x)
{
int l = 0, h = n - 1;
while (l<=h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid -1 ;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
static int upperIndex(int arr[], int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int upperIndex(long arr[], int n, long y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static int UpperBound(long a[], long x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static class DisjointUnionSets
{
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++)
parent[i] = i;
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else // if ranks are the same
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
// if(xRoot!=yRoot)
// parent[y]=x;
}
int connectedComponents()
{
int cnt=0;
for(int i=0;i<n;i++)
{
if(parent[i]==i)
cnt++;
}
return cnt;
}
}
static class Graph
{
int v;
ArrayList<Integer> list[];
Graph(int v)
{
this.v=v;
list=new ArrayList[v+1];
for(int i=1;i<=v;i++)
list[i]=new ArrayList<Integer>();
}
void addEdge(int a, int b)
{
this.list[a].add(b);
}
}
// static class GraphMap{
// Map<String,ArrayList<String>> graph;
// GraphMap() {
// // TODO Auto-generated constructor stub
// graph=new HashMap<String,ArrayList<String>>();
//
// }
// void addEdge(String a,String b)
// {
// if(graph.containsKey(a))
// this.graph.get(a).add(b);
// else {
// this.graph.put(a, new ArrayList<>());
// this.graph.get(a).add(b);
// }
// }
// }
// static void dfsMap(GraphMap g,HashSet<String> vis,String src,int ok)
// {
// vis.add(src);
//
// if(g.graph.get(src)!=null)
// {
// for(String each:g.graph.get(src))
// {
// if(!vis.contains(each))
// {
// dfsMap(g, vis, each, ok+1);
// }
// }
// }
//
// cnt=Math.max(cnt, ok);
// }
static double sum[];
static long cnt;
// static void DFS(Graph g, boolean[] visited, int u)
// {
// visited[u]=true;
//
// for(int i=0;i<g.list[u].size();i++)
// {
// int v=g.list[u].get(i);
//
// if(!visited[v])
// {
// cnt1=cnt1*2;
// DFS(g, visited, v);
//
// }
//
// }
//
//
// }
static class Pair implements Comparable<Pair>
{
int x;
int y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return this.x-o.x;
}
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// static long modInverse(long a, long m)
// {
// long g = gcd(a, m);
//
// return power(a, m - 2, m);
//
// }
static long power(long x, long y)
{
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static int power(int x, int y)
{
int res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
//cnt+=a/b;
return gcd(b%a,a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
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();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9d00e19328918808aedc223af23ac408
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class Main{
private static int n;
private final static int max = 1000006;
private static boolean[] data = new boolean[max];
private static Scanner scanner = new Scanner(System.in);
private static void input() {
n = scanner.nextInt();
for (int i=0; i<n;i++) {
data[scanner.nextInt()] = true;
}
}
private static int cal() {
int count = 0;
for (int i=1; i<max; i++) {
if (!data[i]) {
int g = -1;
for (int j = 2; j*i < max; j++) {
if (data[i*j]) {
if (g == -1) {
g = j;
} else {
g = gcd(g, j);
if (g == 1) {
break;
}
}
}
}
if (g == 1) {
count++;
}
}
}
return count;
}
private static int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public static void main(String [] args) {
input();
System.out.println(cal());
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
040d24a6d51c31390b1ad52043846f94
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Contest1627D
{
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() { // reads in the next string
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() { // reads in the next int
return Integer.parseInt(next());
}
public long nextLong() { // reads in the next long
return Long.parseLong(next());
}
public double nextDouble() { // reads in the next double
return Double.parseDouble(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static long mod = 1000000007;
public static void main(String[] args)
{
int n = r.nextInt();
int maxn = 1000005;
int[] count = new int[maxn+1];
for (int i = 0; i < n; i ++)
{
int a = r.nextInt();
count[a] ++;
}
int ans = 0;
int[] hi = new int[maxn + 1];
for (int i = 1; i < maxn; i ++)
{
int num = 0;
for (int j = i; j < maxn; j +=i)
{
num += count[j];
}
hi[i] = num;
}
for (int i = 1; i < maxn; i ++)
{
if (count[i] == 0 && hi[i] >= 2)
{
boolean flag = false;
for (int j = i*2; j < maxn; j += i)
{
if (hi[j] >= hi[i])
{
flag = true;
break;
}
}
ans += (!flag ? 1:0);
}
}
pw.println(ans);
pw.close();
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
d72d37b90aa4fa2b67a80934ce4fc9c8
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import javax.print.attribute.HashAttributeSet;
//import org.graalvm.compiler.phases.graph.FixedNodeProbabilityCache;
//import org.graalvm.compiler.phases.graph.FixedNodeProbabilityCache;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static long mod_mul( long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum( long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void print(long[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static void print(int[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y){
if(y<0) return 0;
long m = mod;
if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z; // factorial
private long[] z1; // inverse factorial
private long[] z2; // incerse number
private long mod;
public Combinations(long N , long mod) {
this.mod = mod;
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return z1[(int)n];
}
long ncr(long N, long R)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = gcd(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(0);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static int TC;
static StringBuilder sb = new StringBuilder();
static PrintWriter out=new PrintWriter(System.out);
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
TC = 0;
for(int i = 1 ; i<=tc ; i++) {
TC++;
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.print(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
int[] count = new int[(int)((1e6+1))];
int[] arr = new int[n];
for(int i = 0 ;i<n ; i++) arr[i] = sc.nextInt();
for(int e:arr) count[e]++;
for(int i = (int)(1e6) ; i>=1 ; i--) {
int gcd = 0;
for(int j = 2*i ; j<=1e6 ; j+=i) {
if(count[j] == 1) gcd = (int)gcd(gcd , j);
}
if(gcd == i) count[i] = 1;
}
int ans = -n;
for(int e:count) ans += e;
sb.append(ans+"\n");
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
d1dc7b6fbca0e6e9e299b4a579464893
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static long mod_mul( long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum( long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void print(long[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static void print(int[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y){
if(y<0) return 0;
long m = mod;
if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
private long mod;
public Combinations(long N , long mod) {
this.mod = mod;
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = gcd(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(0);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return gcd(left, right);
}
public void update(int index , int val) {
arr[index] = val;
// for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.print(sb);
}
static class Pair{
int f , s , t;
Pair(int f , int s , int t){
this.f = f;
this.s = s;
this.t = t;
}
public String toString() {
return "{"+this.f +","+this.s+","+this.t+"}";
}
}
static void TEST_CASE() {
int n = sc.nextInt();
int[] c = new int[(int)(1e6+1)];
boolean[] visit = new boolean[(int)(1e6+1)];
int k = (int)(1e6);
for(int i =0 ; i<n ; i++){
int e = sc.nextInt();
c[e]++;
visit[e] = true;
}
for(int i = k ; i>=1 ; i--) {
int gcd = 0;
for(int j = i ; j<=k ; j+=i) {
if(!visit[j]) continue;
gcd = (int)gcd(gcd , j);
}
if(gcd == i) {
visit[i] = true;
}
}
int ans = -n;
for(int i = 1; i<=k ; i++) if(visit[i]) ans++;
sb.append(ans+"\n");
}
}
/*******************************************************************************************************************************************************/
/**
*/
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
3663b221e9b25c1b0fc28f3565369531
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
//package com.codeforces.Practise;
import java.io.*;
import java.util.HashSet;
public class temp {
// Function to return gcd of a and b
static int Findgcd(int a, int b) {
if (a == 0)
return b;
return Findgcd(b % a, a);
}
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = scan.nextInt();
HashSet<Integer> hs = new HashSet<>();
for (int i = 0; i < n; i++) {
int val = scan.nextInt();
hs.add(val);
}
//check gcd exist or not
int ans = 0;
for (int i = 1; i <= 1e6; i++) {
if(hs.contains(i))continue;
int gcd = -1;
for (int j = i; j <= 1e6; j += i) {
if (hs.contains(j)) {
if (gcd == -1) {
gcd = j;
} else {
gcd = Findgcd(gcd, j);
}
}
}
if (gcd == i) {
ans++;
}
}
bw.write(ans + "");
bw.newLine();
bw.flush();
}
//FAST READER
static class Reader {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public Reader() {
in = new BufferedInputStream(System.in, BS);
}
public Reader(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+(cur < 0 ? -1*nextLong()/num : nextLong()/num);
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
4c07ed6a0be502afb1552b035a3c7cc1
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
//package com.codeforces.Practise;
import java.io.*;
public class NotAdding {
// Function to return gcd of a and b
static int Findgcd(int a, int b) {
if (a == 0)
return b;
return Findgcd(b % a, a);
}
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = scan.nextInt();
boolean[] visited=new boolean[(int) (1e6+1)];
for (int i = 0; i < n; i++) {
int val = scan.nextInt();
visited[val]=true;
}
//check gcd exist or not
int ans = 0;
for (int i = 1; i <= 1e6; i++) {
if(visited[i])continue;
int gcd = -1;
for (int j = i; j <= 1e6; j += i) {
if (visited[j]) {
if (gcd == -1) {
gcd = j;
} else {
gcd = Findgcd(gcd, j);
}
}
}
if (gcd == i) {
ans++;
}
}
bw.write(ans + "");
bw.newLine();
bw.flush();
}
//FAST READER
static class Reader {
public int BS = 1 << 16;
public char NC = (char) 0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public Reader() {
in = new BufferedInputStream(System.in, BS);
}
public Reader(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
num = 1;
boolean neg = false;
if (c == NC) c = nextChar();
for (; (c < '0' || c > '9'); c = nextChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = nextChar()) {
res = (res << 3) + (res << 1) + c - '0';
num *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + (cur < 0 ? -1 * nextLong() / num : nextLong() / num);
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = nextChar();
while (c > 32) {
res.append(c);
c = nextChar();
}
return res.toString();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
58506a221455d26fffa9cbb2fa282b1e
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
//package contest766div2;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class D_Not_Adding {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
boolean[] nums = new boolean[1000001];
int max = 0;
for (int i = 0; i < n; i++) {
var num = in.nextInt();
nums[num] = true;
if (num > max) {
max = num;
}
}
var counter = 0;
for (int i = max; i >= 1; i--) {
if (nums[i]) {
continue;
}
int gcd = -1;
for (int j = 2; j * i <= max; j++) {
int can = j * i;
if (nums[can]) {
if (gcd == -1) {
gcd = can;
} else {
gcd = gcd(gcd, can);
}
if (gcd == i) {
counter++;
nums[i] = true;
break;
}
}
}
}
System.out.println(counter);
}
public static int gcd(int a , int b) {
if (a < b) {
int temp = a;
a = b;
b = temp;
}
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
0680b9c44382a51f8d47aaab4545bc71
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class 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[] args) {
FastReader obj = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int n=obj.nextInt();
int[] vis=new int[1000001];
HashSet<Integer> h=new HashSet<>();
for(int i=0;i<n;i++)
{
int temp=obj.nextInt();
vis[temp]=1;
h.add(temp);
}
for(int i=1;i<=1000000;i++)
{
int g=0;
for(int j=i;j<=1000000;j+=i)
{
if(vis[j]==1) g=gcd(g,j);
if(vis[g]==0 && g!=0)h.add(g);
}
}
System.out.println(h.size()-n);
}
public static int gcd(int a,int b)
{
if(a==0)return b;
return gcd(b%a,a);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9647798d87c43b36000f757e163c8021
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class 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 FastReader obj = new FastReader();
public static PrintWriter out = new PrintWriter(System.out);
public static void sort(long[] a) {
ArrayList<Long> arr = new ArrayList<>();
for (int i = 0; i < a.length; i++)
arr.add(a[i]);
Collections.sort(arr);
for (int i = 0; i < arr.size(); i++)
a[i] = arr.get(i);
}
public static void revsort(long[] a) {
ArrayList<Long> arr = new ArrayList<>();
for (int i = 0; i < a.length; i++)
arr.add(a[i]);
Collections.sort(arr, Collections.reverseOrder());
for (int i = 0; i < arr.size(); i++)
a[i] = arr.get(i);
}
//Cover the small test cases like for n=1 .
public static class pair {
long a;
long b;
pair(long x, long y) {
a = x;
b = y;
}
}
public static long l() {
return obj.nextLong();
}
public static int i() {
return obj.nextInt();
}
public static String s() {
return obj.next();
}
public static long[] l(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = l();
return arr;
}
public static int[] i(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = i();
return arr;
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static void p(long val) {
out.println(val);
}
public static void p(String s) {
out.println(s);
}
public static void pl(long[] arr) {
for (int i = 0; i < arr.length; i++) {
out.print(arr[i] + " ");
}
out.println();
}
public static void p(int[] arr) {
for (int i = 0; i < arr.length; i++) {
out.print(arr[i] + " ");
}
out.println();
}
public static void sortpair(ArrayList<pair> arr) {
//ascending just change return 1 to return -1 and vice versa to get descending.
//compare based on value of pair.a
arr.sort(new Comparator<pair>() {
public int compare(pair o1, pair o2) {
long val = o1.a - o2.a;
if (val == 0)
return 0;
else if (val > 0)
return 1;
else
return -1;
}
});
}
// Take of the small test cases such as when n=1,2 etc.
// remember in case of fenwick tree ft is 1 based but our array should be 0 based.
// in fenwick tree when we update some index it doesn't change the value to val but it
// adds the val value in it so remember to add val-a[i] instead of just adding val.
//in case of finding the inverse mod do it (biexpo(a,mod-2)%mod + mod )%mod
public static void main(String[] args) {
int len = 1;
while (len-- != 0) {
int n = i();
int[] present=new int[1000001];
for(int i=0;i<n;i++)
{
int x=obj.nextInt();
present[x]=1;
}
int ans=0;
for(int i=1;i<=1000000;i++)
{
int g=0;
for(int j=i;j<=1000000;j+=i)
{
if(present[j]==1)g=gcd(g,j);
}
if(g==i && present[g]!=1)ans++;
}
out.println(ans);
}
out.flush();
}
public static int gcd(int a,int b)
{
if(a==0)return b;
return gcd(b%a,a);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
afa37beab135d34712de9b3e473ec39e
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.lang.Math.ceil;
import static java.util.Arrays.sort;
public class JavaCodeforces {
public static void main(String[] args) throws Exception {
int t = 1;
while (t-- > 0) {
int n = ri();
boolean[] present = new boolean[(int) 1e6 + 1];
int a[] = ria(n);
Arrays.fill(present, false);
for (int i = 0; i < n; i++) {
present[a[i]] = true;
}
int ans = 0;
for (int i = 1; i <= 1e6; i++) {
int g = 0;
for (int mul = i; mul <= 1e6; mul += i) {
if (present[mul]) {
g = gcd(g, mul);
}
}
if (g == i && !present[i]) {
ans++;
}
}
prln(ans);
}
close();
}
static BufferedReader __i = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __r = new Random();
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0) return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0) return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static int[] exgcd(int a, int b) {
if (b == 0) return new int[]{1, 0};
int[] y = exgcd(b, a % b);
return new int[]{y[1], y[0] - y[1] * (a / b)};
}
static long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1, 0};
long[] y = exgcd(b, a % b);
return new long[]{y[1], y[0] - y[1] * (a / b)};
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static void resetBoolean(boolean[] vis, int n) {
for (int i = 0; i < n; i++) {
vis[i] = false;
}
}
static List<Integer>[] readGraph(int n, int m) throws IOException {
List<Integer>[] graph = new List[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = rni() - 1;
int v = ni() - 1;
graph[u].add(v);
graph[v].add(u);
}
return graph;
}
// input
static void r() throws IOException {
input = new StringTokenizer(rline());
}
static int ri() throws IOException {
return Integer.parseInt(rline());
}
static long rl() throws IOException {
return Long.parseLong(rline());
}
static double rd() throws IOException {
return Double.parseDouble(rline());
}
static int[] ria(int n) throws IOException {
int[] a = new int[n];
r();
for (int i = 0; i < n; ++i) a[i] = ni();
return a;
}
static void ria(int[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = ni();
}
static int[] riam1(int n) throws IOException {
int[] a = new int[n];
r();
for (int i = 0; i < n; ++i) a[i] = ni() - 1;
return a;
}
static void riam1(int[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = ni() - 1;
}
static long[] rla(int n) throws IOException {
long[] a = new long[n];
r();
for (int i = 0; i < n; ++i) a[i] = nl();
return a;
}
static void rla(long[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = nl();
}
static double[] rda(int n) throws IOException {
double[] a = new double[n];
r();
for (int i = 0; i < n; ++i) a[i] = nd();
return a;
}
static void rda(double[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = nd();
}
static char[] rcha() throws IOException {
return rline().toCharArray();
}
static void rcha(char[] a) throws IOException {
int n = a.length, i = 0;
for (char c : rline().toCharArray()) a[i++] = c;
}
static String rline() throws IOException {
return __i.readLine();
}
static String n() {
return input.nextToken();
}
static int rni() throws IOException {
r();
return ni();
}
static int ni() {
return Integer.parseInt(n());
}
static long rnl() throws IOException {
r();
return nl();
}
static long nl() {
return Long.parseLong(n());
}
static double rnd() throws IOException {
r();
return nd();
}
static double nd() {
return Double.parseDouble(n());
}
// output
static void pr(int i) {
__o.print(i);
}
static void prln(int i) {
__o.println(i);
}
static void pr(long l) {
__o.print(l);
}
static void prln(long l) {
__o.println(l);
}
static void pr(double d) {
__o.print(d);
}
static void prln(double d) {
__o.println(d);
}
static void pr(char c) {
__o.print(c);
}
static void prln(char c) {
__o.println(c);
}
static void pr(char[] s) {
__o.print(new String(s));
}
static void prln(char[] s) {
__o.println(new String(s));
}
static void pr(String s) {
__o.print(s);
}
static void prln(String s) {
__o.println(s);
}
static void pr(Object o) {
__o.print(o);
}
static void prln(Object o) {
__o.println(o);
}
static void prln() {
__o.println();
}
static void pryes() {
prln("yes");
}
static void pry() {
prln("Yes");
}
static void prY() {
prln("YES");
}
static void prno() {
prln("no");
}
static void prn() {
prln("No");
}
static void prN() {
prln("NO");
}
static boolean pryesno(boolean b) {
prln(b ? "yes" : "no");
return b;
}
;
static boolean pryn(boolean b) {
prln(b ? "Yes" : "No");
return b;
}
static boolean prYN(boolean b) {
prln(b ? "YES" : "NO");
return b;
}
static void prln(int... a) {
for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ;
if (a.length > 0) prln(a[a.length - 1]);
else prln();
}
static void prln(long... a) {
for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ;
if (a.length > 0) prln(a[a.length - 1]);
else prln();
}
static void prln(double... a) {
for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ;
if (a.length > 0) prln(a[a.length - 1]);
else prln();
}
static <T> void prln(Collection<T> c) {
int n = c.size() - 1;
Iterator<T> iter = c.iterator();
for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i) ;
if (n >= 0) prln(iter.next());
else prln();
}
static void h() {
prln("hlfd");
flush();
}
static void flush() {
__o.flush();
}
static void close() {
__o.close();
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
17061d0c4e3d244abb4756924023c2b2
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D {
public void prayGod() throws IOException {
int n = nextInt();
int[] a = nextIntArray(n);
int maxVal = 0;
for (int i = 0; i < n; i++) {
maxVal = Math.max(maxVal, a[i]);
}
long[] dp = new long[maxVal + 1];
long[] existed = new long[maxVal + 1];
for (int i = 0; i < n; i++) {
existed[a[i]]++;
}
long ret = 0;
for (int i = maxVal; i >= 1; i--) {
// Count number of values that are multiples of i
long curr = existed[i];
for (int j = i * 2; j <= maxVal; j += i) {
curr += existed[j];
}
// # of available pairs will be C(curr, 2)
dp[i] = curr * (curr - 1) / 2;
// Remove all pairs that whose gcd resulted in multiples of i
for (int j = i * 2; j <= maxVal; j += i) {
dp[i] -= dp[j];
}
// If this number has never been encountered before and it is possible to create
// it
if (existed[i] == 0 && dp[i] >= 1) {
ret++;
existed[i]++;
dp[i] += curr;
}
}
out.println(ret);
}
static final boolean RUN_TIMING = true;
static final boolean AUTOFLUSH = false;
static final boolean FILE_INPUT = false;
static final boolean FILE_OUTPUT = false;
static int iinf = 0x3f3f3f3f;
static long inf = (long) 1e18 + 10;
static long mod = 998244353L;
static char[] inputBuffer = new char[1 << 20];
static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20);
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), AUTOFLUSH);
// int data-type
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
// long data-type
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public static void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
public void sort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
// double data-type
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++)
arr[i] = nextDouble();
return arr;
}
public static void printArray(double[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
// Generic type
public <T> void sort(T[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T> void printArray(T[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
public String next() throws IOException {
int len = 0;
int c;
do {
c = in.read();
} while (Character.isWhitespace(c) && c != -1);
if (c == -1) {
throw new NoSuchElementException("Reached EOF");
}
do {
inputBuffer[len] = (char) c;
len++;
c = in.read();
} while (!Character.isWhitespace(c) && c != -1);
while (c != '\n' && Character.isWhitespace(c) && c != -1) {
c = in.read();
}
if (c != -1 && c != '\n') {
in.unread(c);
}
return new String(inputBuffer, 0, len);
}
public String nextLine() throws IOException {
int len = 0;
int c;
while ((c = in.read()) != '\n' && c != -1) {
if (c == '\r') {
continue;
}
inputBuffer[len] = (char) c;
len++;
}
return new String(inputBuffer, 0, len);
}
public boolean hasNext() throws IOException {
String line = nextLine();
if (line.isEmpty()) {
return false;
}
in.unread('\n');
in.unread(line.toCharArray());
return true;
}
public void shuffle(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void shuffle(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void shuffle(Object[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
Object temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public static void main(String[] args) throws IOException {
if (FILE_INPUT)
in = new PushbackReader(new BufferedReader(new FileReader(new File("output.txt"))), 1 << 20);
if (FILE_OUTPUT)
out = new PrintWriter(new FileWriter(new File("output.txt")));
long time = 0;
time -= System.nanoTime();
new D().prayGod();
time += System.nanoTime();
if (RUN_TIMING)
System.err.printf("%.3f ms%n", time / 1000000.0);
out.flush();
in.close();
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
e49f7fa4d78c25bfc381d72026688ba0
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class NotAdding {
public static int gcd(int A, int B) {
while (B != 0) {
int C = A;
A = B;
B = C % B;
}
return A;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, false);
int N = reader.nextInt();
int[] A = new int[N];
int M = 0;
for (int i = 0; i < N; i++) {
A[i] = reader.nextInt();
M = Math.max(M, A[i]);
}
int[] dp = new int[M + 1];
for (int x : A) dp[x] = x;
for (int i = 1; i <= M; i++) {
for (int j = 2 * i; j <= M; j += i) {
dp[i] = gcd(dp[i], dp[j]);
}
}
int count = 0;
for (int i = 1; i <= M; i++) {
if (dp[i] == i) count++;
}
writer.println(count - N);
writer.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());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
1ca2f33e9eed0b72b8d0cbf40e0db92a
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class NotAdding {
public static int gcd(int A, int B) {
while (B != 0) {
int C = A;
A = B;
B = C % B;
}
return A;
}
public static void main(String[] args) {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, false);
int N = reader.nextInt();
int[] A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = reader.nextInt();
}
int M = A[0];
for (int x : A) M = Math.max(M, x);
int[] dp = new int[M + 1];
for (int x : A) dp[x] = x;
for (int i = 1; i <= M; i++) {
for (int j = 2 * i; j <= M; j += i) {
dp[i] = gcd(dp[i], dp[j]);
}
}
int count = 0;
for (int i = 1; i <= M; i++) {
if (dp[i] == i) count++;
}
writer.println(count - N);
writer.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());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
84980b54c398c3bb131dcbd9f028a183
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.InputMismatchException;
public class E1627D {
static int A = (int) 1e6;
public static void main(String[] args) {
FastIO io = new FastIO();
int n = io.nextInt();
boolean[] exists = new boolean[A + 1];
for (int i = 0; i < n; i++) exists[io.nextInt()] = true;
int count = 0;
for (int i = 1; i <= 1e6; i++) {
long gcd = 0;
for (int j = i; j <= 1e6; j += i) {
if (exists[j])
gcd = gcd(gcd, j);
}
if (gcd == i) count++;
}
io.println(count - n);
io.close();
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
private static class FastIO extends PrintWriter {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public int nextInt() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() { // nextLong() would be implemented similarly
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
46f15763b13d4873be8b478bd12b9ef8
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static AReader scan = new AReader();
static int N = 1000010;
static int MAXN = 1000000;
static boolean[] st = new boolean[N];
static int gcd(int a,int b){
return b == 0 ? a : gcd(b,a%b);
}
static void solve() {
int n = scan.nextInt();
for(int i = 0;i<n;i++) st[scan.nextInt()] = true;
int cnt = 0;
for(int i = 1;i<=MAXN;i++){
int g = 0;
if(st[i]) continue;
for(int j = i;j<=MAXN;j +=i){
if(st[j]){
g = gcd(j,g);
}
}
if(i == g){
st[i] = true;
cnt++;
}
}
System.out.println(cnt);
}
public static void main(String[] args) {
//int T = scan.nextInt();
//while (T-- > 0) {
solve();
//}
}
}
class AReader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
76e36c60ec4a7cbd8c6ff4f1cc03c425
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static AReader scan = new AReader();
static int N = 1000010;
static int MAXN = 1000000;
static boolean[] st = new boolean[N];
static int gcd(int a,int b){
return b == 0 ? a : gcd(b,a%b);
}
static void solve() {
int n = scan.nextInt();
for(int i = 0;i<n;i++) st[scan.nextInt()] = true;
int cnt = 0;
for(int i = MAXN;i>0;i--){
int g = 0;
if(st[i]) continue;
for(int j = i;j<=MAXN;j +=i){
if(st[j]){
g = gcd(j,g);
}
}
if(i == g){
st[i] = true;
cnt++;
}
}
System.out.println(cnt);
}
public static void main(String[] args) {
//int T = scan.nextInt();
//while (T-- > 0) {
solve();
//}
}
}
class AReader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9313150a3d800798a1aa410f2b227ca5
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.IOException;
public class Main {
public static void main(String... args) throws IOException {
int t = readInt();
boolean[] bits = new boolean[1000001];
int max = 0;
for (int i = 0; i < t; i++) {
int read = readInt();
bits[read] = true;
max = Math.max(max, read);
}
int k = 0;
for (int i = 1; i < max; i++) {
if (!bits[i]) {
int gcd = 0;
for (int j = i * 2; j <= max; j += i) {
if (bits[j]) {
gcd = gcd(gcd, j);
}
}
if (gcd == i) {
k += 1;
}
}
}
System.out.println(k);
}
static int gcd(int a, int b) {
while (a != 0) {
int c = a;
a = b % a;
b = c;
}
return b;
}
static int readInt() throws IOException {
int i = System.in.read();
while (i == ' ' || i == '\n' || i == '\r') {
i = System.in.read();
}
boolean negative = false;
if (i == '-') {
negative = true;
i = System.in.read();
}
int result = 0;
while (i != ' ' && i != '\n' && i != '\r' && i != -1) {
result *= 10;
result += i - '0';
i = System.in.read();
}
return negative ? -result : result;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
14e349d19d7e3ea4bb8cf37be870c606
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
/*
Codeforces
Problem 1627D
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class NotAdding {
public static void main(String[] args) throws IOException {
FastIO in = new FastIO(System.in);
int n = in.nextInt();
int[] a = new int[n];
int max = -1;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
max = Math.max(a[i], max);
}
boolean[] inArray = new boolean[max + 1];
int count = 0;
for (int i = 0; i < n; i++) inArray[a[i]] = true;
for (int i = max; i > 0; i--) {
int g = 0;
for (int j = i; j <= max; j += i) {
if (inArray[j]) g = gcd(g, j);
}
if (i == g) {
inArray[i] = true;
count++;
}
}
System.out.println(count - n);
in.close();
}
public static int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public static class FastIO {
private InputStream dis;
private byte[] buffer = new byte[1 << 17];
private int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
public int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
public String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
public void close() throws IOException {
dis.close();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
df8e8836adefa4f2f4f367f9b5850502
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main{
static final Random random=new Random();
static long mod=1000000007L;
static HashMap<String,Integer>map=new HashMap<>();
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n){
int[] res=new int[n];
for(int i=0;i<n;i++)res[i]=nextInt();
return res;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
public static void main(String[] args) {
try {
FastReader in=new FastReader();
FastWriter out = new FastWriter();
//int testCases=in.nextInt();
int testCases=1;
while(testCases-- > 0){
// write code here
int n=in.nextInt();
//int[] arr=in.readIntArray(n);
int m=1000000;
boolean[] arr=new boolean[m+1];
int count=0;
for(int i=0;i<n;i++){
int a=in.nextInt();
arr[a]=true;
}
for(int i=1;i<=m;i++){
int gd=0;
for(int j=i;j<=m;j+=i){
if(arr[j]){
gd=gcd(gd,j);
}
}
if(gd==i){
count++;
arr[i]=true;
}
}
out.println(count-n);
}
out.close();
} catch (Exception e) {
return;
}
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
//constrain is helpful 10^6 numb
//1 to 10^6 check if the x is gcd of some subset of array
//we find multiple of x in array if present get gcd g, at last compare g with x if both are equal count++
//total-orignal array size
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
f8ed92611f873f02d62bcdd03b77fa93
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D {
public static final int MAX_A = 1000000;
public static void main(String[] args) {
var io = new Kattio(System.in, System.out);
solve(io);
io.close();
}
public static void solve(Kattio io) {
int n = io.nextInt();
boolean[] inArray = new boolean[MAX_A + 1];
for (int i = 0; i < n; i++) {
int a = io.nextInt();
inArray[a] = true;
}
int count = 0;
for (int i = 1; i <= MAX_A; i++) {
int g = 0;
for (int j = i; j <= MAX_A; j += i) {
if (inArray[j]) {
g = gcd(g, j);
}
}
if (i == g) {
inArray[i] = true;
count++;
}
}
io.println(count - n);
}
public static int gcd(int x, int y) {
int temp;
while (y > 0) {
x %= y;
temp = x;
x = y;
y = temp;
}
return x;
}
}
// modified from https://github.com/Kattis/kattio/blob/master/Kattio.java
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7cf618cc68c49fe698a10760e1c1ed67
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Solution extends PrintWriter {
int MX = 1_000_000;
void solve() {
int n = sc.nextInt();
int[] cnt = new int[MX+1];
for(int i = 0; i < n; i++) {
cnt[sc.nextInt()]++;
}
int ans = 0;
for(int i = 1; i <= MX; i++) {
int gcd = 0;
for(int j = i; j <= MX; j+=i) {
if(cnt[j] > 0) gcd = gcd(gcd, j);
}
if(gcd == i) ans++;
}
println(ans - n);
}
int gcd(int a, int b) {
while(b > 0) {
int t = b;
b = a%b;
a = t;
}
return a;
}
// Main() throws FileNotFoundException { super(new File("output.txt")); }
// InputReader sc = new InputReader(new FileInputStream("test_input.txt"));
Solution() { super(System.out); }
InputReader sc = new InputReader(System.in);
static class InputReader {
InputReader(InputStream in) { this.in = in; } InputStream in;
private byte[] buf = new byte[16384];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] $) {
new Thread(null, new Runnable() {
public void run() {
long start = System.nanoTime();
try {Solution solution = new Solution(); solution.solve(); solution.flush();}
catch (Exception e) {e.printStackTrace(); System.exit(1);}
System.err.println((System.nanoTime()-start)/1E9);
}
}, "1", 1 << 27).start();
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
c6b05d27027cdc3ab5f4d08c3e0a50df
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] ar = new int[n];
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++){
ar[i] = s.nextInt();
max = Math.max(max, ar[i]);
}
boolean[] present = new boolean[max+1];
for (int e: ar){
present[e] = true;
}
int cnt = 0;
for (int i = max; i > 0; i--){
int g = 0;
for (int j = i; j <= max; j += i){
if (present[j]) g = gcd(g, j);
}
if (i == g) {
cnt++;
present[i] = true;
}
}
System.out.println(cnt-n);
}
public static int gcd (int x, int y){
if (x == 0) return y;
if (y == 0) return x;
return gcd(y%x, x);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
5c8e23a3a0154852265098eea28e0541
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
boolean[] pres = new boolean[1_000_001];
int[] ar = new int[n];
for (int i = 0; i < n; i++){
ar[i] = s.nextInt();
pres[ar[i]] = true;
}
int cnt = 0;
for (int i = 1_000_000; i > 0; i--){
int g = 0;
for (int j = i; j <= 1_000_000; j += i){
if (pres[j]) g = gcd(g, j);
}
if (i == g){
pres[i] = true;
cnt++;
}
}
System.out.println(cnt-n);
}
public static int gcd(int x, int y){
if (x == 0) return y;
if (y == 0) return x;
return gcd(y%x, x);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7ae1b4ba5ce108fd65d78144ad70eff1
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
// For fast input output
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
try {
br = new BufferedReader(
new FileReader("input.txt"));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// end of fast i/o code
public static void main(String[] args) {
FastReader reader = new FastReader();
StringBuilder sb = new StringBuilder("");
int n = reader.nextInt();
int arr[] = new int[n];
HashSet<Integer> ts = new HashSet<>();
int max = Integer.MIN_VALUE;
for(int i=0; i<n; i++){
arr[i] = reader.nextInt();
max = Math.max(max, arr[i]);
ts.add(arr[i]);
}
int ans = 0;
for(int i=1; i<=max; i++){
if(ts.contains(i)){
continue;
}
int final_gcd = i;
int count = 0;
for(int j=1; i*j<=max; j++){
int num = i*j;
if(ts.contains(num)){
count++;
if(count==1){
final_gcd = num;
}
// System.out.println(i+" "+num);
final_gcd = gcd(final_gcd, num);
}
}
if(final_gcd==i && count>=1){
// System.out.println(i);
ans++;
}
// System.out.println((final_gcd==i));
}
System.out.println(ans);
}
static int gcd(int a, int b){
if(b==0){
return a;
}
return gcd(b, a%b);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
3e42ed04c0ec570c0a4edc3dbd7bb6af
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[]args){
long s = System.currentTimeMillis();
new Solver().run();
System.err.println(System.currentTimeMillis()-s+"ms");
}
}
class Solver{
final int MAX_N = (int)1e6;
void process(int testNumber){
int N = ni();
boolean present[] = new boolean[MAX_N + 1];
for(int i = 1; i <= N; i++){
int x = ni();
present[x] = true;
}
int res = 0;
for(int i = MAX_N; i >= 1; i--){
if(present[i]){
continue;
}
int g = 0;
for(int j = 2*i; j <= MAX_N; j += i){
if(present[j]){
g = gcd(g, j/i);
}
}
if(g == 1){
res += 1;
present[i] = true;
}
}
pn(res);
}
final long mod = (long)1e9+7l;
boolean DEBUG = true;
FastReader sc;
PrintWriter out = new PrintWriter(System.out);
void run(){
sc = new FastReader();
int t = 1;
// t = ni();
for(int test = 1; test <= t; test++)
process(test);
out.flush();
}
void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); };
void pn(Object o){ out.println(o); }
void p(Object o){ out.print(o); }
int ni(){ return Integer.parseInt(sc.next()); }
long nl(){ return Long.parseLong(sc.next()); }
double nd(){ return Double.parseDouble(sc.next()); }
String nln(){ return sc.nextLine(); }
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); }
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();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
class pair implements Comparable<pair> {
int first, second;
public pair(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(pair ob){
if(this.first != ob.first)
return this.first - ob.first;
return this.second - ob.second;
}
@Override
public String toString(){
return this.first + " " + this.second;
}
static public pair from(int f, int s){
return new pair(f, s);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
799550858d811997214db10a0f58d923
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
//package notadding;
import java.util.*;
import java.io.*;
public class notadding {
public static int gcd(int a, int b) {
int t;
while(b != 0) {
t = a;
a = b;
b = t % b;
}
return a;
}
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(fin.readLine());
boolean[] v = new boolean[1000001];
int ans = 0;
StringTokenizer st = new StringTokenizer(fin.readLine());
for(int i = 0; i < n; i++) {
int next = Integer.parseInt(st.nextToken());
v[next] = true;
}
for(int i = v.length - 1; i >= 1; i--) {
if(v[i]) {
continue;
}
int pointer = 2;
ArrayList<Integer> nums = new ArrayList<Integer>();
int prev = -1;
boolean isValid = false;
outer:
while(pointer * i <= v.length - 1) {
if(!v[pointer * i]) {
pointer += 1;
continue;
}
if(prev != -1 && gcd(pointer, prev) == 1) {
isValid = true;
break outer;
}
prev = pointer;
nums.add(pointer);
pointer ++;
}
if(isValid) {
v[i] = true;
ans ++;
}
}
System.out.println(ans);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7069c53ceb3b19d4a44f94b29132d7a7
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class copy {
public static boolean checker(long[] arr, long K, long diff) {
long collect = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > diff)
collect += arr[i] - diff;
}
if (collect >= K)
return true;
else
return false;
}
public static long search(long[] arr, long K, long R) {
long l = 0;
long r = R;
while (l <= r) {
long mid = (l + r) / 2;
if (checker(arr, K, mid)) {
if (checker(arr, K, mid + 1))
l = mid + 1;
else
return mid;
} else
r = mid - 1;
}
return -1;
}
static void sieveOfEratosthenes(int n, ArrayList<Integer> arr, ArrayList<Integer> arr1) {
// 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 * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
int x = 0;
for (int i = 2; i <= n; i++) {
if (prime[i] == true) {
arr.add(i);
}
}
System.out.println(arr.size());
}
public static boolean check(String s, int K, char ch) {
ArrayList<Integer> arr = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ch)
arr.add(i);
}
// if(K==1 && ch=='z')
// System.out.println(arr);
if (arr.size() == 0)
return false;
if (arr.get(0) >= K)
return false;
if (s.length() - 1 - arr.get(arr.size() - 1) >= K)
return false;
for (int i = 1; i < arr.size(); i++) {
if (arr.get(i) - arr.get(i - 1) > K)
return false;
}
return true;
}
public static int check(long N) {
int sum = 0;
while (N > 0) {
sum += N % 10;
N = N / 10;
}
return sum;
}
public static long call(long N) {
long l = 1;
long r = (long) Math.floor(Math.sqrt(N));
while (l <= r) {
long mid = (l + r) / 2;
double left = N / (double) (mid) - mid;
int right = check(mid);
System.out.println(mid + " " + left + " " + right);
if (mid == 10)
System.out.println(left + " " + right);
if (left > right)
l = mid + 1;
else if (right > left)
r = mid - 1;
else
return mid;
}
return -1;
}
public static int path(ArrayList<ArrayList<Integer>> arr, int X, int parent, int[] gold, PriorityQueue<Integer> pq) {
int max = 0;
ArrayList<Integer> ch = new ArrayList<>();
for (int i : arr.get(X)) {
if (i != parent) {
ch.add(path(arr, i, X, gold, pq));
}
}
Collections.sort(ch, Collections.reverseOrder());
for (int i = 1; i < ch.size(); i++)
pq.add(ch.get(i));
if (ch.size() == 0)
return gold[X];
else
return ch.get(0) + gold[X];
}
public static long fac(long N, long mod) {
if (N == 0)
return 1;
if(N==1)
return 1;
return ((N % mod) * (fac(N - 1, mod) % mod)) % mod;
}
public static String form(char ch, int freq) {
String s = "";
for (int i = 1; i <= freq; i++)
s += ch;
return s;
}
static long power(long x, long y, long p) {
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
// System.out.println(modInverse(fac(r,p),p));
// System.out.println(modInverse(fac(n-r,p),p));
return ((fac(n, p) % p * (modInverse(fac(r, p), p)
% p)) % p * (modInverse(fac(n - r, p), p)
% p)) % p;
}
public static boolean check(long[] arr, long time, int M) {
long sum = 0;
int count = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
if (sum >= time) {
++count;
sum = 0;
}
}
if (sum >= time)
++count;
return count >= M;
}
public static int check(ArrayList<Integer> arr, ArrayList<Integer> arr2) {
int l = 0, r = 0, ans = 0;
while (l < arr.size() && r < arr2.size()) {
if (arr.get(l) < arr2.get(r))
++l;
else if (arr.get(l) > arr2.get(r))
++r;
else {
++ans;
++l;
++r;
}
}
return ans;
}
public static int find(int[] parent, int x) {
if (parent[x] == x)
return x;
return find(parent, parent[x]);
}
public static void merge(int[] parent, int[] rank, int x, int y) {
int x1 = find(parent, x);
int y1 = find(parent, y);
if (rank[x1] > rank[y1]) {
parent[y1] = x1;
} else if (rank[y1] > rank[x1]) {
parent[x1] = y1;
} else {
parent[y1] = x1;
rank[x1]++;
}
}
public static int bfs(ArrayList<ArrayList<Integer>> arr, int e1, int e2, int N) {
boolean[] visited = new boolean[N];
visited[0] = true;
int[] dist = new int[N];
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
Arrays.fill(dist, -1);
dist[0] = 0;
while (queue.size() > 0) {
int x = queue.poll();
for (int i : arr.get(x)) {
if (!visited[i] || (e1 == x && e2 == i)) {
System.out.println(x + " " + dist[x]);
dist[i] = dist[x] + 1;
visited[i] = true;
queue.add(i);
}
}
}
return dist[N - 1];
}
public static int binarysearch(ArrayList<Integer> possible, int X, int start) {
int l = start, r = possible.size() - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (possible.get(mid) > X) {
if (mid - 1 >= start && possible.get(mid - 1) > X)
r = mid - 1;
else
return mid;
} else
l = mid + 1;
}
return -1;
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void leftRotatebyOne(int arr[], int n) {
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n - 1] = temp;
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
public static long[][] ncr(int n,int r)
{
long[][] dp=new long[n+1][r+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=r;j++)
{
if(j>i)
continue;
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
return dp;
}
static boolean status=false;
static int x1=-1,y1=-1;
public static int dfs(ArrayList<ArrayList<Integer>> arr,int X,int[] ans,int value,int parent)
{
int xor=ans[X];
for(int i:arr.get(X))
{
if(i!=parent)
{
int x=dfs(arr,i,ans,value,X);
if(x==-1)
return -1;
if(x==value)
{
x1=X;
y1=i;
return -1;
}
xor=xor^x;
}
}
return xor;
}
public static boolean prime(long N)
{
int c=0;
for(int i=2;i*i<=N;i++)
{
if(N%i==0)
++c;
}
return c==0;
}
static int[] c;
static boolean sta=true;
public static int dfs(ArrayList<ArrayList<Integer>> arr,int N,int j,int[] status,boolean[] visited)
{
Queue<Integer> queue=new LinkedList<>();
queue.add(j);
status[j]=1;
visited[j]=true;
int[] color=new int[2];
while(queue.size()>0)
{
int temp=queue.poll();
if(temp<N)
color[status[temp]]++;
for(int i:arr.get(temp))
{
if(visited[i])
{
if(status[i]==status[temp])
return -1;
}
else
{
queue.add(i);
status[i]=1-status[temp];
visited[i]=true;
}
}
}
return Math.max(color[0],color[1]);
}
public static boolean check(String s,int N,long D,long C,long M)
{
int index=s.lastIndexOf('D');
for(int i=0;i<=index;i++)
{
if(s.charAt(i)=='D' && D>0)
{
D-=1;
C+=M;
}
else if(s.charAt(i)=='C' && C>0)
{
C-=1;
}
else
return false;
}
return true;
}
public static boolean checkbounds(int x,int y,int N,int M)
{
return x>=0 && x<N && y>=0 && y<M;
}
public static void dfs(int x,int y,char[][] grid,boolean[][] visited,int N,int M)
{
visited[x][y]=true;
if(checkbounds(x+1,y,N,M) && !visited[x+1][y] && grid[x+1][y]=='.')
dfs(x+1,y,grid,visited,N,M);
if(checkbounds(x-1,y,N,M) && !visited[x-1][y] && grid[x-1][y]=='.')
dfs(x-1,y,grid,visited,N,M);
if(checkbounds(x,y+1,N,M) && !visited[x][y+1] && grid[x][y+1]=='.')
dfs(x,y+1,grid,visited,N,M);
if(checkbounds(x,y-1,N,M) && !visited[x][y-1] && grid[x][y-1]=='.')
dfs(x,y-1,grid,visited,N,M);
}
public static int bin(ArrayList<Integer> arr,int search)
{
int l=0,r=arr.size()-1;
if(search<arr.get(0))
return -1;
if(search>arr.get(r-1))
return r+1;
while(l<=r)
{
int mid=(l+r)/2;
if(arr.get(mid)>search)
{
if(mid-1>=0 && arr.get(mid-1)>search)
r=mid-1;
else
return mid;
}
else
l=mid+1;
}
return -1;
}
public static int mcbc(ArrayList<Long> arr,long search,int N,int lower)
{
if(search>=arr.get(N))
return N;
if(search<=arr.get(lower))
return lower;
int l=lower;
int r=N;
while(l<=r)
{
int mid=(l+r)/2;
if(arr.get(mid)==search)
{
return mid;
}
if(arr.get(mid)>search)
{
if(mid-1>=lower && arr.get(mid-1)>=search)
r=mid-1;
else
{
if(mid-1>=lower)
{
if (Math.abs(search - arr.get(mid)) < Math.abs(search - arr.get(mid - 1)))
return mid;
else
return mid - 1;
}
else
return mid;
}
}
else if(arr.get(mid)<search)
{
if(mid+1<=N && arr.get(mid+1)<=search)
l=mid+1;
else
{
if(mid+1<=N)
{
if (Math.abs(search - arr.get(mid)) < Math.abs(search - arr.get(mid + 1)))
return mid;
else
return mid + 1;
}
else
return mid;
}
}
}
return -1;
}
public static int check(String s,char ch)
{
int l=0,r=s.length()-1;
int c=0;
while(l<r)
{
if(s.charAt(l)!=s.charAt(r))
{
if(s.charAt(l)==ch)
{
++c;
++l;
}
else if(s.charAt(r)==ch)
{
++c;
--r;
}
else
{
return -1;
}
}
else
{
++l;
--r;
}
}
return c;
}
static boolean cycle=false;
static int connected=0;
public static int edges(ArrayList<ArrayList<Integer>> arr,int x,boolean[] visited)
{
++connected;
int sum=arr.get(x).size();
visited[x]=true;
for(int i:arr.get(x))
{
if(!visited[i])
sum+=edges(arr,i,visited);
}
return sum;
}
public static boolean getbounds(int x,int y,int N,int M)
{
return x>=0 && x<N && y>=0 && y<M;
}
public static boolean drag(int[][] arr,int mid)
{
// System.out.println(mid);
for(int i=0;i<arr[0].length;i++)
{
boolean status=false;
for(int j=0;j<arr.length;j++)
{
status=status || arr[j][i]>=mid;
}
if(!status)
return false;
}
for(int i=0;i<arr.length;i++) {
int count=0;
for(int j=0;j<arr[0].length;j++)
{
if(arr[i][j]>=mid)
{
++count;
}
}
if(count>=2)
return true;
}
return false;
}
public static int search(int[][] arr)
{
int l=1;int r=(int)Math.pow(10,9);
while(l<=r)
{
int mid=(l+r)/2;
if(drag(arr,mid))
{
if(mid+1<=Math.pow(10,9) && drag(arr,mid+1))
l=mid+1;
else
return mid;
}
else
r=mid-1;
}
return -1;
}
public static long check(long[][] dp,int x,int y,long mod,int H,int W)
{
if(x>=H || y>=W)
return 0;
if(dp[x][y]!=-1)
return dp[x][y];
long max=0;
max=((max%mod)+(check(dp,x+1,y,mod,H,W)%mod))%mod;
max=((max%mod)+(check(dp,x,y+1,mod,H,W)%mod))%mod;
dp[x][y]=max;
return max;
}
public static String recover(int[][] dp,String s,String t,int x,int y)
{
if(x>=1 && y>=1)
{
String temp="";
if(s.charAt(x-1)==t.charAt(y-1))
{
temp+=s.charAt(x-1);
temp+=recover(dp,s,t,x-1,y-1);
return temp;
}
else
{
if(dp[x-1][y]>dp[x][y-1])
return recover(dp,s,t,x-1,y);
else
return recover(dp,s,t,x,y-1);
}
}
return "";
}
public static long form(long[][] dp,int i,int j,long[] a,long[] b,long max)
{
if(dp[i][j]!=0)
return dp[i][j];
dp[i][j]=form(dp,i+1,j-1,a,b,max)+a[i]*(b[j]-b[i])+a[j]*(b[i]-b[j]);
return dp[i][j];
}
static long min;
public static boolean check(HashMap<Character,Integer> hp, int length,int K)
{
int pairs=0;
for(char ch:hp.keySet())
{
pairs+=hp.get(ch)/2;
}
int pairs_req=(length/2)*K;
return pairs>=pairs_req;
}
public static int solve_left(HashMap<Character,Integer> hp, int K,int N)
{
int l=1,r=N/K;
while(l<=r)
{
int mid=(l+r)/2;
if(check(hp,mid,K))
{
if(mid+1<=N/K && check(hp,mid+1,K))
l=mid+1;
else
return mid;
}
else
r=mid-1;
}
return -1;
}
public static int child_calc(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child)
{
if(arr.get(x).size()==1 && x!=0)
return 1;
int count=0;
for(int i:arr.get(x))
{
if(i!=parent)
{
count+=child_calc(arr,i,x,child);
}
}
child[x]=count;
return count+1;
}
public static void bipartite(ArrayList<ArrayList<Integer>> arr,int x,int parent,ArrayList<Integer> leaf,int d)
{
// System.out.println(x);
if(arr.get(x).size()==1 && x!=0)
{
leaf.add(d+1);
return;
}
for(int i:arr.get(x))
{
if(i!=parent)
{
bipartite(arr,i,x,leaf,d+1);
}
}
}
public static long fill(long[][] dp,int N,int i,int j,int M,int[] arr,long mod)
{
if(i>=N || j>M || j<1)
return 0;
if(arr[i]!=0 && arr[i]!=j)
{
return 0;
}
if(dp[i][j]!=-1)
return dp[i][j];
dp[i][j]=(fill(dp,N,i+1,j+1,M,arr,mod)%mod+fill(dp,N,i+1,j,M,arr,mod)%mod)%mod;
dp[i][j]=(dp[i][j]%mod+fill(dp,N,i+1,j-1,M,arr,mod)%mod)%mod;
return dp[i][j];
}
public static boolean check(ArrayList<Integer> keys,int X)
{
int l=0,r=keys.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(keys.get(mid)==X)
return true;
else if(X>keys.get(mid))
l=mid+1;
else
r=mid-1;
}
return false;
}
public static void shadow(HashMap<String,Integer> hp,ArrayList<ArrayList<Integer>> arr,int x,int parent, int edge)
{
for(int i:arr.get(x))
{
if(i!=parent)
{
hp.put(x+" "+i,5-edge);
hp.put(i+" "+x,5-edge);
shadow(hp,arr,i,x,5-edge);
}
}
}
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// int T=Reader.nextInt();
// A:for(int m=1;m<=T;m++)
// {
int N=Reader.nextInt();
boolean[] status=new boolean[(int)Math.pow(10,6)+1];
int max=Integer.MIN_VALUE;
for(int i=0;i<N;i++)
{
int x=Reader.nextInt();
status[x]=true;
if(x>max)
max=x;
}
int ans=0;
for(int i=(int)max;i>=1;i--)
{
if(!status[i])
{
int x=max/i;
long gcd=-1;
while(i*x>i)
{
if(status[x*i])
{
if(gcd==-1)
gcd=x*i;
else
gcd=gcd(gcd,x*i);
}
--x;
}
if(gcd==i)
++ans;
}
}
output.write(ans+"");
// }
output.flush();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class sortat implements Comparator<div>
{
public int compare(div o1,div o2)
{
return o1.x-o2.x;
}
}
class div {
int x;
int y;
div(int x,int y) {
this.x = x;
this.y=y;
}
}
class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
left=null;
right=null;
this.data=data;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7697a85685e2eb84e24fec04d315fb3e
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
public class D {
public static void main(String[] args) throws IOException {
FastScanner scanner = new FastScanner();
int n = scanner.nextInt();
BitSet numbers = new BitSet();
int maxVal = -1;
for (int i = 0; i < n; i++) {
int ai = scanner.nextInt();
numbers.set(ai);
maxVal = Math.max(maxVal, ai);
}
int ans = 0;
for (int i = maxVal; i >= 1; i--) {
int gcd = -1;
for (int j = i; j <= maxVal; j += i) {
if (numbers.get(j)) {
if (gcd == -1) gcd = j;
else gcd = gcd(gcd, j);
}
}
if (gcd == i) {
if (!numbers.get(gcd)) {
numbers.set(gcd);
ans++;
}
}
}
System.out.println(ans);
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
/**
* Credits: https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
*/
private static class FastScanner implements Closeable {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(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' || c == '\r') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String next() throws IOException {
return next(32);
}
public String next(int len) throws IOException {
byte[] buf = new byte[len];
int ptr = 0;
byte c = read();
while (c <= ' ') c = read();
do {
if (ptr == buf.length) {
buf = Arrays.copyOf(buf, buf.length << 1);
}
buf[ptr++] = c;
} while ((c = read()) > ' ');
if (buf.length == ptr) return new String(buf);
return new String(Arrays.copyOf(buf, ptr));
}
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++];
}
@Override
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
8d637d9ffacddaed5caa533e02530a23
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class _766 {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = 1;
int MAX = (int) 1e6;
while (t-- > 0) {
int n = sc.nextInt();
int [] a = new int[MAX + 1];
for (int i = 0; i < n; i++) a[sc.nextInt()] = 1;
int count = 0;
for (int i = 1; i <= MAX; i++) {
int gcd = 0;
for (int j = i; j <= MAX; j += i) {
if (a[j] == 1) {
gcd = gcd(gcd, j / i);
}
}
if (gcd == 1) {
a[i] = 1;
++count;
}
}
out.println(count - n);
}
out.close();
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
015707956f3012cc3e5367453942ca5c
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
*
* @author eslam
*/
public class Solution {
// Beginning of the solution
static Kattio input = new Kattio();
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>();
static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>();
static ArrayList<LinkedList<String>> allprems = new ArrayList<>();
static ArrayList<Long> luc = new ArrayList<>();
static long mod = (long) (1e9 + 7);
static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}};
static long dp[][][];
static double cmp = 1e-7;
static final double pi = 3.14159265359;
static int[] ans;
public static void main(String[] args) throws IOException {
// Kattio input = new Kattio("input");
// BufferedWriter log = new BufferedWriter(new FileWriter(f));
int test = 1;//input.nextInt();
loop:
for (int co = 1; co <= test; co++) {
int n = input.nextInt();
int res = 0;
int fre[] = new int[(int) 1e6 + 9];
for (int i = 0; i < n; i++) {
fre[input.nextInt()]++;
}
for (int i = 1; i <= 1e6; i++) {
long gcd = 0;
if (fre[i]==1) {
continue;
}
for (int j = i + i; j <= 1e6; j += i) {
if (fre[j]==1) {
gcd = GCD(j, gcd);
}
}
if (gcd == i) {
res++;
}
}
log.write(res + "\n");
}
log.flush();
}
static void dfs(int node, ArrayList<Integer> g[], boolean vi[], boolean ca, TreeMap<pair, Integer> edges) {
vi[node] = true;
for (Integer ch : g[node]) {
if (!vi[ch]) {
if (ca) {
ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 2;
} else {
ans[edges.get(new pair(Math.max(node, ch), Math.min(node, ch)))] = 5;
}
dfs(ch, g, vi, !ca, edges);
ca = !ca;
}
}
}
static long f(long x) {
return (long) ((x * (x + 1) / 2) % mod);
}
static long Sub(long x, long y) {
long z = x - y;
if (z < 0) {
z += mod;
}
return z;
}
static long add(long a, long b) {
a += b;
if (a >= mod) {
a -= mod;
}
return a;
}
static long mul(long a, long b) {
return (long) ((long) a * b % mod);
}
static long powlog(long base, long power) {
if (power == 0) {
return 1;
}
long x = powlog(base, power / 2);
x = mul(x, x);
if ((power & 1) == 1) {
x = mul(x, base);
}
return x;
}
static long modinv(long x) {
return fast_pow(x, mod - 2, mod);
}
static long Div(long x, long y) {
return mul(x, modinv(y));
}
static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) {
vi[r][c] = true;
for (int i = 0; i < 4; i++) {
int nr = grid[0][i] + r;
int nc = grid[1][i] + c;
if (isValid(nr, nc, a.length, a[0].length)) {
if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) {
floodFill(nr, nc, a, vi, w, d);
}
}
}
}
static boolean isdigit(char ch) {
return ch >= '0' && ch <= '9';
}
static boolean lochar(char ch) {
return ch >= 'a' && ch <= 'z';
}
static boolean cachar(char ch) {
return ch >= 'A' && ch <= 'Z';
}
static class Pa {
long x;
long y;
public Pa(long x, long y) {
this.x = x;
this.y = y;
}
}
static long sqrt(long v) {
long max = (long) 4e9;
long min = 0;
long ans = 0;
while (max >= min) {
long mid = (max + min) / 2;
if (mid * mid > v) {
max = mid - 1;
} else {
ans = mid;
min = mid + 1;
}
}
return ans;
}
static long cbrt(long v) {
long max = (long) 3e6;
long min = 0;
long ans = 0;
while (max >= min) {
long mid = (max + min) / 2;
if (mid * mid > v) {
max = mid - 1;
} else {
ans = mid;
min = mid + 1;
}
}
return ans;
}
static void prefixSum2D(long arr[][]) {
for (int i = 0; i < arr.length; i++) {
prefixSum(arr[i]);
}
for (int i = 0; i < arr[0].length; i++) {
for (int j = 1; j < arr.length; j++) {
arr[j][i] += arr[j - 1][i];
}
}
}
public static long baseToDecimal(String w, long base) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(base, l);
r = r + x;
l++;
}
return r;
}
static int bs(int v, ArrayList<Integer> a) {
int max = a.size() - 1;
int min = 0;
int ans = 0;
while (max >= min) {
int mid = (max + min) / 2;
if (a.get(mid) >= v) {
ans = a.size() - mid;
max = mid - 1;
} else {
min = mid + 1;
}
}
return ans;
}
static Comparator<tri> cmpTri() {
Comparator<tri> c = new Comparator<tri>() {
@Override
public int compare(tri o1, tri o2) {
if (o1.x > o2.x) {
return 1;
} else if (o1.x < o2.x) {
return -1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.z > o2.z) {
return 1;
} else if (o1.z < o2.z) {
return -1;
} else {
return 0;
}
}
}
}
};
return c;
}
static Comparator<pair> cmpPair2() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
if (o1.x > o2.x) {
return -1;
} else if (o1.x < o2.x) {
return 1;
} else {
return 0;
}
}
}
};
return c;
}
static Comparator<pair> cmpPair() {
Comparator<pair> c = new Comparator<pair>() {
@Override
public int compare(pair o1, pair o2) {
if (o1.x > o2.x) {
return -1;
} else if (o1.x < o2.x) {
return 1;
} else {
if (o1.y > o2.y) {
return 1;
} else if (o1.y < o2.y) {
return -1;
} else {
return 0;
}
}
}
};
return c;
}
static class rec {
long x1;
long x2;
long y1;
long y2;
public rec(long x1, long y1, long x2, long y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public long getArea() {
return (x2 - x1) * (y2 - y1);
}
}
static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) {
return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1];
}
public static int[][] bfs(int i, int j, String w[]) {
Queue<pair> q = new ArrayDeque<>();
q.add(new pair(i, j));
int dis[][] = new int[w.length][w[0].length()];
for (int k = 0; k < w.length; k++) {
Arrays.fill(dis[k], -1);
}
dis[i][j] = 0;
while (!q.isEmpty()) {
pair p = q.poll();
int cost = dis[p.x][p.y];
for (int k = 0; k < 4; k++) {
int nx = p.x + grid[0][k];
int ny = p.y + grid[1][k];
if (isValid(nx, ny, w.length, w[0].length())) {
if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') {
q.add(new pair(nx, ny));
dis[nx][ny] = cost + 1;
}
}
}
}
return dis;
}
public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException {
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
while (q-- > 0) {
int x = input.nextInt();
int y = input.nextInt();
a[x].add(y);
a[y].add(x);
}
}
public static boolean isValid(int i, int j, int n, int m) {
return (i > -1 && i < n) && (j > -1 && j < m);
}
// present in the left and right indices
public static int[] swap(int data[], int left, int right) {
// Swap the data
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// Return the updated array
return data;
}
// Function to reverse the sub-array
// starting from left to the right
// both inclusive
public static int[] reverse(int data[], int left, int right) {
// Reverse the sub-array
while (left < right) {
int temp = data[left];
data[left++] = data[right];
data[right--] = temp;
}
// Return the updated array
return data;
}
// Function to find the next permutation
// of the given integer array
public static boolean findNextPermutation(int data[]) {
// If the given dataset is empty
// or contains only one element
// next_permutation is not possible
if (data.length <= 1) {
return false;
}
int last = data.length - 2;
// find the longest non-increasing suffix
// and find the pivot
while (last >= 0) {
if (data[last] < data[last + 1]) {
break;
}
last--;
}
// If there is no increasing pair
// there is no higher order permutation
if (last < 0) {
return false;
}
int nextGreater = data.length - 1;
// Find the rightmost successor to the pivot
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
// Swap the successor and the pivot
data = swap(data, nextGreater, last);
// Reverse the suffix
data = reverse(data, last + 1, data.length - 1);
// Return true as the next_permutation is done
return true;
}
// public static pair[] dijkstra(int node, ArrayList<pair> a[]) {
// PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() {
// @Override
// public int compare(tri o1, tri o2) {
// if (o1.y > o2.y) {
// return 1;
// } else if (o1.y < o2.y) {
// return -1;
// } else {
// return 0;
// }
// }
// });
// q.add(new tri(node, 0, -1));
// pair distance[] = new pair[a.length];
// while (!q.isEmpty()) {
// tri p = q.poll();
// int cost = p.y;
// if (distance[p.x] != null) {
// continue;
// }
// distance[p.x] = new pair(p.z, cost);
// ArrayList<pair> nodes = a[p.x];
// for (pair node1 : nodes) {
// if (distance[node1.x] == null) {
// tri pa = new tri(node1.x, cost + node1.y, p.x);
// q.add(pa);
// }
// }
// }
// return distance;
// }
public static String revs(String w) {
String ans = "";
for (int i = w.length() - 1; i > -1; i--) {
ans += w.charAt(i);
}
return ans;
}
public static boolean isPalindrome(String w) {
for (int i = 0; i < w.length() / 2; i++) {
if (w.charAt(i) != w.charAt(w.length() - i - 1)) {
return false;
}
}
return true;
}
public static void getPowerSet(Queue<Integer> a) {
int n = a.poll();
if (!a.isEmpty()) {
getPowerSet(a);
}
int s = powerSet.size();
for (int i = 0; i < s; i++) {
ArrayList<Integer> ne = new ArrayList<>();
ne.add(n);
for (int j = 0; j < powerSet.get(i).size(); j++) {
ne.add(powerSet.get(i).get(j));
}
powerSet.add(ne);
}
ArrayList<Integer> p = new ArrayList<>();
p.add(n);
powerSet.add(p);
}
public static int getlo(int va) {
int v = 1;
while (v <= va) {
if ((va&v) != 0) {
return v;
}
v <<= 1;
}
return 0;
}
static long fast_pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a) % mod;
p /= 2;
} else {
res = (res * a) % mod;
p--;
}
}
return res;
}
public static int countPrimeInRange(int n, boolean isPrime[]) {
int cnt = 0;
Arrays.fill(isPrime, true);
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (int j = i * 2; j <= n; j += i) {
isPrime[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
cnt++;
}
}
return cnt;
}
public static void create(long num) {
luc.add(num);
if (num > power(10, 9)) {
return;
}
create(num * 10 + 4);
create(num * 10 + 7);
}
public static long ceil(long a, long b) {
return (a + b - 1) / b;
}
public static long round(long a, long b) {
if (a < 0) {
return (a - b / 2) / b;
}
return (a + b / 2) / b;
}
public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) {
if (l.size() == st.size()) {
allprems.add(l);
}
for (int i = 0; i < st.size(); i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<String> nl = new LinkedList<>();
for (String x : l) {
nl.add(x);
}
nl.add(st.get(i));
allPremutationsst(nl, visited, st);
visited[i] = false;
}
}
}
public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) {
if (l.size() == a.length) {
allprem.add(l);
}
for (int i = 0; i < a.length; i++) {
if (!visited[i]) {
visited[i] = true;
LinkedList<Integer> nl = new LinkedList<>();
for (Integer x : l) {
nl.add(x);
}
nl.add(a[i]);
allPremutations(nl, visited, a);
visited[i] = false;
}
}
}
public static int binarySearch(long[] a, long value) {
int l = 0;
int r = a.length - 1;
while (l <= r) {
int m = (l + r) / 2;
if (a[m] == value) {
return m;
} else if (a[m] > value) {
r = m - 1;
} else {
l = m + 1;
}
}
return -1;
}
public static void reverse(int l, int r, char ch[]) {
for (int i = 0; i < r / 2; i++) {
char c = ch[i];
ch[i] = ch[r - i - 1];
ch[r - i - 1] = c;
}
}
public static long logK(long v, long k) {
int ans = 0;
while (v > 1) {
ans++;
v /= k;
}
return ans;
}
public static long power(long a, long p) {
long res = 1;
while (p > 0) {
if (p % 2 == 0) {
a = (a * a);
p /= 2;
} else {
res = (res * a);
p--;
}
}
return res;
}
public static long get(long max, long x) {
if (x == 1) {
return max;
}
int cnt = 0;
while (max > 0) {
cnt++;
max /= x;
}
return cnt;
}
public static int numOF0(long v) {
long x = 1;
int cnt = 0;
while (x <= v) {
if ((x & v) == 0) {
cnt++;
}
x <<= 1;
}
return cnt;
}
public static int log2(double n) {
int cnt = 0;
while (n > 1) {
n /= 2;
cnt++;
}
return cnt;
}
public static int[] bfs(int node, ArrayList<Integer> a[]) {
Queue<Integer> q = new LinkedList<>();
q.add(node);
int distances[] = new int[a.length];
Arrays.fill(distances, -1);
distances[node] = 0;
while (!q.isEmpty()) {
int parent = q.poll();
ArrayList<Integer> nodes = a[parent];
int cost = distances[parent];
for (Integer node1 : nodes) {
if (distances[node1] == -1) {
q.add(node1);
distances[node1] = cost + 1;
}
}
}
return distances;
}
public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) {
boolean ca = true;
while (n % 2 == 0) {
if (ca) {
if (h.get(2) == null) {
h.put(2, new ArrayList<>());
}
h.get(2).add(ind);
ca = false;
}
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
ca = true;
while (n % i == 0) {
if (ca) {
if (h.get(i) == null) {
h.put(i, new ArrayList<>());
}
h.get(i).add(ind);
ca = false;
}
n /= i;
}
if (n < i) {
break;
}
}
if (n > 2) {
if (h.get(n) == null) {
h.put(n, new ArrayList<>());
}
h.get(n).add(ind);
}
}
// end of solution
public static BigInteger ff(long n) {
if (n <= 1) {
return BigInteger.ONE;
}
long t = n - 1;
BigInteger b = new BigInteger(t + "");
BigInteger ans = new BigInteger(n + "");
while (t > 1) {
ans = ans.multiply(b);
b = b.subtract(BigInteger.ONE);
t--;
}
return ans;
}
public static long factorial(long n) {
if (n <= 1) {
return 1;
}
long t = n - 1;
while (t > 1) {
n = mod((mod(n, mod) * mod(t, mod)), mod);
t--;
}
return n;
}
public static long rev(long n) {
long t = n;
long ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans;
}
public static boolean isPalindrome(int n) {
int t = n;
int ans = 0;
while (t > 0) {
ans = ans * 10 + t % 10;
t /= 10;
}
return ans == n;
}
static class tri {
int x, y;
long z;
public tri(int x, int y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
static boolean isPrime(long num) {
if (num == 1) {
return false;
}
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num == 3) {
return true;
}
for (long i = 3; i * i <= num; i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void prefixSum(long[] a) {
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
}
public static void suffixSum(long[] a) {
for (int i = a.length - 2; i > -1; i--) {
a[i] = a[i] + a[i + 1];
}
}
static long mod(long a, long b) {
long r = a % b;
return r < 0 ? r + b : r;
}
public static long binaryToDecimal(String w) {
long r = 0;
long l = 0;
for (int i = w.length() - 1; i > -1; i--) {
long x = (w.charAt(i) - '0') * (long) Math.pow(2, l);
r = r + x;
l++;
}
return r;
}
public static String decimalAnyBase(long n, long base) {
String w = "";
while (n > 0) {
w = n % base + w;
n /= base;
}
return w;
}
public static String decimalToBinary(long n) {
String w = "";
while (n > 0) {
w = n % 2 + w;
n /= 2;
}
return w;
}
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
return false;
}
}
return true;
}
public static void print(long[] a) throws IOException {
for (int i = 0; i < a.length; i++) {
log.write(a[i] + " ");
}
log.write("\n");
}
public static void read(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = input.nextInt();
}
}
static class gepair {
long x;
long y;
public gepair(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pair {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
static class pai {
long x;
int y;
public pai(long x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return x + " " + y;
}
}
public static long LCM(long x, long y) {
return x / GCD(x, y) * y;
}
public static long GCD(long x, long y) {
if (y == 0) {
return x;
}
return GCD(y, x % y);
}
public static void simplifyTheFraction(int a, int b) {
long GCD = GCD(a, b);
System.out.println(a / GCD + " " + b / GCD);
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName));
}
// returns null if no more input
String nextLine() {
String str = "";
try {
str = r.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(r.readLine());
}
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
801bff805837a512dfcb2b4770d8c30a
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class DebugApp {
static int a[]=new int[1000005];
public static void main(String[] args) {
int n;
Scanner x=new Scanner(System.in);
n=x.nextInt();
int mx=0;
for(int i=1;i<=n;i++)
{
int xx;
xx=x.nextInt();
a[xx]=1;
if(mx<=xx)
{
mx=xx;
}
}
int ans=0;
for(int i=1;i<=mx;i++)
{
if(a[i]!=0)continue;
int gcd=-1;
for(int j=i*2;j<=mx;j+=i) {
if (a[j] == 0) continue;
if (gcd == -1)
{
gcd = j;
} else {
gcd = _gcd(gcd, j);
}
}
if(gcd==i)ans++;
}
System.out.println(ans);
}
static int _gcd(int x,int y)
{
return y==0?x:_gcd(y,x%y);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
c2461f99b729087187efee365408bbd3
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.cert.X509CRL;
import java.util.*;
import java.lang.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static String OUTPUT = "";
//global
//private final static long BASE = 998244353L;
private final static int ALPHABET = (int)('z') - (int)('a') + 1;
private final static long BASE = 1000000007l;
private final static int INF_I = (1<<31)-1;
private final static long INF_L = (1l<<63)-1;
private final static int MAXN = 1000100;
private final static int MAXK = 31;
private final static int[] DX = {-1,0,1,0};
private final static int[] DY = {0,1,0,-1};
static void solve() {
int ntest = 1;
//int ntest = readInt();
for (int test=0;test<ntest;test++) {
int N = readInt();
int[] A = readIntArray(N);
int[] cnt = new int[MAXN];
boolean[] used = new boolean[MAXN];
for (int i=0;i<N;i++) {
cnt[A[i]] = 1;
used[A[i]] = true;
}
for (int x=1; x<MAXN; x++)
for (int y=2*x; y<MAXN; y+=x)
cnt[x] += cnt[y];
int ans=0;
for (int x=1;x<MAXN;x++) {
if (used[x] || cnt[x]==0) continue;
boolean isOk = true;
for (int y=2*x; y<MAXN; y+=x)
if (cnt[y] == cnt[x]) {
isOk = false;
break;
}
if (isOk) ans++;
}
out.println(ans);
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
if (INPUT=="") {
is = System.in;
} else {
File file = new File(INPUT);
is = new FileInputStream(file);
}
if (OUTPUT == "") out = new PrintWriter(System.out);
else out = new PrintWriter(OUTPUT);
solve();
out.flush();
long G = System.currentTimeMillis();
}
private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> {
private T x;
private T y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {return x;}
public T getY() {return y;}
@Override
public int compareTo(Point<T> o) {
int cmp = x.compareTo(o.getX());
if (cmp==0) return y.compareTo(o.getY());
return cmp;
}
}
private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> {
public ClassComparator() {}
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
public ListComparator() {}
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double readDouble() { return Double.parseDouble(readString()); }
private static char readChar() { return (char)skip(); }
private static String readString()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] readChar(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readTable(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = readChar(m);
return map;
}
private static int[] readIntArray(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = readInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i=0;i<n;i++) a[i] = readLong();
return a;
}
private static int readInt()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long readLong()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
c57e1081610666d7a0775a7b245486f4
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
public class Main
{
public static void main(String[] args)
{
Input input = new Input();
Output output = new Output();
boolean[] a = new boolean[1000001];
for (int i = input.nextInt(); i > 0; i--)
a[input.nextInt()] = true;
int count = 0;
for (int i = 1; i < (a.length + 1) / 2; i++)
{
if (!a[i])
{
boolean valid = false;
int gcd;
for (gcd = i; gcd < a.length; gcd += i)
{
if (a[gcd])
{
valid = true;
break;
}
}
if (valid)
{
for (int j = gcd + i; j < a.length; j += i)
{
if (a[j])
gcd = Algebra.gcd(gcd, j);
}
if (gcd == i)
count++;
}
}
}
output.append(count).appendNewLine();
output.flush();
}
}
class Input
{
private final byte[] buffer;
private int pos;
public Input()
{
try
{
buffer = new byte[System.in.available() + 1];
buffer[buffer.length - 1] = '\n';
System.in.read(buffer);
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
public byte[] next(int n)
{
byte[] bytes = new byte[n];
while (true)
{
byte b = buffer[pos++];
if (b != '\r' && b != '\n')
{
bytes[0] = b;
break;
}
}
for (int i = 1; i < n; i++)
bytes[i] = buffer[pos++];
return bytes;
}
public byte[] next()
{
int from;
while (true)
{
byte b = buffer[pos++];
if (b != ' ' && b != '\r' && b != '\n')
{
from = pos;
break;
}
}
while (true)
{
byte b = buffer[pos++];
if (b == ' ' || b == '\r' || b == '\n')
break;
}
byte[] bytes = new byte[pos - from];
from--;
for (int i = 0; i < bytes.length; i++, from++)
bytes[i] = buffer[from];
return bytes;
}
public byte[] nextLine()
{
int from = pos;
while (true)
{
byte b = buffer[pos++];
if (b == '\r')
{
pos++;
break;
}
else if (b == '\n')
break;
}
byte[] bytes = new byte[pos - from - 1];
for (int i = 0; i < bytes.length; i++, from++)
bytes[i] = buffer[from];
return bytes;
}
public int nextInt()
{
int n;
boolean positive;
while (true)
{
byte b = buffer[pos++];
if (b == '-')
{
positive = false;
n = buffer[pos++] - '0';
break;
}
else if (b >= '0' && b <= '9')
{
positive = true;
n = b - '0';
break;
}
}
while (true)
{
byte b = buffer[pos++];
if (b >= '0' && b <= '9')
n = n * 10 + b - '0';
else
return positive ? n : -n;
}
}
public long nextLong()
{
long n;
boolean positive;
while (true)
{
byte b = buffer[pos++];
if (b == '-')
{
positive = false;
n = buffer[pos++] - '0';
break;
}
else if (b >= '0' && b <= '9')
{
positive = true;
n = b - '0';
break;
}
}
while (true)
{
byte b = buffer[pos++];
if (b >= '0' && b <= '9')
n = n * 10 + b - '0';
else
return positive ? n : -n;
}
}
public double nextDouble()
{
long n, m, o;
boolean positive;
while (true)
{
byte b = buffer[pos++];
if (b == '-')
{
positive = false;
n = buffer[pos++] - '0';
break;
}
else if (b >= '0' && b <= '9')
{
positive = true;
n = b - '0';
break;
}
}
while (true)
{
byte b = buffer[pos++];
if (b >= '0' && b <= '9')
n = n * 10 + b - '0';
else
break;
}
m = buffer[pos++] - '0';
o = 1;
while (true)
{
byte b = buffer[pos++];
if (b >= '0' && b <= '9')
{
m = m * 10 + b - '0';
o *= 10;
}
else
return (positive ? n : -n) + (double)m / o;
}
}
}
class Output
{
private static final int BUFFER_SIZE = 1048576;
private final byte[] buffer = new byte[BUFFER_SIZE];
private int pos;
public Output append(String s)
{
int length = s.length();
ensureCapacity(length);
for (int i = 0; i < length; i++)
buffer[pos++] = (byte)s.charAt(i);
return this;
}
public Output append(byte[] bytes)
{
ensureCapacity(bytes.length);
for (byte b: bytes)
buffer[pos++] = b;
return this;
}
public Output append(char c)
{
ensureCapacity(1);
buffer[pos++] = (byte)c;
return this;
}
public Output append(int i)
{
return append(Integer.toString(i));
}
public Output append(long l)
{
return append(Long.toString(l));
}
public Output append(double d)
{
return append(Double.toString(d));
}
public void appendNewLine()
{
ensureCapacity(1);
buffer[pos++] = '\n';
}
public void flush()
{
System.out.write(buffer, 0, pos);
pos = 0;
}
private void ensureCapacity(int n)
{
if (BUFFER_SIZE - pos < n)
flush();
}
}
class Algebra
{
private Algebra() {}
public static int modPow(int n, int exponent, int m)
{
long result = 1;
for (long i = 1, j = n % m; i <= exponent; i <<= 1, j = j * j % m)
{
if ((i & exponent) != 0)
result = result * j % m;
}
return (int)result;
}
public static int modInverse(int n, int p)
{
return modPow(n, p - 2, p);
}
public static int gcd(int a, int b)
{
if (a < b)
{
int temp = a;
a = b;
b = temp;
}
while (true)
{
a %= b;
if (a == 0)
return b;
else
{
int temp = a;
a = b;
b = temp;
}
}
}
public static long gcd(long a, long b)
{
if (a < b)
{
long temp = a;
a = b;
b = temp;
}
while (true)
{
a %= b;
if (a == 0)
return b;
else
{
long temp = a;
a = b;
b = temp;
}
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
e0bea20429092c998dc5d63fd917243e
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class GCDProblem {
static Scanner sc = new Scanner(System.in);
static List<Integer> primes;
public static void main(String[] args) {
// TODO Auto-generated method st
int n = sc.nextInt();
int [] arr = new int [n];
int max = 0;
for (int i = 0; i < arr.length; ++i) {
arr[i] = sc.nextInt();
max = Math.max(max, arr[i]);
}
++max;
boolean [] visited = new boolean[max];
int [] vals = new int [max];
int [] count = new int [max];
int [] gcds = new int [max];
for (int num : arr) {
visited[num] = true;
}
for (int i = 1; i < max; ++i) {
if (visited[i]) continue;
for (int j = i; j < max; j += i) {
if (!visited[j]) continue;
count[i]++;
if (count[i] == 1) {
gcds[i] = j;
}else {
gcds[i] = gcd(gcds[i], j);
}
}
}
int total = 0;
for (int i = 1; i < max; ++i) {
if (!visited[i] && count[i] > 1 && gcds[i] == i)
++total;
}
System.out.println(total);
}
private static int gcd(int a , int b) {
if (a % b == 0)
return b;
return gcd(b, a % b);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
c969dafd66bf020ae8c6b0b216d631fc
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
public class Main{
public static int gcd(int a,int b){
int mx = Math.max(a,b);
int mn = Math.min(a,b);
if(mn == 0){
return mx;
}
return gcd(mn,mx%mn);
}
public static void main(String[]args){
Scanner at = new Scanner(System.in);
int n = at.nextInt();
boolean []vis = new boolean[1000003];
int count = 0;
for(int i = 0;i<n;i++){
int temp = at.nextInt();
vis[temp] = true;
}
for(int i = 1;i<vis.length;i++){
int g = 0;
for(int j = i;j<vis.length;j += i){
if(vis[j]){
g = gcd(g,j);
}
}
if(g == i){
vis[i] = true;
count++;
}
}
System.out.println(count-n);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
ce8261937d46562a716bb7781bd98808
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
// JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.stream.*;
import java.lang.*;
import java.math.BigInteger;
import java.rmi.ConnectIOException;
import java.text.DecimalFormat;
import java.io.*;
public class Eshan {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.0000000");
final static int mod = (int) (1e9 + 7);
final static int MAX = Integer.MAX_VALUE;
final static int MIN = Integer.MIN_VALUE;
final static long INF = Long.MAX_VALUE;
final static long NEG_INF = Long.MIN_VALUE;
static Random rand = new Random();
// ======================= MAIN ==================================
public static void main(String[] args) throws IOException {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// ==== start ====
input();
int t = 1;
// int t = readInt();
preprocess();
while (t-- > 0) {
solve();
}
out.flush();
// ==== end ====
if (!oj)
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
private static void solve() throws IOException {
int n = readInt(), count = 0;
boolean[] present = new boolean[(int) 1e6 + 1];
for (int i = 0; i < n; i++)
present[readInt()] = true;
for (int i = (int) 1e6; i > 0; i--) {
int gcd = 0;
for (int j = i; j <= 1e6; j += i) {
if (present[j])
gcd = gcd(gcd, j);
}
if (i == gcd) {
count++;
present[i] = true;
}
}
out.println(count - n);
}
private static void preprocess() {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac Eshan.java
// java Eshan
// javac Eshan.java && java Eshan
// ==================== CUSTOM CLASSES ================================
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair o) {
if (this.first != o.first)
return this.second - o.second;
return this.first - o.first;
}
}
static class DequeNode {
DequeNode prev, next;
int val;
DequeNode(int val) {
this.val = val;
}
DequeNode(int val, DequeNode prev, DequeNode next) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
// ======================= FOR INPUT ==================================
private static void input() {
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
static int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = readInt();
return arr;
}
static int[][] read2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = readIntArray(m);
return arr;
}
static List<Integer> readIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(readInt());
return list;
}
static long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = readLong();
return arr;
}
static long[][] read2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = readLongArray(m);
return arr;
}
static List<Long> readLongList(int n) throws IOException {
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(readLong());
return list;
}
static char[] readCharArray(int n) throws IOException {
return readString().toCharArray();
}
static char[][] readMatrix(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = readCharArray(m);
return mat;
}
// ========================= FOR OUTPUT ==================================
private static void printIList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIArray(arr[i]);
}
private static void printLArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLArray(arr[i]);
}
// ====================== TO CHECK IF STRING IS NUMBER ========================
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// ==================== FASTER SORT ================================
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// ==================== MATHEMATICAL FUNCTIONS ===========================
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static long power(long a, long b) {
if (b == 0)
return 1L;
long ans = power(a, b >> 1);
ans *= ans;
if ((b & 1) == 1)
ans *= a;
return ans;
}
private static int mod_power(int a, int b, int mod) {
if (b == 0)
return 1;
int temp = mod_power(a, b >> 1, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static int multiply(int a, int b) {
return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod);
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
private static long nCr(long n, long r) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans *= i;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans;
}
// ==================== Primes using Seive =====================
private static List<Integer> getPrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i)
prime[j] = false;
}
}
// return prime;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= n; i++)
if (prime[i])
list.add(i);
return list;
}
private static int[] SeivePrime(int n) {
int[] primes = new int[n];
for (int i = 0; i < n; i++)
primes[i] = i;
for (int i = 2; i * i < n; i++) {
if (primes[i] != i)
continue;
for (int j = i * i; j < n; j += i) {
if (primes[j] == j)
primes[j] = i;
}
}
return primes;
}
// ==================== STRING FUNCTIONS ================================
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// ==================== LIS & LNDS ================================
private static int LIS(int arr[], int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// =============== Lower Bound & Upper Bound ===========
// less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(List<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(List<Long> list, long val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== UNION FIND =====================
private static int find(int x, int[] parent) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x], parent);
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly)
return false;
if (rank[lx] > rank[ly])
parent[ly] = lx;
else if (rank[lx] < rank[ly])
parent[lx] = ly;
else {
parent[lx] = ly;
rank[ly]++;
}
return true;
}
// ==================== SEGMENT TREE (RANGE SUM) =====================
public static class SegmentTree {
int n;
int[] arr, tree, lazy;
SegmentTree(int arr[]) {
this.arr = arr;
this.n = arr.length;
this.tree = new int[(n << 2)];
this.lazy = new int[(n << 2)];
build(1, 0, n - 1);
}
void build(int id, int start, int end) {
if (start == end)
tree[id] = arr[start];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
build(left, start, mid);
build(right, mid + 1, end);
tree[id] = tree[left] + tree[right];
}
}
void update(int l, int r, int val) {
update(1, 0, n - 1, l, r, val);
}
void update(int id, int start, int end, int l, int r, int val) {
distribute(id, start, end);
if (end < l || r < start)
return;
if (start == end)
tree[id] += val;
else if (l <= start && end <= r) {
lazy[id] += val;
distribute(id, start, end);
} else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
update(left, start, mid, l, r, val);
update(right, mid + 1, end, l, r, val);
tree[id] = tree[left] + tree[right];
}
}
int query(int l, int r) {
return query(1, 0, n - 1, l, r);
}
int query(int id, int start, int end, int l, int r) {
if (end < l || r < start)
return 0;
distribute(id, start, end);
if (start == end)
return tree[id];
else if (l <= start && end <= r)
return tree[id];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r);
}
}
void distribute(int id, int start, int end) {
if (start == end)
tree[id] += lazy[id];
else {
tree[id] += lazy[id] * (end - start + 1);
lazy[(id << 1)] += lazy[id];
lazy[(id << 1) + 1] += lazy[id];
}
lazy[id] = 0;
}
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
public void insert(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
curr.children[ch - 'a'] = new Node();
curr = curr.children[ch - 'a'];
}
curr.isEnd = true;
}
public boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
return false;
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// ==================== FENWICK TREE ================================
static class FT {
long[] tree;
int n;
FT(int[] arr, int n) {
this.n = n;
this.tree = new long[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
long query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
long getSum(int idx) {
long ans = 0L;
while (idx > 0) {
ans += tree[idx];
idx -= idx & -idx;
}
return ans;
}
}
// ==================== BINARY INDEX TREE ================================
static class BIT {
long[][] tree;
int n, m;
BIT(int[][] mat, int n, int m) {
this.n = n;
this.m = m;
tree = new long[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
update(i, j, mat[i - 1][j - 1]);
}
}
}
void update(int x, int y, int val) {
while (x <= n) {
int t = y;
while (t <= m) {
tree[x][t] += val;
t += t & -t;
}
x += x & -x;
}
}
long query(int x1, int y1, int x2, int y2) {
return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1);
}
long getSum(int x, int y) {
long ans = 0L;
while (x > 0) {
int t = y;
while (t > 0) {
ans += tree[x][t];
t -= t & -t;
}
x -= x & -x;
}
return ans;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
2b9527277de549bb75497f76930c011d
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
boolean[] visited = new boolean[1000001];
for (int i = 0; i < n; i++) {
int x = in.nextInt();
visited[x] = true;
}
int ans = 0;
for (int i = 1000000; i >= 1; i--) {
if (visited[i]) continue;
int now = -1;
for (int j = i; j <= 1000000; j += i) {
if (!visited[j]) continue;
if (now == -1) {
now = j;
} else {
now = gcd(now, j);
}
}
if (now == i) {
visited[i] = true;
ans++;
}
}
out.println(ans);
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long add_mod(long... longs) {
long ans = 0;
for (long now : longs) {
ans = (ans + now) % mod;
if (ans < 0) ans += mod;
}
return ans;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static int[] read_int_array(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextInt();
}
return a;
}
private static long[] read_long_array(int len) throws IOException {
long[] a = new long[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextLong();
}
return a;
}
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
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 {
din.close();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9a888c801511463e3b6204167b6fced6
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class NotAdding {
public static int gcd(int a, int b) {
if (b==0) return a;
return gcd(b, a%b);
}
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int n = in.nextInt();
int[] arr = new int[n];
int[] exists = new int[1000001];
for (int i=0; i<n; i++) {
arr[i] = in.nextInt();
exists[arr[i]] = 1;
}
int ans = 0;
for (int i=1; i<1000001; i++) {
int gcd = 0;
for (int j=i; j<1000001; j+=i) {
if (exists[j]>0) gcd = gcd(gcd, j);
}
if (gcd==i) {
exists[i] = 1;
ans++;
}
}
System.out.println(ans-n);
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter pr;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
pr = new PrintWriter(System.out);
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
3c08795fc938ce7d9bbbc4e3ed84c387
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
private static void run() throws IOException {
int n = in.nextInt();
boolean[] visited = new boolean[1000001];
for (int i = 0; i < n; i++) {
int x = in.nextInt();
visited[x] = true;
}
int ans = 0;
for (int i = 1000000; i >= 1; i--) {
if (visited[i]) continue;
int now = -1;
for (int j = i; j <= 1000000; j += i) {
if (!visited[j]) continue;
if (now == -1) {
now = j;
} else {
now = gcd(now, j);
}
}
if (now == i) {
visited[i] = true;
ans++;
}
}
out.println(ans);
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(new OutputStreamWriter(System.out));
// int t = in.nextInt();
// for (int i = 0; i < t; i++) {
// }
run();
out.flush();
in.close();
out.close();
}
private static int gcd(int a, int b) {
if (a == 0 || b == 0)
return 0;
while (b != 0) {
int tmp;
tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static final long mod = 1000000007;
static long pow_mod(long a, long b) {
long result = 1;
while (b != 0) {
if ((b & 1) != 0) result = (result * a) % mod;
a = (a * a) % mod;
b >>= 1;
}
return result;
}
private static long add_mod(long... longs) {
long ans = 0;
for (long now : longs) {
ans = (ans + now) % mod;
if (ans < 0) ans += mod;
}
return ans;
}
private static long multiplied_mod(long... longs) {
long ans = 1;
for (long now : longs) {
ans = (ans * now) % mod;
}
return ans;
}
@SuppressWarnings("FieldCanBeLocal")
private static Reader in;
private static PrintWriter out;
private static int[] read_int_array(int len) throws IOException {
int[] a = new int[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextInt();
}
return a;
}
private static long[] read_long_array(int len) throws IOException {
long[] a = new long[len];
for (int i = 0; i < len; i++) {
a[i] = in.nextLong();
}
return a;
}
private static void print_array(int[] array) {
for (int now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
private static void print_array(long[] array) {
for (long now : array) {
out.print(now);
out.print(' ');
}
out.println();
}
static class Reader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
final byte[] buf = new byte[1024]; // 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 nextSign() throws IOException {
byte c = read();
while ('+' != c && '-' != c) {
c = read();
}
return '+' == c ? 0 : 1;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() throws IOException {
int b;
// noinspection ALL
while ((b = read()) != -1 && isSpaceChar(b)) {
;
}
return b;
}
public char nc() throws IOException {
return (char) skip();
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
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 {
din.close();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
9b88068a23ed2b903c9918006f42fa35
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D {
public static final int MAX_A = 1000000;
public static void main(String[] args) {
var io = new Kattio(System.in, System.out);
solve(io);
io.close();
}
public static void solve(Kattio io) {
int n = io.nextInt();
boolean[] inArray = new boolean[MAX_A + 1];
for (int i = 0; i < n; i++) {
int a = io.nextInt();
inArray[a] = true;
}
int count = 0;
for (int i = MAX_A; i > 0; i--) {
int g = 0;
for (int j = i; j <= MAX_A; j += i) {
if (inArray[j]) {
g = gcd(g, j);
}
}
if (i == g) {
inArray[i] = true;
count++;
}
}
io.println(count - n);
}
public static int gcd(int x, int y) {
int temp;
while (y > 0) {
x %= y;
temp = x;
x = y;
y = temp;
}
return x;
}
}
// modified from https://github.com/Kattis/kattio/blob/master/Kattio.java
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
71d7e01db59db853aaf2c02c23c95d58
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
// static boolean[] prime = new boolean[10000000];
final static long mod = 998244353;
public static void main(String[] args) {
// sieve();
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = new int[n];
int max = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
max = Math.max(a[i], max);
}
boolean[] arr = new boolean[max + 1];
for (int i : a) {
arr[i] = true;
}
for (int i = max; i > 0; i--) {
int gcd = 0;
for (int j = i; j <= max; j += i) {
if (arr[j]) {
gcd = gcd(gcd, j);
}
}
if (i == gcd) {
arr[gcd] = true;
}
}
int ans = 0;
for (boolean b : arr) {
if (b)
ans++;
}
out.println(ans - n);
out.flush();
}
static int gcd(int a, int b) {
int temp;
while (b > 0) {
a %= b;
temp = a;
a = b;
b = temp;
}
return a;
}
static Integer[] intInput(int n, InputReader in) {
Integer[] a = new Integer[n];
for (int i = 0; i < a.length; i++)
a[i] = in.nextInt();
return a;
}
static Long[] longInput(int n, InputReader in) {
Long[] a = new Long[n];
for (int i = 0; i < a.length; i++)
a[i] = in.nextLong();
return a;
}
static String[] strInput(int n, InputReader in) {
String[] a = new String[n];
for (int i = 0; i < a.length; i++)
a[i] = in.next();
return a;
}
// static void sieve() {
// for (int i = 2; i * i < prime.length; i++) {
// if (prime[i])
// continue;
// for (int j = i * i; j < prime.length; j += i) {
// prime[j] = true;
// }
// }
// }
}
class Data {
int val, ind;
Data(int val, int ind) {
this.val = val;
this.ind = ind;
}
}
class compareVal implements Comparator<Data> {
@Override
public int compare(Data o1, Data o2) {
return (o1.val - o2.val);
}
}
class compareInd implements Comparator<Data> {
@Override
public int compare(Data o1, Data o2) {
return o1.ind - o2.ind == 0 ? o1.val - o2.val : o1.ind - o2.ind;
}
}
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());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
39603cc6cf5e16fe4e2e161421ad2d29
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class F {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
String ar[] = br.readLine().split(" ");
boolean added[] = new boolean[1000001];
int max = 0;
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(ar[i]);
if (a[i] > max)
max = a[i];
added[a[i]] = true;
}
int ans = 0;
for (int i = max; i >= 1; i--) {
if (added[i])
continue;
int g = 0;
for (int j = 2 * i; j <= max; j += i) {
if (added[j])
g = gcd(g, j / i);
}
if (g == 1) {
added[i] = true;
ans++;
}
}
bw.write(ans + "\n");
bw.flush();
}
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
b08e4004ff4c4110b4d75eb3f85f1783
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
public static int GCD(int x, int y) {
if (y == 0) return x;
return GCD(y, x%y);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
boolean[] a = new boolean[1000001];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(st.nextToken());
a[x] = true;
}
int ans = 0;
for (int i = 1; i <= 1000000; i++) {
int gcd = 0;
if (a[i]) continue;
for (int j = i; j <= 1000000; j+=i) {
if (a[j]) {
gcd = GCD(j, gcd);
if (gcd == i) {
ans++;
break;
}
}
}
}
System.out.println(ans);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
f0c3e7757e85c22897bdf37fb96ddb38
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Codeforces {
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE) innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE) innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE) innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map) write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final int readInt() throws IOException {
return (int) readLong();
}
public final long readLong() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new IOException();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return negative ? -res : res;
}
public final int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = readInt();
}
return array;
}
public final long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < size; i++) {
array[i] = readLong();
}
return array;
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static long mulmod(long a, long b,
long mod) {
long res = 0; // Initialize result
a = a % mod;
while (b > 0) {
// If b is odd, add 'a' to result
if (b % 2 == 1) {
res = (res + a) % mod;
}
// Multiply 'a' with 2
a = (a * 2) % mod;
// Divide b by 2
b /= 2;
}
// Return result
return res % mod;
}
static long pow(long a, long b, long MOD) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y);
if (x > MOD) x %= MOD;
}
y = (y * y);
if (y > MOD) y %= MOD;
b /= 2;
}
return x;
}
static long[] f = new long[200001];
static long InverseEuler(long n, long MOD) {
return pow(n, MOD - 2, MOD);
}
static long C(int n, int r, long MOD) {
return (f[n] * ((InverseEuler(f[r], MOD) * InverseEuler(f[n - r], MOD)) % MOD)) % MOD;
}
static int[] h = {0, 0, -1, 1};
static int[] v = {1, -1, 0, 0};
public static class Pair {
public int a;
public int b;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return a == pair.a &&
b == pair.b;
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
static long compute_hash(String s) {
int p = 31;
int m = 1000000007;
long hash_value = 0;
long p_pow = 1;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
hash_value = (hash_value + (c - 'a' + 1) * p_pow) % m;
p_pow = (p_pow * p) % m;
}
return hash_value;
}
public static class SegmentTree {
long[] tree;
int n;
public SegmentTree(int[] nodes) {
tree = new long[nodes.length * 4];
n = nodes.length;
build(0, n - 1, 0, nodes);
}
// public void update(int pos, int val) {
// build(0, n-1, 0, pos, val);
// }
private void build(int l, int r, int pos, int[] nodes) {
if (l == r) {
tree[pos] = nodes[l];
return;
}
// if (l > pos) return;
// if (r < pos) return;
int mid = (l + r) / 2;
build(l, mid, 2 * pos + 1, nodes);
build(mid + 1, r, 2 * pos + 2, nodes);
tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];
}
// public void update(int pos, int val) {
// updateUtil(0, n - 1, 0, pos, val);
// }
public long get(int l, int r) {
return getUtil(0, n - 1, 0, l, r);
}
private long getUtil(int l, int r, int pos, int ql, int qr) {
if (ql > r || qr < l) {
return 0;
}
if (l >= ql && r <= qr) {
return tree[pos];
}
int mid = (l + r) / 2;
long left = getUtil(l, mid, 2 * pos + 1, ql, qr);
long right = getUtil(mid + 1, r, 2 * pos + 2, ql, qr);
return left + right;
}
// private void updateUtil(int l, int r, int pos, int i, int val) {
// if (i < l || i > r) {
// return;
// }
// if (l == r) {
// tree[pos] = val;
// return;
// }
// int mid = (l + r) / 2;
// updateUtil(l, mid, 2 * pos + 1, i, val);
// updateUtil(mid + 1, r, 2 * pos + 2, i, val);
// tree[pos] = tree[2 * pos + 1] + tree[2 * pos + 2];
// }
}
static int counter = 0;
static int[] rIn;
static int[] rOut;
static int[] lIn;
static int[] lOut;
private static int[] flatten;
private static int[] lFlatten;
static int VISITED = 1;
static int VISITING = 2;
static int[] DIRX = new int[]{0, 0, 1, -1};
static int[] DIRY = new int[]{1, -1, 0, 0};
static int answer = 0;
public static void main(String[] args) throws Exception {
//https://i...content-available-to-author-only...e.com/ebRGa6
InputReader in = new InputReader(System.in);
// FileWriter fileWriter = new FileWriter("hello.txt");
// PrintWriter out = new PrintWriter(fileWriter);
FastWriter out = new FastWriter(System.out);
// f[0] = 1;
// f[1] = 1;
// for (int i = 2; i < 200001; ++i) {
// f[i] = f[i-1] * i;
// f[i] %= 1000000007;
// }
int t = 1;
while (t-- > 0) {
int n = in.readInt();
int[] arr = new int[n];
HashSet<Integer> h = new HashSet<>();
int max = 0;
for (int i = 0; i < n; ++i) {
arr[i] = in.readInt();
h.add(arr[i]);
max = Math.max(max, arr[i]);
}
int answer = 0;
for (int i = 1; i <= max; ++i) {
if (!h.contains(i)) {
int cur = 0;
for (int j = i*2; j <= max; j += i) {
if (h.contains(j))
cur = gcd(cur, j);
}
if (cur == i) {
++answer;
}
}
}
out.println(answer);
out.flush();
}
// for (int i = 0; i < n; ++i) {
// System.out.print(ans[i] + " ");
// }
// System.out.println();
}
private static int solverrr(int pos, int lastTaken, int leftToBeRemoved, int n, int l, int[] posOfSign, int[] limits, int[][][] dp) {
if (pos == n) {
return (l - posOfSign[lastTaken]) * limits[lastTaken];
}
if (dp[pos][lastTaken][leftToBeRemoved] != -1) return dp[pos][lastTaken][leftToBeRemoved];
int max = solverrr(pos + 1, pos, leftToBeRemoved, n, l, posOfSign, limits, dp) + (posOfSign[pos] - posOfSign[lastTaken]) * limits[lastTaken];
if (leftToBeRemoved > 0) {
max = Math.min(max,
solverrr(pos + 1, lastTaken, leftToBeRemoved - 1, n, l, posOfSign, limits, dp));
}
return dp[pos][lastTaken][leftToBeRemoved] = max;
}
private static int solver(int x) {
int cur = 2;
int max = 0;
while (cur <= x) {
max = Math.max(max, (cur / 2) * (x / cur) + Math.max(0, (x % cur) - cur/2));
cur *= 2;
}
return max;
}
private static void solverr(String n, int pos, int total, boolean[] isPrime, int cur) {
if (pos == n.length()) {
// System.out.println(cur);
if (total == 0) {
if (isPrime[cur]) answer = cur;
}
return;
}
if (total > 0) {
int newcur = cur;
newcur *= 10;
newcur += (n.charAt(pos) - '0');
solverr(n, pos + 1, total - 1, isPrime, newcur);
}
solverr(n, pos + 1, total, isPrime, cur);
}
private static void dfss(List<List<Integer>> g, int cur, int last, long[] ways, boolean[] isLeaf) {
boolean isCurLeaf = true;
long leafCount = 0;
long waysCount = 0;
long waysMultiplier = 1;
for (int i = 0; i < g.get(cur).size(); ++i) {
int ntb = g.get(cur).get(i);
if (ntb != last) {
isCurLeaf = false;
dfss(g, ntb, cur, ways, isLeaf);
if (isLeaf[ntb]) {
leafCount++;
} else {
waysCount++;
waysMultiplier = mulmod(waysMultiplier, ways[ntb], 1000000007);
}
}
}
if (isCurLeaf) {
isLeaf[cur] = true;
return;
}
if ((waysCount % 2) == 0) {
long leaves = leafCount;
if (leaves == 0) {
ways[cur] = 0;
return;
} else {
ways[cur] = mulmod(waysMultiplier, pow(2, leaves - 1, 1000000007), 1000000007);
}
} else {
long leaves = leafCount;
if (leaves == 0) {
ways[cur] = waysMultiplier;
return;
} else {
ways[cur] = mulmod(waysMultiplier, pow(2, leaves - 1, 1000000007), 1000000007);
}
}
}
private static void dfs(List<List<Integer>> g, int cur, int last, int[] parent, int[] depth, int curDepth) {
parent[cur] = last;
depth[cur] = curDepth;
for (int i = 0; i < g.get(cur).size(); ++i) {
int ntb = g.get(cur).get(i);
if (ntb != last) {
dfs(g, ntb, cur, parent, depth, curDepth + 1);
}
}
}
private static void printBit(long maxBitSet, int m) {
StringBuilder ans = new StringBuilder();
while (maxBitSet > 0) {
if (maxBitSet % 2 == 1) {
ans.append("1");
} else {
ans.append("0");
}
maxBitSet /= 2;
}
for (int i = m - 1; i >= 0; --i) {
if (i <= ans.length() - 1)
System.out.print(ans.charAt(i));
else
System.out.print(0);
}
System.out.println();
}
private static void solvedd(int[] arr, int left, int right, int[] ans, int depth) {
if (left > right) return;
int maxInd = left;
for (int i = left; i <= right; ++i) {
if (arr[i] > arr[maxInd]) {
maxInd = i;
}
}
ans[maxInd] = depth;
solvedd(arr, left, maxInd - 1, ans, depth + 1);
solvedd(arr, maxInd + 1, right, ans, depth + 1);
}
private static void solved(List<List<Integer>> g, int node, int[][] dp, int last, int[] a) {
int donttake = 0;
int take = 0;
for (int i = 0; i < g.get(node).size(); ++i) {
int ntb = g.get(node).get(i);
if (ntb != last) {
solved(g, ntb, dp, node, a);
donttake += Math.max(dp[ntb][0], dp[ntb][1]);
take += dp[ntb][1];
}
}
dp[node][0] = a[node] + take;
dp[node][1] = donttake;
}
private static boolean solve(int n, List<Integer> nums, int cur, int pos, Boolean[][] dp) {
if (cur > n) return false;
if (cur == n) return true;
if (pos >= nums.size()) return false;
if (dp[cur][pos] != null) {
return dp[cur][pos];
}
boolean without = solve(n, nums, cur, pos + 1, dp);
boolean with = false;
int ogcur = cur;
for (int i = 1; i < 12; ++i) {
with |= solve(n, nums, cur + nums.get(pos), pos + 1, dp);
cur += nums.get(pos);
}
return dp[ogcur][pos] = with | without;
}
// private static Pair22 dfss(List<LinkedHashSet<Integer>> g, int node, HashSet<Integer> vis, int[] dis, int[] dis2) {
// if (vis.contains(node)) return new Pair22(dis[node], dis2[node], -1);
// vis.add(node);
// int min = dis[node];
// for (Integer ntb : g.get(node)) {
// if (dis[ntb] > dis[node])
// dfss(g, ntb, vis, dis, dis2);
// if (dis[ntb] <= dis[node]) {
// min = Math.min(min, dis[ntb]);
// } else {
// min = Math.min(min, dis2[ntb]);
// }
// }
// // if (dis)
// dis2[node] = min;
// return new Pair22(dis[node], min, -1);
// }
private static int solver(int[] nums, int pos, int[] dp) {
if (pos >= nums.length) return 0;
if (dp[pos] != Integer.MAX_VALUE) return dp[pos];
int min = solver(nums, pos + 2, dp) + nums[pos];
min = Math.min(solver(nums, pos + 3, dp) + nums[pos], min);
if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 3, dp));
if (pos + 1 < nums.length) min = Math.min(min, nums[pos] + nums[pos + 1] + solver(nums, pos + 4, dp));
// System.out.println(pos + " " + min);
return dp[pos] = min;
}
static int countFreq(String pattern, String text) {
int m = pattern.length();
int n = text.length();
int res = 0;
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
if (j == m) {
res++;
j = 0;
}
}
return res;
}
private static void dfsR(List<List<Integer>> g, int node, int[] v) {
rIn[node] = counter;
flatten[counter++] = v[node];
for (int i = 0; i < g.get(node).size(); ++i) {
dfsR(g, g.get(node).get(i), v);
}
rOut[node] = counter;
flatten[counter++] = v[node] * -1;
}
private static void dfsL(List<List<Integer>> g, int node, int[] v) {
lIn[node] = counter;
lFlatten[counter++] = v[node];
for (int i = 0; i < g.get(node).size(); ++i) {
dfsL(g, g.get(node).get(i), v);
}
lOut[node] = counter;
lFlatten[counter++] = v[node] * -1;
TreeMap<String, Integer> map = new TreeMap<>();
}
private static void preprocess(int pos, int[][] pre, List<List<Integer>> tree, int[] traverse, int depth, int last, int[] tin, int[] tout) {
tin[pos] = counter++;
traverse[depth] = pos;
for (int i = 0; depth - (1 << i) >= 0; ++i) {
pre[pos][i] = traverse[depth - (1 << i)];
}
for (int i = 0; i < tree.get(pos).size(); ++i) {
if (tree.get(pos).get(i) != last)
preprocess(tree.get(pos).get(i), pre, tree, traverse, depth + 1, pos, tin, tout);
}
tout[pos] = counter++;
}
static int gcd(int a, int b) {
while (b != 0) {
int t = a;
a = b;
b = t % b;
}
return a;
}
static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
static boolean submit = true;
static void debug(String s) {
if (!submit)
System.out.println(s);
}
static void debug(int s) {
LinkedHashSet<Integer> exist = new LinkedHashSet<>();
/*
4 2 3 _ 2 4 3 _
*/
}
/**
* Your DetectSquares object will be instantiated and called as such:
* DetectSquares obj = new DetectSquares();
* obj.add(point);
* int param_2 = obj.count(point);
*/
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
8cb30f33ec8f5fdb35028755692a4c89
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
public class D_NotAdding766_766 {
static HashSet<Integer> values = new HashSet<Integer>();
static boolean[] present;
static int max = 0;
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(scan.readLine());
String[] s = scan.readLine().split(" ");
for(int i = 0; i < n; i++)
{
int val = Integer.parseInt(s[i]);
values.add(val);
max = Math.max(max, val);
}
present = new boolean[max + 1];
for(int v : values)
present[v] = true;
for(int i = max; i > 0; i--)
{
if(hasGCD(i))
{
values.add(i);
present[i] = true;
}
}
out.println(values.size() - n);
out.flush();
}
private static boolean hasGCD(int gcd)
{
if(values.contains(gcd)) return true;
int k = -1;
for(int i = gcd; i <= max; i+=gcd)
{
if(present[i])
{
k = k == -1 ? i : gcd(k, i);
if(k == gcd) return true;
}
}
return k == gcd;
}
private static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a%b);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
ef4d79375646bb5e5ff0f83c48706a64
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {}
}
void solve() {
int n = in.nextInt();
int max = -1;
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
int val = in.nextInt();
max = Math.max(max, val);
set.add(val);
}
for (int i = 1; i <= max; i++) {
if (set.contains(i))continue;
int c = 0;
int gcd = 0;
for (int p = i; p <= max; p += i) {
if (set.contains(p)) {
if (c == 0) {
gcd = p;
} else {
gcd = gcd(gcd, p);
}
c++;
}
}
if (gcd == i)set.add(i);
}
out.append(set.size() - n);
}
int gcd(int a, int b) {
if (b == 0)return a;
return gcd(b, a % b);
}
public static void main (String[] args) {
// Its Not Over Untill I Win - Syed Mizbahuddin
Main sol = new Main();
int t = 1;
// t = in.nextInt();
while (t-- != 0) {
sol.solve();
}
System.out.print(out);
}
<T> void println(T[] s) {
System.out.println(Arrays.toString(s));
}
<T> void println(T s) {
System.out.println(s);
}
void print(int s) {
System.out.print(s);
}
void println(int s) {
System.out.println(s);
}
void println(int[] a) {
println(Arrays.toString(a));
}
int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
static FastReader in;
static StringBuffer out;
final int MAX;
final int MIN;
int mod ;
Main() {
in = new FastReader();
out = new StringBuffer();
MAX = Integer.MAX_VALUE;
MIN = Integer.MIN_VALUE;
mod = (int)1e9 + 7;
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
6076a960d30be04b4037a16419c177a6
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class D_Not_Adding {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
InputReader sc = new InputReader(inputStream);
int n = sc.nextInt();
// List<Integer> arr = new ArrayList<>();
int[] arr = new int[1000005];
for(int i = 0 ; i < n ; i++){
int temp = sc.nextInt();
// arr.add(temp);
arr[temp] = 1;
}
int count = 0;
for(long i = 1 ; i <= 1e6; i++){
long g = 0;
for(long j = i ; j <= 1e6 ; j += i){
if(arr[(int)j] == 1){
g = gcd(g,j);
}
}
if(g == i){
count++;
}
}
System.out.println(count-n);
}
public static long gcd(long a, long b){
if(a == 0) return b;
return gcd(b % 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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().charAt(0);
}
public String nextLine() throws IOException {
return reader.readLine().trim();
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
2cca503decc8c739c5298bef2812ba01
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D_Not_Adding{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static int gcd(int a,int b){
if(a%b==0)return b;
return gcd(b,a%b);
}
public static void main(String args[])throws IOException{
Reader sc=new Reader();
int n=sc.nextInt();
int a[]=new int[n];
int maxN=0;
boolean visited[]=new boolean[1000010];
for(int i=0;i<n;i++)
{a[i]=sc.nextInt();visited[a[i]]=true;maxN=Math.max(maxN,a[i]);}
int count=0;
for(int i=maxN;i>0;i--){
int g=0;
for(int j=i;j<=maxN;j=j+i){
if(visited[j]){
g=gcd(g,j);
}
}
if(g==i){
visited[i]=true;
count++;
}
}
System.out.println(count-n);
}
}
class Data implements Comparable<Data>{
int num;
public Data(int num){
this.num=num;
}
public int compareTo(Data o){
return o.num-num;
}
}
class Binary{
public String convertToBinaryString(long ele){
StringBuffer res=new StringBuffer();
while(ele>0){
if(ele%2==0)res.append(0+"");
else res.append(1+"");
ele=ele/2;
}
return res.reverse().toString();
}
}
class PAndC{
long c[][];
long mod;
public PAndC(int n,long mod){
c=new long[n+1][n+1];
this.mod=mod;
build(n);
}
public void build(int n){
for(int i=0;i<=n;i++){
c[i][0]=1;
c[i][i]=1;
for(int j=1;j<i;j++){
c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;
}
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
f62044be5ebb9e4d80427fe44827b4cf
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
boolean[] used = new boolean[(int)(1e6+1)];
StringTokenizer st = new StringTokenizer(in.readLine());
for(int i = 0; i < n; i++) {
int num = Integer.parseInt(st.nextToken());
used[num] = true;
}
int ans = 0;
for(int i = used.length-1; i >= 1; i--) {
if(used[i])
continue;
int gcd = 0;
for(int j = i*2; j < used.length; j+=i) {
if(used[j])
gcd = gcd(gcd, j);
}
if(gcd == i) {
used[i] = true;
ans++;
}
}
System.out.println(ans);
}
public static int gcd(int a, int b) {
if(b == 0)
return a;
return gcd(b, a%b);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7b6538c03b1eb698d0bd28ed029f80f6
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static final int MAX_A = 1000000;
public static void main(String[] args) throws IOException {
Kattio io = new Kattio();
int n = io.nextInt();
boolean[] appears = new boolean[MAX_A + 1];
for(int i = 0; i < n; i++) {
int num = io.nextInt();
appears[num] = true;
}
int ans = 0;
for(int i = MAX_A; i > 0; i--) {
int check = 0;
for(int j = i; j <= MAX_A; j += i) {
if(appears[j]) {
check = gcd(check, j);
}
}
if(check == i) {
appears[i] = true;
ans++;
}
}
io.println(ans - n);
io.close();
}
static int gcd(int a, int b) {
if(b == 0) return a;
return gcd(b, a % b);
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st = new StringTokenizer("");
private String token;
// standard input
public Kattio() { this(System.in,System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(new FileWriter(problemName+".out"));
r = new BufferedReader(new FileReader(problemName+".in"));
}
private String peek() {
if (token == null)
try {
while (!st.hasMoreTokens()) {
String line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
public boolean hasMoreTokens() { return peek() != null; }
public String next() {
String ans = peek();
token = null;
return ans;
}
public int nextInt() { return Integer.parseInt(next()); }
public double nextDouble() { return Double.parseDouble(next()); }
public long nextLong() { return Long.parseLong(next()); }
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
318793d78b94e801172428047c202922
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Solution {
static int mod = 1000000007;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
// int t = fs.nextInt();
// outer: while (t-- > 0) {
// }
int n = fs.nextInt();
int arr[] = fs.readArray(n);
HashSet<Integer> set = new HashSet<>();
int out = 0;
int max = 0;
for (int e : arr) {
set.add(e);
max = Math.max(max, e);
}
for (int i = 1; i < max + 1; i++) {
int g = 0;
if (set.contains(i))
continue;
for (int j = i; j < max + 1; j += i) {
if (set.contains(j))
g = gcd(g, j);
}
if (g == i)
out++;
}
System.out.println(out);
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(int[] a) {
// suffle
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
// then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
ArrayList<Integer> readList(int n) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++)
list.add(nextInt());
return list;
}
}
static class Pair {
int one;
int two;
public Pair(int one, int two) {
this.one = one;
this.two = two;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
4deff101df04c6a645b25e1c8edf5dd0
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class NotAdding {
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt();
int size = (int) 1e6;
boolean [] present = new boolean[size+1];
for(int i = 0;i < n;i++){
int a = in.nextInt();
present[a] = true;
}
int ans = 0;
for(int i = 1;i <= size;i++){
int g = 0;
for(int j = i;j <= size;j+=i){
if(present[j]){
g = gcd(g,j);
}
}
ans += g == i?1:0;
}
System.out.println(ans - n);
}
public static int gcd(int a,int b){
return b == 0?a:gcd(b,a%b);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
7918905c5e0d7735629f7b1df773d7d8
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
private static FS sc = new FS();
private static class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
private static class extra {
static int[] intArr(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) a[i] = sc.nextInt();
return a;
}
static long[] longArr(int size) {
Scanner scc = new Scanner(System.in);
long[] a = new long[size];
for(int i = 0; i < size; i++) a[i] = sc.nextLong();
return a;
}
static long intSum(int[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static long longSum(long[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static LinkedList[] graphD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
}
return temp;
}
static LinkedList[] graphUD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
temp[y].add(x);
}
return temp;
}
static void printG(LinkedList[] temp) { for(LinkedList<Integer> aa:temp) System.out.println(aa); }
static long cal(long val, long pow, long mod) {
if(pow == 0) return 1;
long res = cal(val, pow/2, mod);
long ret = (res*res)%mod;
if(pow%2 == 0) return ret;
return (val*ret)%mod;
}
static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); }
}
static int mod = (int) 1e9;
static LinkedList<Integer>[] temp, idx;
static long inf = (long) Long.MAX_VALUE;
// static long inf = Long.MAX_VALUE;
// static int max;
static StringBuilder out;
public static void main(String[] args) {
// int t = sc.nextInt();
int t = 1;
StringBuilder ret = new StringBuilder();
while(t-- > 0) {
int n = sc.nextInt(), size = (int) 1e6+10, count = 0;
int[] a = extra.intArr(n);
int[] arr = new int[size];
for(int aa:a) arr[aa] = 1;
for(int i = 1; i < size; i++) {
long g = 0;
for(int j = i; j < size; j += i) {
if(arr[j] == 1) {
g = extra.gcd(g, j);
}
}
if(g == i) count++;
}
ret.append((count - n) + "\n");
}
System.out.println(ret);
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
8e6f86635d813ef877ea78a941f18483
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class D {
public static final int MAX_A = 1000000;
public static void main(String[] args) {
var io = new Kattio(System.in, System.out);
solve(io);
io.close();
}
public static void solve(Kattio io) {
int n = io.nextInt();
boolean[] inArray = new boolean[MAX_A + 1];
for (int i = 0; i < n; i++) {
int a = io.nextInt();
inArray[a] = true;
}
int count = 0;
for (int i = MAX_A; i > 0; i--) {
int g = 0;
for (int j = i; j <= MAX_A; j += i) {
if (inArray[j]) {
g = gcd(g, j);
}
}
if (i == g) {
inArray[i] = true;
count++;
}
}
io.println(count - n);
}
public static int gcd(int x, int y) {
int temp;
while (y > 0) {
x %= y;
temp = x;
x = y;
y = temp;
}
return x;
}
}
// modified from https://github.com/Kattis/kattio/blob/master/Kattio.java
class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public String next() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
| |
PASSED
|
54fb80a1024b4ef5ee39f8ec6041365f
|
train_109.jsonl
|
1642257300
|
You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
//review! -> https://codeforces.com/contest/1591/submission/138904356
public class TaskD {
public static void main(String[] arg) {
final FastScanner in = new FastScanner(System.in);
final PrintWriter out = new PrintWriter(System.out);
final int n = in.nextInt();
final int[] a = in.readIntArr(n);
out.println(solution(n, a));
out.flush();
out.close();
in.close();
}
private static int solution(final int n, final int[] a) {
int max = max(a);
boolean[] present = new boolean[max+1];
for (int i = 0; i < n; i++) {
present[a[i]] = true;
}
int res = 0;
for (int i = 1; i <= max; i++) {
int g = 0;
for (int mx = 1; i * mx <= max; mx++) {
int mult = i * mx;
if (present[mult]) {
g = gcd(g, mult);
}
}
if (g == i && present[i] == false) {
res++;
present[i] = true;
}
}
return res;
}
public static String arrToString(final int[] a) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++) {
sb.append(a[i]).append(' ');
}
return sb.toString();
}
public static int max(int[] a) {
int max = a[0];
for (int i = 0; i < a.length; i++) {
if (max < a[i]) {
max = a[i];
}
}
return max;
}
public static int gcd(int a, int b) {
int t;
while (b > 0) {
a %= b;
t = a;
a = b;
b = t;
}
return a;
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readIntArr(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = Integer.parseInt(next());
}
return result;
}
long[] readLongArr(int n) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = Long.parseLong(next());
}
return result;
}
void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long nextLong() {
return Long.parseLong(next());
}
}
}
|
Java
|
["5\n4 20 1 25 30", "3\n6 10 15"]
|
2 seconds
|
["3", "4"]
|
NoteIn the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.
|
Java 11
|
standard input
|
[
"brute force",
"dp",
"math",
"number theory"
] |
1a37e42263fdd1cb62e2a18313eed989
|
The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.
| 1,900
|
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.