Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7255 Accepted Submission(s): 2458
Problem Description
There is a sequence of integers. Your task is to find the longest subsequence that satisfies the following condition: the difference between the maximum element and the minimum element of the subsequence is no smaller than m and no larger than k.
Input
There are multiple test cases.
For each test case, the first line has three integers, n, m and k. n is the length of the sequence and is in the range [1, 100000]. m and k are in the range [0, 1000000]. The second line has n integers, which are all in the range [0, 1000000].
Proceed to the end of file.
For each test case, the first line has three integers, n, m and k. n is the length of the sequence and is in the range [1, 100000]. m and k are in the range [0, 1000000]. The second line has n integers, which are all in the range [0, 1000000].
Proceed to the end of file.
Output
For each test case, print the length of the subsequence on a single line.
Sample Input
5 0 0 1 1 1 1 1 5 0 3 1 2 3 4 5
Sample Output
5 4题意:
给你一串数字组成的数组,求最长的子串满足,字串的最大值减去子串的最小值大于等于m,小于等于k
单调队列的思想,i表示满足条件的子串的终点,一个单调递增的队列用来保存比i大的数,一个单调递减队列用来保存比i小的数字,对于每个i相当于枚举起点,找到合适的
实际上算法很巧秒的使每个位置只枚举一次
具体看程序,然后自己多模拟理解理解,就会豁然开朗
#include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> #include<stack> #define ll long long #define read(a) scanf("%d",&a); using namespace std; const int maxn=1e5+10; int a[maxn],qmax[maxn],qmin[maxn]; int main(){ freopen("test.txt","r",stdin); int n,m,k; while(~scanf("%d %d %d",&n,&m,&k)){ int head1,tail1,head2,tail2; int last=0; int ans=0; head1=tail1=head2=tail2=0; for(int i=1;i<=n;i++){ scanf("%d",&a[i]); while(head1<tail1&&a[qmax[tail1-1]]<a[i])tail1--; while(head2<tail2&&a[qmin[tail2-1]]>a[i])tail2--; qmax[tail1++]=i; qmin[tail2++]=i; while(a[qmax[head1]]-a[qmin[head2]]>k){ last=(qmax[head1]>qmin[head2]?qmin[head2++]:qmax[head1++]); } if(a[qmax[head1]]-a[qmin[head2]]>=m){ ans=max(ans,i-last); } } printf("%d\n",ans); } return 0; }