766DNot Adding
You have an array
- Choose two elements from the array
">ai anda i ">aj (a j i ≠ j ">i≠j) such thatgcd ( a i , a j ) ">gcd(ai,aj)is not present in the array, and addgcd ( a i , a j ) ">gcd(ai,aj)to the end of the array. Heregcd ( x , y ) ">gcd(x,y)denotes greatest common divisor (GCD) of integersx ">x andy ">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?
InputThe first line consists of a single integer
The second line consists of
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
Examples input5 4 20 1 25 30output
3input
3 6 10 15output
4Note
In the first example, one of the ways to perform maximum number of operations on the array is:
- Pick
i = 1 , j = 5 ">i=1,j=5i=1,j=5 and addgcd ( a 1 , a 5 ) = gcd ( 4 , 30 ) = 2 ">gcd(a1,a5)=gcd(4,30)=2to the array. - Pick
i = 2 , j = 4 ">i=2,j=4i=2,j=4 and addgcd ( a 2 , a 4 ) = gcd ( 20 , 25 ) = 5 ">gcd(a2,a4)=gcd(20,25)=5 to the array. - Pick
i = 2 , j = 5 ">i=2,j=5i=2,j=5 and addgcd ( a 2 , a 5 ) = gcd ( 20 , 30 ) = 10 ">gcd(a2,a5)=gcd(20,30)=10 to the array.
It can be proved that there is no way to perform more than
In the second example one can add
题目分析:我们要求这几个数最多能通过gcd变出多少个新的数来?我们首先考虑gcd(ac,bc) = c,也就是说只要是有两个以上c的倍数,就一定能把c这个数给变出来,这里a[i]的范围是1~10^6,所以我们可以枚举输入的任何一个存在的值,如果能构成一个新的数,则ans++,然后把新的数存入数组即可。答案就是ans,枚举的话从后往前枚举,因为一旦出现新的数,也会比你后面的数要小,也可以使用到新生成的数。因此我们的代码实现就不难了。
1 #include "bits/stdc++.h" 2 using namespace std; 3 int a[1000010]; 4 int gcd(int a,int b){ 5 if(!b) return a; 6 return gcd(b,a % b); 7 } 8 int main() 9 { 10 int n,d; 11 int ans = 0; 12 cin >> n; 13 for(int i = 0;i < n;i++){ 14 cin >> d; 15 a[d] = 1; 16 } 17 for(int i = 1e6;i >= 1;i--){ 18 int g = 0; 19 if(a[i])//如果已经有了,则不用进行操作了 20 continue; 21 for(int j = i;j <= 1e6;j += i)//每次以i的倍数进行枚举 22 if(a[j]) 23 g = gcd(j,g); 24 if(i == g){ 25 ans += 1; 26 a[i] = 1; 27 } 28 } 29 cout << ans; 30 return 0; 31 }