Algorithm improves change
time limit: 1.0s memory limit: 256.0MB
Problem Description
array A total of n elements, initially all 0. You can be an array of two operations: 1, the element in the array plus 1; 2, all of the elements in the array by 2. A request from an initial array state to the target state B operand minimum required.
The input format
of the first line of a positive integer and n represents the number of elements in the array
The second row of n represents a positive integer B element in the target state
output format
output a line representing the smallest operand
Sample Input
2
78
sample output
7
data size and conventions
n <= 50, B [i ] <= 1000
import java.util.Scanner;
public class change {
static int a[]=new int [51];
static int n;
public static boolean juge(){
for (int i = 0; i < n; i++) {
if(a[i]!=0)
return true;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for (int i = 0; i < n; i++) {
a[i]=sc.nextInt();
}
int sum=0;
while(juge())
{
for(int i=0;i<n;i++)
if(a[i]%2==0) continue;//如果是偶数就放过它。。。
else
{
a[i]--;//改造为偶数,并操作加1
sum++;
}
if(juge())
{
for(int i=0;i<n;i++)
a[i]/=2;
sum++;
}
else break;
}
System.out.println(sum);
}
}