Subsequence(HDU3530 单调队列)
题目描述
给出一个长度为n的数列,求一个最长的区间,使得区间中最小值和最大值的差在[m,k]之间
输入
有多组测试数据 对于每组测试数据,第一行三个整数n,m,k。其中n表示序列的长度,范围[1,100000],m和k以及序列中的元素范围[0,1000000]输出
For each test case, print the length of the subsequence on a single line.
样例输入
5 0 0
1 1 1 1 1
5 0 3
1 2 3 4 5
样例输出
5
4
思路
维护了两个队列,一个是以当前结束所构成的递减序列的位置,另一个是以当前结束构成的递增序列的位置,然后每次的最大值减去最小值,如果大于k,那么就更新两个中的一个,应该更新位置较小的那个,这样才能使得这个区间的长度最大,然后就这么更新就行了
PS:好难想啊。。。
#include<bits/stdc++.h>
#define mem(a,x) memset(a,x,sizeof(a))
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;
typedef unsigned long long ull; // %llu
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = -1u>>1;
const int maxn = 1e6+5;
const int mod=998244353;
struct node
{
int x,num;
};
int p[maxn];
int main()
{
int n,l,r;
while(~scanf("%d%d%d",&n,&l,&r))
{
int pos=0;
int ans=0; //pos为右端点为i时符合条件的最优左端点
for(int i=1; i<=n; i++)scanf("%d",&p[i]);
deque<node>q1; //递减
deque<node>q2; //递增
for(int i=1; i<=n; i++)
{
while(!q1.empty()&&q1.back().x<p[i])q1.pop_back(); //递减
q1.push_back(node{p[i],i});
while(!q2.empty()&&q2.back().x>p[i])q2.pop_back(); //递增
q2.push_back(node{p[i],i});
while(!q1.empty()&&!q2.empty()&&q1.front().x-q2.front().x>r) //如果当前队首元素差值,即最大最小值差大于r 则应令最大元素出队或最小元素出队 取决于谁的下标更小
{
if(q1.front().num<q2.front().num)
pos=q1.front().num,q1.pop_front();
else
pos=q2.front().num,q2.pop_front();
}
//pos会更新到最优左端点
if(!q1.empty()&&!q2.empty()&&q1.front().x-q2.front().x>=l)
{
ans=max(ans,i-pos);
}
//记录答案
}
printf("%d\n",ans);
}
}
做完发现网上用multiset也可以做,佩服 ,直接粘了
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100050;
int n, m, k;
int a[maxn];
int main ()
{
while(~scanf("%d%d%d", &n, &m, &k))
{
multiset<int>st;//写到main()函数里面,结束后会被析构掉
int pos = 1, ans = 0;
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
st.insert(a[i]);
while(*st.rbegin() - *st.begin() > k) st.erase(a[pos++]);
if(*st.rbegin() - *st.begin() >= m) ans = max(ans, i - pos + 1);
}
printf("%d\n", ans);
}
return 0;
}