You are given a sequence of positive integers: A=(a_1,a_2,\ldots,a_N)A=(a1,a2,…,aN).
You can choose and perform one of the following operations any number of times, possibly zero.
Your objective is to make AA satisfy a_1=a_2=\ldots=a_Na1=a2=…=aN.
Find the minimum total number of times you need to perform an operation to achieve the objective. If there is no way to achieve the objective, print -1 instead.
The input is given from Standard Input in the following format:
NN a_1a1 a_2a2 \ldots… a_NaN
Print the answer.
Copy
3 1 4 3
Copy
3
Here is a way to achieve the objective in three operations, which is the minimum needed.
Copy
3 2 7 6
Copy
-1
There is no way to achieve the objective.
Copy
6 1 1 1 1 1 1
Copy
0
题解:要想所有的数能变成同一个数,那它们的因素只可能有2 , 3 以及 它们的最大公因数 ,注意最大公因数也可能是2,3的倍数。
因此: 1.所有数的求最大公因数
2.数组元素除最大公因数,此时不数组中不可能存在一个元素(不等于1),可以使得数组中每个数都等于该元素.
3.因此最小的操作次数是除去最大公因数后到1 的操作次数之和。
- #include
- #include
- #include
- #include
- #include
- using namespace std;
- typedef long long ll;
-
- ll n, p, ans;
- ll a[1100];
-
- long long gcd(long long a, long long b)
- {
- while (b ^= a ^= b ^= a %= b);
- return a;
- }
-
- int main() {
- cin >> n;
- for (ll i = 1; i <= n; i++) {
- cin >> a[i];
- }
- p = a[1];
- for (ll i = 2; i <= n; i++) {
- p = gcd(a[i], p);//找最大公因数
- }
- for (ll i = 1; i <= n; i++) {
- ll x = a[i] / p;
- while (x % 2 == 0) {
- x /= 2;
- ans++;
- }
- while (x % 3 == 0) {
- x /= 3;
- ans++;
- }
- if (x != 1) {
- ans = -1;
- break;
- }
- }
- printf("%lld\n", ans);
- return 0;
- }