Codeforces Round 787 (Div. 3) B. Make It Increasing

152 阅读1分钟

题目链接

题目详情

Given nn integers a1,a2,…,an. You can perform the following operation on them:

select any element ai (1≤i≤n) and divide it by 2 (round down). In other words, you can replace any selected element ai with the value ⌊ai2⌋ (where ⌊x⌋ is – round down the real number x). Output the minimum number of operations that must be done for a sequence of integers to become strictly increasing (that is, for the condition a1<a2<⋯<an to be satisfied). Or determine that it is impossible to obtain such a sequence. Note that elements cannot be swapped. The only possible operation is described above.

For example, let n=3 and a sequence of numbers [3,6,5] be given. Then it is enough to perform two operations on it:

Write the number ⌊62⌋=3 instead of the number a2=6 and get the sequence[3,3,5]; Then replace a1=3 with ⌊32⌋=1 and get the sequence [1,3,5]. The resulting sequence is strictly increasing because 1<3<5.

Input The first line of the input contains an integer t (1≤t≤104) — the number of test cases in the input.

The descriptions of the test cases follow.

The first line of each test case contains a single integer n (1≤n≤30).

The second line of each test case contains exactly n integers a1,a2,…,an (0≤ai≤2⋅109).

Output For each test case, print a single number on a separate line — the minimum number of operations to perform on the sequence to make it strictly increasing. If a strictly increasing sequence cannot be obtained, print "-1".

input

7
3
3 6 5
4
5 3 2 1
5
1 2 3 4 5
1
1000000000
4
2 8 7 5
5
8 26 5 21 10
2
5 14

output

2
-1
0
0
4
11
0

题目大意及解题思路

大意:
给定n个整数a1,a2,…,an。您可以对它们执行以下操作:选择任意元素ai(1≤i≤n),并将其除以2(向下取整)。即我们可以将任何选定的元素ai替换为值⌊ai⌋。输出整数序列必须执行的最小操作数,以使其严格递增(即,满足条件a1<a2<…<an)。或者确定不可能获得这样的序列。请注意,元素不能交换。如果无法获得严格递增序列,请打印“-1”。
解题思路:
其实这里用到的就是贪心,我们先把数据读入,然后从后往前枚举,如果前一个大于等于后一个,就循环,让前一个/2,次数++。如果循环完,前一个仍然大于等于后一个,则无解,跳出循环。这里我们标记一下是否输出-1,如果输出了后面就不输出ans了。

AC代码

#include<iostream>
using namespace std;  
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
      int t,a[31];
      cin>>t;
      for(int i=1;i<=t;i++) cin>>a[i];.  int ans = 0;
      bool flage = false;
     for(int i=t-1;i>=1;i--)
     {
          while(a[i]&&a[i]>=a[i+1])
          {
              a[i]/=2;
              ans++;
          }
         if(a[i]>=a[i+1])
         { 
            cout<<-1<<endl;
            flage=true;
            break;
         }
     }
        if(!flage) cout<<ans<<endl;
    }
}