笑死,最坏情况下时间复杂度为O(n*nlogn)
思路:每次找前面最小l,使[l,i]满足条件,dp[i] = dp[l-1]+1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112#include <stdio.h> #include <string.h> #include <ctime> #include <stack> #include <string> #include <algorithm> #include <iostream> #include <cmath> #include <map> #include <queue> #include <vector> using namespace std; #define LL long long #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define lowbit(x) (x&-x) const int maxn = 1e5+7; const int INF = 0x3f3f3f3f; int rmq[maxn][20][2]; int mm[maxn],a[maxn]; int dp[maxn],n,s; void initRMQ() { mm[0] = -1; for(int i=1; i<=n; i++) { mm[i]=((i&(i-1))==0)?mm[i-1]+1:mm[i-1]; rmq[i][0][0] = rmq[i][0][1] = a[i]; } for(int j=1; j<=mm[n]; j++) for(int i=1; i+(1<<j)-1<=n; i++) { rmq[i][j][0] = max(rmq[i][j-1][0],rmq[i+(1<<(j-1))][j-1][0]); rmq[i][j][1] = min(rmq[i][j-1][1],rmq[i+(1<<(j-1))][j-1][1]); } } int qMin(int x,int y) { int k = mm[y-x+1]; return min(rmq[x][k][1],rmq[y-(1<<k)+1][k][1]); } int qMax(int x,int y) { int k = mm[y-x+1]; return max(rmq[x][k][0],rmq[y-(1<<k)+1][k][0]); } int f(int l,int r) { return qMax(l,r)-qMin(l,r); } int findLeft(int l,int r,int i) { int m,ret = -1; while(l<=r) { m = (l+r)>>1; if(f(m,i)<=s) { ret = m; r = m-1; } else l = m+1; } return ret; } int main() { int l; while(scanf("%d%d%d",&n,&s,&l)!=EOF) { for(int i=1; i<=n; i++) scanf("%d",&a[i]); initRMQ(); if(qMax(1,1+l-1)-qMin(1,1+l-1)>s) { //puts("this"); puts("-1"); continue; } for(int i=1; i<l; i++) dp[i] = maxn; dp[l] = 1; for(int i=l+1; i<=n; i++) { int t = findLeft(1,i-l+1,i); if(t!=-1) { while(dp[t-1]>=maxn&&t<=i-l) t++; dp[i] = dp[t-1]+1; } else dp[i] = maxn; } if(dp[n]<maxn) printf("%dn",dp[n]); else puts("-1"); } return 0; }
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.
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 the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
1
27 2 2 1 3 1 2 4 1 2
13
1
27 2 2 1 100 1 100 1 100 1
1-1
最后
以上就是无奈老鼠最近收集整理的关于codeforces-487B Strip(dp+rmq+二分+水数据)的全部内容,更多相关codeforces-487B内容请搜索靠谱客的其他文章。
发表评论 取消回复