题目链接:
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
- Each piece should contain at least l numbers.
- The difference between the maximal and the minimal number on the piece should be at most s.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
Input
The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 105, 0 ≤ s ≤ 109, 1 ≤ l ≤ 105).
The second line contains n integers ai separated by spaces ( - 109 ≤ ai ≤ 109).
Output
Output the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
Examples
input
7 2 2
1 3 1 2 4 1 2
output
3
input
7 2 2
1 100 1 100 1 100 1
output
-1
题意:
把n个数字分成尽量少的连续部分,每部分至少l个数,而且最大值和最小值得差不超过s,问最少能分成多少部分;
思路:
dp[i]表示前i个数字最少能分成多少部分,因为差不能超过s,所以先求出RMQ,以方便后面询问,可以二分找出区间[l,i]l是满足要求的最左边的第一个差值不超过s的位置,然后看是否满足长度的要求,还有就是要转移最小的值;
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <bits/stdc++.h>
#include <stack>
#include <map>
using namespace std;
#define For(i,j,n) for(int i=j;i<=n;i++)
#define mst(ss,b) memset(ss,b,sizeof(ss));
typedef long long LL;
template<class T> void read(T&num) {
char CH; bool F=false;
for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar());
for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar());
F && (num=-num);
}
int stk[70], tp;
template<class T> inline void print(T p) {
if(!p) { puts("0"); return; }
while(p) stk[++ tp] = p%10, p/=10;
while(tp) putchar(stk[tp--] + '0');
putchar('\n');
}
const LL mod=1e6+3;
const double PI=acos(-1.0);
const int inf=1e9;
const int N=1e5+10;
const int maxn=1e3+520;
const double eps=1e-12;
int n,s,le,a[N],dp[N];
int mi[N][20],ma[N][20];
inline void RMQ()
{
for(int i=0;i<n;i++)ma[i][0]=mi[i][0]=a[i];
for(int j=1;(1<<j)<=n;j++)
{
for(int i=0;i+(1<<j)<=n;i++)
{
mi[i][j]=min(mi[i][j-1],mi[i+(1<<(j-1))][j-1]);
ma[i][j]=max(ma[i][j-1],ma[i+(1<<(j-1))][j-1]);
}
}
}
int query(int L,int R)
{
int k=0;
while((1<<(k+1))<=R-L+1)k++;
return max(ma[L][k],ma[R-(1<<k)+1][k])-min(mi[L][k],mi[R-(1<<k)+1][k]);
}
int check(int x,int y)
{
int temp=query(x,y);
if(temp<=s)return 1;
return 0;
}
int main()
{
read(n);read(s);read(le);
For(i,0,n-1)read(a[i]),dp[i]=inf;
RMQ();
For(i,0,n-1)
{
int l=0,r=i;
while(l<=r)
{
int mid=(l+r)>>1;
if(check(mid,i))r=mid-1;
else l=mid+1;
}
r++;
if(i-r+1<le)dp[i]=inf;
else
{
if(r==0)dp[i]=1;
else
{
for(int j=r-1;j<=i-le;j++)dp[i]=min(dp[i],dp[j]+1);
}
}
}
if(dp[n-1]==inf)dp[n-1]=-1;
cout<<dp[n-1]<<endl;
return 0;
}