Problem Description
There are n elements in the array A, and the initial value is 0. You can perform two operations on the array: 1. Add 1 to an element in the array; 2. Multiply all the elements in the array by 2. Find the minimum number of operands required to change the array A from the initial state to the target state B.
Input format
A positive integer n in the first line represents the number of elements in the array The
second line of n positive integers represents the elements in the target state B
second line of n positive integers represents the elements in the target state B
Output format
The output line represents the minimum number of operations
Sample input
2
7 8
7 8
Sample output
7
Data size and agreement
n<=50,B[i]<=1000
This question is quite fun.
The positive solution is to think that it takes at least a few steps to change the B array into an array of all 0s.
I used to be very resistant to while (1), but now it seems that it is sometimes very convenient.
Reference from https://www.cnblogs.com/lusiqi/p/12547532.html
1 #include <bits/stdc++.h> 2 using namespace std; 3 int a[60]; 4 int main() { 5 int n; 6 cin >> n; 7 for (int i = 1; i <= n; i++) { 8 cin >> a[i]; 9 } 10 int ans = 0; 11 while (1) { 12 for (int i = 1; i <= n; i++) { 13 if (a[i] % 2 == 1) { 14 ans++; 15 a[i]--; 16 } 17 } 18 int cnt = 0; 19 for (int i = 1; i <= n; i++) { 20 if (a[i] == 0) { 21 cnt++; 22 } 23 } 24 if (cnt == n) { 25 break; 26 } 27 for (int i = 1; i <= n; i++) { 28 a[i] /= 2; 29 30 } 31 ans++; 32 } 33 cout << ans << endl; 34 return 0; 35 }