蓝桥杯 change 模拟

问题描述
  数组A中共有n个元素,初始全为0。你可以对数组进行两种操作:1、将数组中的一个元素加1;2、将数组中所有元素乘2。求将数组A从初始状态变为目标状态B所需要的最少操作数。
输入格式
  第一行一个正整数n表示数组中元素的个数
  第二行n个正整数表示目标状态B中的元素
输出格式
  输出一行表示最少操作数
样例输入
2
7 8
样例输出
7
数据规模和约定
  n<=50,B[i]<=1000
这道题目挺好玩的。
正解是思考把B数组变为全为0的数组最少需要几步。
之前一直对while(1)这种写法很抵触,现在看来有时候特别方便。
参考自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 }

猜你喜欢

转载自www.cnblogs.com/fx1998/p/12716468.html
今日推荐