今天做了两道题,都是关于队列的题。
POJ2739:
好久不刷题。。连POJ的水题都不会了。。。心情复杂.jpg
这道题很明显要先素数筛一下,然后进行处理。我一开始想到了前缀和和树状数组,但发现不对,没法用。。后来看了题目下的评论(vjude中),一下子想到了单调队列,但这道题很简单用队列足够了。我用数组模拟了一下,就是记录一个head(队头)和tmp(当前的连续素数和),从前往后搜,当tmp>n时队头出队tmp更新,tmp=n时ans++即可。AC代码如下:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
const int MAX=10005;
int pri[MAX];
bool vis[MAX];
void getPri()
{
memset(pri,0,sizeof(pri));
memset(vis,false,sizeof(vis));
for(int i=2;i<MAX;i++)
{
if(!vis[i]) pri[++pri[0]]=i;
for(int j=1;j<=pri[0]&&i*pri[j]<MAX;j++)
{
vis[i*pri[j]]=true;
if(i%pri[j]==0) break;
}
}
}
int main()
{
getPri();
int n;
while(scanf("%d",&n)==1)
{
if(n==0)
break;
int ans=0;
int tmp=0;
int head=1,top=1;
for(int i=1;i<=pri[0]&&pri[i]<=n;i++)
{
tmp+=pri[i];
while(tmp>n)
{
tmp-=pri[head],head++;
}
if(tmp==n)
ans++;
}
printf("%d\n",ans);
}
return 0;
}
然后我发现网上的题解暴搜O(n^2)也可以???好吧果然还是水题。。。
POJ2823:
这道题是典型的单调队列了。之前做过两道,但理解不深,今天再做一道题吧。
先附上一个讲解很好的博客Orz:https://www.cnblogs.com/tham/p/8038828.html
其中两句话很精辟:单调队列实现的大致过程:
1、维护队首(对于上题就是如果队首已经是当前元素的m个之前,则队首就应该被删了,head++)
2、在队尾插入(每插入一个就要从队尾开始往前去除冗杂状态,保持单调性)
之前做的是直接调STL,这次还是用数组模拟吧。。有些需要注意的地方标在注释里了。。
这道题卡常卡死了。。为了能优化时间我直接多开了几个数组。。最神奇的是一模一样的代码G++交上去T,结果C++过了exm?????
附上AC代码(C++提交):
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
const int INF=0x3f3f3f3f;
typedef pair<int,int> pp;
const int MAX=1e6+5;
int n,k;
int a[MAX];
pp que1[MAX],que2[MAX]; //min,max
int ans1[MAX],ans2[MAX];
int main()
{
while(scanf("%d%d",&n,&k)==2)
{
for(int i=1;i<=n;i++) //从1开始
scanf("%d",&a[i]);
int head1=1,head2=1,top1=0,top2=0; //top初始化为0
for(int i=1;i<k;i++) //前k-1个数入队同时保持单调性
{
while(top1>=head1&&que1[top1].first>=a[i]) //min
top1--;
que1[++top1].first=a[i]; //注意前置++
que1[top1].second=i; //要记录下标
while(top2>=head2&&que2[top2].first<=a[i]) //max
top2--;
que2[++top2].first=a[i];
que2[top2].second=i;
}
for(int i=k;i<=n;i++)
{
while(top1>=head1&&que1[top1].first>=a[i]) //min
top1--; //保持单调性
que1[++top1].first=a[i];que1[top1].second=i;
while(que1[top1].second-que1[head1].second>=k) //注意"="
head1++; //超过k个数(注意是下标差不是top-head!)
ans1[i]=que1[head1].first;
while(top2>=head2&&que2[top2].first<=a[i]) //max
top2--;
que2[++top2].first=a[i];que2[top2].second=i;
while(que2[top2].second-que2[head2].second>=k)
head2++;
ans2[i]=que2[head2].first;
}
for(int i=k;i<=n;i++)
printf("%d ",ans1[i]);
printf("\n");
for(int i=k;i<=n;i++)
printf("%d ",ans2[i]);
printf("\n");
}
return 0;
}