1. KingdomAndTrees

给出n个数a[1..n],求一个数组b[1..n]满足b严格递增,且b[1]>=1。

定义代价为W = max{abs(a[i]-b[i])},求代价最小值。

n<=50

【题解】

二分代价W,贪心判断。当前肯定越小越优,如果下一个加上当前二分的值,小于等于当前这个,那么就肯定不行,依次判即可。

// BEGIN CUT HERE  
  
// END CUT HERE  
#line 5 "KingdomAndTrees.cpp"  
# include <vector> 
# include <stdio.h>
# include <string.h>
# include <iostream>
# include <algorithm> 

using namespace std;

typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const int M = 50 + 10;
const int INF = 1e9;

class KingdomAndTrees {
    public:
        int n, h[M];
        inline bool chk(int x) {
            int lst = max(h[1]-x, 1); 
            for (int i=2; i<=n; ++i) {
                if(h[i]+x <= lst) return false;
                lst = max(h[i]-x, lst+1); 
            }
            return true;
        }
        int minLevel(vector<int> heights) {
            int l = 0, r = 2e9, mid, ans;
            n = heights.size();
            for (int i=0; i<n; ++i) h[i+1] = heights[i];
            while(1) {
                if(r-l <= 3) {
                    for (int i=l; i<=r; ++i)
                        if(chk(i)) {
                            ans = i;
                            break;
                        }
                    break;
                }
                mid = l+r>>1;
                if(chk(mid)) r = mid;
                else l = mid;
            }
            return ans;
        }
};
View Code

相关文章:

  • 2021-10-29
  • 2021-12-13
  • 2021-09-29
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2022-02-20
  • 2022-01-22
  • 2021-06-06
  • 2021-06-26
相关资源
相似解决方案