hdu 1198 线段树

题目链接:https://www.luogu.com.cn/problem/P1198

线段树的单点更新+区间查询,典型的求区间最大值。

代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define dbg(args) cout<<#args<<":"<<args<<endl;
17 #define pb(i) push_back(i)
18 #define ppb(x) pop_back(x)
19 #define inf 0x7fffffff
20 #define maxn 200005
21 int n,m,mod;
22 int t[maxn<<2];
23 char s[4];
24 int x,tot=0;
25 void build(int l,int r,int rt)//递归建树,由于维护的是区间最大值,建树初始是-inf 
26 {
27     t[rt]=-inf; 
28     if(l==r)return;
29     int mid=(l+r)>>1;
30     build(lson);
31     build(rson);
32 }
33 void update(int l,int r,int rt,int pos,int C)//单点更新 
34 {
35     if(l==r)
36     {
37         t[rt]=C;
38         return ;
39     }
40     int mid=(l+r)>>1;
41     if(pos<=mid)update(lson,pos,C);
42     else update(rson,pos,C);
43     t[rt]=max(t[rt<<1],t[rt<<1|1]);//pushup操作,由于没有lazytag所以直接一条语句来维护 
44 }
45 int query(int l,int r,int rt ,int L,int  R)
46 {
47     if(L<=l&&r<=R)return t[rt];
48     int mid=l+r>>1,ans=-inf;
49     if(L<=mid) ans=query(lson,L,R);
50     if(R>mid) ans=max(ans,query(rson,L,R));
51     return ans;    
52 } 
53 int main()
54 {
55     //freopen("input.txt","r",stdin);
56     //freopen("output.txt","w",stdout);
57     std::ios::sync_with_stdio(false);
58     scan(m);
59     scan(mod);
60     n=maxn-1;
61     int last=0;
62     while(m--)
63     {
64         scanf("%s",&s);
65         scan(x);
66         if(s[0]=='A')
67         {
68             tot++;//加在序列的尾部 
69             update(1,n,1,tot,(last+x)%mod);
70         }
71         else if(s[0]=='Q')
72         {
73             last=query(1,n,1,tot-x+1,tot);//1-n长度上一共有1-tot的数 
74             pf("%d\n",last);
75         }
76     }
77  } 

猜你喜欢

转载自www.cnblogs.com/randy-lo/p/12441494.html