百度之星初賽1002(二分搜尋),初賽1002

來源:互聯網
上載者:User

百度之星初賽1002(二分搜尋),初賽1002

序列變換  Accepts: 816  Submissions: 3578 Time Limit: 4000/2000 MS (Java/Others)  Memory Limit: 32768/32768 K (Java/Others)Problem Description

給定序列A={A1,A2,...,An}, 要求改變序列A中的某些元素,形成一個嚴格單調的序列B(嚴格單調的定義為:Bi<Bi+1,1≤i<N)。

我們定義從序列A到序列B變換的代價為cost(A,B)=max(|Ai−Bi|)(1≤i≤N)。

請求出滿足條件的最小代價。

注意,每個元素在變換前後都是整數。

Input

第一行為測試的組數T(1≤T≤10).

對於每一組: 第一行為序列A的長度N(1≤N≤105),第二行包含N個數,A1,A2,...,An. 序列A中的每個元素的值是正整數且不超過106。

Output

對於每一個測試範例,輸出兩行:

第一行輸出:"Case #i:"。i代表第 i 組測試資料。

第二行輸出一個正整數,代表滿足條件的最小代價。

Sample Input
221 1032 5 4
Sample Output
Case #1:0Case #2:1

這題窩覺得貪心才是才是正解,但是貪心沒貪出來,QAQ,二分更好想

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <vector>#include <queue>using namespace std;typedef long long LL;const int MOD = 1e9 + 7;const int INF = 0x7fffffff;const int N = 1e6 + 10;int a[N], n;bool f(int x) {    int pre = a[0] - x;    for(int i = 1; i < n; i++) {        if(pre  >= x + <span style="font-family: Arial, Helvetica, sans-serif;">a[i]</span>) return false;        else pre = max(a[i] - x, pre + 1);//pre+1是看當前減去x是否小於pre-1,如果是則不能    }    return true;}int main() {    int T, C = 1;    scanf("%d", &T);    while(T--) {        scanf("%d", &n);        for(int i = 0; i < n; i++) {            scanf("%d", &a[i]);        }        int ans = 0;        int l = 0, r = 1e7, mid;        while(r >= l) {            int mid = (l + r) / 2;            if(f(mid)) {                ans = mid;                r = mid - 1;            } else {                l = mid + 1;            }        }        printf("Case #%d:\n%d\n", C++, ans);    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.