百度之星初賽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;}