hdu 5248(二分)

来源:互联网 发布:天猫超市销售数据 编辑:程序博客网 时间:2024/06/05 14:40

题解:二分出最小代价x,然后倒着让每个数字都在x的变化范围内单调递减,如果无法实现就return false,左边界为x + 1,否则右边界是x。

#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;const int N = 100005;long long n, a[N];bool judge(long long x) {    int temp = a[n - 1] + x;    for (int i = n - 2; i >= 0; i--) {        if (abs(temp - 1 - a[i]) <= x)            temp = temp - 1;        else if (temp - 1 >= a[i])            temp = a[i] + x;        else            return false;    }    return true;}int main() {    int t, cas = 1;    scanf("%d", &t);    while (t--) {        scanf("%lld", &n);        long long l = 0, r = 1000000;        for (int i = 0; i < n; i++)            scanf("%lld", &a[i]);        while (l < r) {            long long mid = (l + r) / 2;            if (judge(mid))                r = mid;            else                l = mid + 1;        }        printf("Case #%d:\n%lld\n", cas++, l);    }    return 0;}
0 0