【BZOJ 1012】【JSOI 2008】最大数

来源:互联网 发布:信息安全与密码学编程 编辑:程序博客网 时间:2024/05/22 12:20

Description

  现在请求你维护一个数列,要求提供以下两种操作:1、 查询操作。语法:Q L 功能:查询当前数列中末尾L
个数中的最大的数,并输出这个数的值。限制:L不超过当前数列的长度。2、 插入操作。语法:A n 功能:将n加
上t,其中t是最近一次查询操作的答案(如果还未执行过查询操作,则t=0),并将所得结果对一个固定的常数D取
模,将所得答案插入到数列的末尾。限制:n是非负整数并且在长整范围内。注意:初始时数列是空的,没有一个
数。

Input

  第一行两个整数,M和D,其中M表示操作的个数(M <= 200,000),D如上文中所述,满足D在longint内。接下来
M行,查询操作或者插入操作。

Output

  对于每一个询问操作,输出一行。该行只有一个数,即序列中最后L个数的最大数。

Sample Input

5 100
A 96
Q 1
A 97
Q 1
Q 2

Sample Output

96
93
96

题解们:

啊,看了黄学长的博客,才知道这题有好多解法。

一:线段树

现将每个点初始为0,剩下的你们会了吧。

这种算法是对题意的最直观理解

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define lson o << 1#define rson o << 1 | 1const int N = 200010;int maxn[N << 2],t[N << 2];int ll,rr;void build(int o,int l,int r){    if(l == r){maxn[o] = t[o] = 0;return;}    int mid = (l+r)>>1;    build(lson,l,mid); build(rson,mid+1,r);    return;}int query(int o,int l,int r){    if(ll <= l && rr >= r) return maxn[o];    int mid = (l+r)>>1;    int ans = -1;    if(ll <= mid) ans = max(ans,query(lson,l,mid));    if(rr > mid) ans = max(ans,query(rson,mid+1,r));    return ans;}void update(int o,int l,int r,int pos,int n){    if(l == r && l == pos){maxn[o] = n;return;}    int mid = (l+r)>>1;    if(pos <= mid) update(lson,l,mid,pos,n);        else update(rson,mid+1,r,pos,n);    maxn[o] = max(maxn[lson],maxn[rson]);    return;}int main(){    char type[2];    int n,m,d,l;    scanf("%d%d",&m,&d);    build(1,1,200000);    int len = 0,t = 0;    while(m--)    {        scanf("%s",type);        if(type[0] == 'Q')        {            scanf("%d",&l);            ll = len - l + 1;            rr = len;            t = query(1,1,200000);            printf("%d\n",t);        }        else        {            scanf("%d",&n);            n = (n + t) % d;            update(1,1,200000,++len,n);        }    }    return 0;}

二:单调队列

我比较喜欢这种,代码短,效率高,易理解。

#include<cstdio>int a[200010],maxn[200010],n,m,d,x;char type[1];int main(){    scanf("%d%d",&m,&d);    int len = 0,t = 0;    while(m--)    {        scanf("%s%d",type,&x);        if(type[0] == 'A')        {            a[++len] = (t + x) % d;            for(int i = len;i;i--)                if(maxn[i] < a[len]) maxn[i] = a[len];                else break;        }        else            printf("%d\n",t = maxn[len - x + 1]);    }    return 0;}

三:栈

用一个类似栈的方法来维护,感觉很好玩O(∩_∩)O~~

#include<cstdio>#include<algorithm>using namespace std;int a[200010],num[200010],len;int m,d,t,top;char type[1];int main(){    scanf("%d%d",&m,&d);    len = 0; t = 0; top = 0;    int x;    while(m--)    {        scanf("%s%d",type,&x);        if(type[0] == 'A')        {            a[++len] = (t+x) % d;            while(top && a[num[top]] <= a[len]) top--;            num[++top] = len;        }        else        {            int y = lower_bound(num+1,num+top+1,len-x+1)-num;            printf("%d\n",t = a[num[y]]);        }    }    return 0;}
1 0
原创粉丝点击