序列变换
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 158 Accepted Submission(s): 83
Problem Description
给定序列$A = \{A_1, A_2,...,A_n\}$, 要求改变序列A中的某些元素,形成一个严格单调的序列B(严格单调的定义为:$B_i < B_{i+1}, 1 \leq i < N$)。
我们定义从序列A到序列B变换的代价为$cost(A, B) = max(|A_i - B_i|) (1 \leq i \leq N)$。
请求出满足条件的最小代价。
注意,每个元素在变换前后都是整数。
Input
第一行为测试的组数$T(1 \leq T \leq 10)$.
对于每一组:
第一行为序列A的长度$N(1 \leq N \leq 10^5)$,第二行包含N个数,$A_1, A_2, ...,A_n$.
序列A中的每个元素的值是正整数且不超过$10^6$。
Output
对于每一个测试样例,输出两行:
第一行输出:"Case #i:"。i代表第 i 组测试数据。
第二行输出一个正整数,代表满足条件的最小代价。
Sample Input
2
2
1 10
3
2 5 4
2
1 10
3
2 5 4
Sample Output
Case #1:
0
Case #2:
1
0
Case #2:
1
Problem's Link: http://acm.hdu.edu.cn/showproblem.php?pid=5248
Mean:
略
analyse:
二分答案 + 贪心验证
Time complexity: O(n)
Source code:
/*
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-05-30-22.26
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#define LL long long
#define ULL unsigned long long
using namespace std;
const int MAXN=; int num[MAXN],n,T,tmp[MAXN];
inline bool check(int l){
for(int i=;i<=n;i++)
tmp[i]=num[i];
tmp[]=num[]-l;
for(int i=;i<=n;i++)
if(num[i]+l<=tmp[i-])
return false;
else
tmp[i]=max(num[i]-l,tmp[i-]+);
return true;
}
int main()
{
scanf("%d",&T);
for (int Rt=;Rt<=T;Rt++)
{
scanf("%d",&n);
cout<<"Case #"<<Rt<<':'<<endl;
for(int i=;i<=n;i++) scanf("%d",&num[i]);
int l=,r=,ans=;
while(l<=r){
int mid=(l+r)>>;
if(check(mid)){
ans=mid;
r=mid-;
}else{
l=mid+;
}
}
cout<<ans<<endl;
}
return ;
}