codeforces 1675B. Make It Increasing

Given 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛. You can perform the following operation on them:

select any element 𝑎𝑖 (1≤𝑖≤𝑛) and divide it by 2 (round down). In other words, you can replace any selected element 𝑎𝑖 with the value ⌊𝑎𝑖2⌋ (where ⌊𝑥⌋ is – round down the real number 𝑥).
题目如下
Output the minimum number of operations that must be done for a sequence of integers to become strictly increasing (that is, for the condition 𝑎1<𝑎2<⋯<𝑎𝑛 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 𝑛=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 𝑎2=6 and get the sequence [3,3,5];
Then replace 𝑎1=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 𝑡 (1≤𝑡≤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 𝑛 (1≤𝑛≤30).

The second line of each test case contains exactly 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (0≤𝑎𝑖≤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".

题目大意
题目要求我们判定对于给定的数组,能否不改变数组元素的位置,通过对元素进行多次ai=ai/2并向下取整操作,使得整个数组呈现严格的升序排列,如果可以就输出所需最少的操作数;否则,输出-1表示无法实现

解题思路
要实现严格的升序数组,我们可以通过贪心算法,从右向左开始让每两个元素进行比较大小,若不符合升序要求则对左侧元素进行操作反复进行直到符合要求,再进行前两项,从左到右一直进行到严格升序
实现

点击查看代码
int ope(int* a, int n){
    int sum = 0;
    for (int i = n - 2; i >= 0; i--) {
        while (a[i] >= a[i + 1]) {
            if (a[i] == 0)
                return -1;
            a[i] /= 2;
            sum++;
        }
    }
    return sum;
}

完整代码如下

点击查看代码
#include <stdio.h>

int ope(int* a, int n){
    int sum = 0;
    for (int i = n - 2; i >= 0; i--) {
        while (a[i] >= a[i + 1]) {
            if (a[i] == 0)
                return -1;
            a[i] /= 2;
            sum++;
        }
    }
    return sum;
}

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        int n;
        scanf("%d", &n);
        int arr[10005];
        for(int i = 0; i < n; i++){
            scanf("%d", &arr[i]);
        }
        int res = ope(arr, n);
        printf("%d\n", res);
    }
    return 0;
}
posted @ 2025-07-01 17:54  sirro1uta  阅读(13)  评论(0)    收藏  举报