P3572 [POI2014]PTA-Little Bird
题目描述
从1开始,跳到比当前矮的不消耗体力,否则消耗一点体力,每次询问有一个步伐限制,求每次最少耗费多少体力
输入输出样例
输入样例#1:
9
4 6 3 6 3 7 2 6 5
2
2
5
输出样例#1:
2
1
说明
从1开始,跳到比当前矮的不消耗体力,否则消耗一点体力,每次询问有一个步伐限制,求每次最少耗费多少体力
其实双端队列的数组实现双端队列还算简单,
empty –> front>tail
push_back –> q[++tail]=x
pop_back –> tail–;
pop_front –> front++;
q.front() –> q[front]
q.back() –>q[tail-1]//代码形式因人而异,意会即可。
相比于STL,虽然数组实现双端队列代码量比较大,但是STL容易被卡时间。
STL
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<deque>
#include<cstring>
using namespace std;
int n,m,i,j,k,l,a[1000006],f[1000006];
int r()
{
int ans=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
ans*=10;
ans+=ch-'0';
ch=getchar();
}
return ans*f;
}
int main()
{
n=r();
for(i=1;i<=n;i++)
a[i]=r();
m=r();
for(k=1;k<=m;k++)
{
deque <int> q;
l=r();
f[1]=0,q.push_back(1);
for(int i=2;i<=n;i++)
{
while(!q.empty()&&i-q.front()>l)
q.pop_front();
f[i]=f[q.front()]+(a[q.front()]<=a[i]);
while(!q.empty()&&(f[q.back()]>f[i]||
(f[q.back()]==f[i]&&a[q.back()]<a[i])))
q.pop_back();
q.push_back(i);
}
printf("%d\n",f[n]);
}
return 0;
}
/*
9
4 6 3 6 3 7 2 6 5
2
2
5
*/
数组
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int n,m,i,j,k,l,a[1000006],f[1000006];
int qq[1000006];
int r()
{
int ans=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
{
ans*=10;
ans+=ch-'0';
ch=getchar();
}
return ans*f;
}
int main()
{
n=r();
for(i=1;i<=n;i++)
a[i]=r();
m=r();
int ff,tt;
for(k=1;k<=m;k++)
{
l=r();
ff=tt=0;
f[1]=0;
qq[tt++]=1;
for(i=2;i<=n;i++)
{
while(tt-ff&&i-qq[ff]>l)
ff++;
f[i]=f[qq[ff]]+(a[qq[ff]]<=a[i]);
while(tt-ff&&(f[qq[tt-1]]>f[i]||
(f[qq[tt-1]]==f[i]&&a[qq[tt-1]]<a[i])))
tt--;
qq[tt++]=i;
}
printf("%d\n",f[n]);
}
return 0;
}
/*
9
4 6 3 6 3 7 2 6 5
2
2
5
*/
STL
#1 AC 0ms/19515kB
#2 AC 0ms/19515kB
#3 AC 0ms/19515kB
#4 AC 381ms/19515kB
#5 AC 317ms/19515kB
#6 AC 566ms/19515kB
#7 AC 429ms/19765kB
#8 AC 589ms/19515kB
#9 TLE
#10 TLE
数组
#1 AC 0ms/23324kB
#2 AC 0ms/23324kB
#3 AC 0ms/23324kB
#4 AC 60ms/23324kB
#5 AC 39ms/23324kB
#6 AC 70ms/23324kB
#7 AC 39ms/23324kB
#8 AC 79ms/23324kB
#9 AC 619ms/23324kB
#10 AC 951ms/23324kB
所以STL虽然好用,还是尽可能的去练习手打数组实现。