杭電 3308 LCIS (線段樹+單點更新+區間求和)
阿新 • • 發佈:2018-12-24
Given n integers.
You have two operations:
U A B: replace the Ath number by B. (index counting from 0)
Q A B: output the length of the longest consecutive increasing subsequence (LCIS) in [a, b].
Input
T in the first line, indicating the case number.
Each case starts with two integers n , m(0<n,m<=10 5).
The next line has n integers(0<=val<=10 5).
The next m lines each has an operation:
U A B(0<=A,n , 0<=B=10 5)
OR
Q A B(0<=A<=B< n).
Output
For each Q, output the answer.
Sample Input
1 10 10 7 7 3 3 5 9 9 8 1 8 Q 6 6 U 3 4 Q 0 1 Q 0 5 Q 4 7 Q 3 5 Q 0 2 Q 4 6 U 6 10 Q 0 9
Sample Output
1 1 4 2 3 1 2 5
思路:需要對最長遞增子序列進行維護,每次一個個找肯定會爆。
AC程式碼:
#include<iostream> #include<cstdio> using namespace std; int n,m,num[100010]; struct node { int l,r,c;//左右邊界和區間長度 int ln,rn;//左右邊界的值 int ls,rs,ms;//左右及區間的最長遞增序列(LCIS) }tree[400010]; void up(int k) { tree[k].ls=tree[k*2].ls; tree[k].rs=tree[k*2+1].rs;//更新左右邊界值 tree[k].ln=tree[k*2].ln; tree[k].rn=tree[k*2+1].rn;//更新左右邊界LCIS長度 tree[k].ms=max(tree[k*2].ms,tree[k*2+1].ms);//更新區間內LCIS長度 if(tree[k*2].rn<tree[k*2+1].ln)//如果左子樹的右邊界值小於右子樹的左邊界值,要合併左子樹的右邊界和右子樹的左邊界計算 { if(tree[k*2].ls==tree[k*2].c)//若左子樹的右LCIS就是其本身 tree[k].ls+=tree[k*2+1].ls; //就應該再加上右子樹的左LCIS if(tree[k*2+1].rs==tree[k*2+1].c) tree[k].rs+=tree[k*2].rs; tree[k].ms=max(tree[k].ms,tree[k*2].rs+tree[k*2+1].ls); } } void build(int l,int r,int k) { tree[k].l=l; tree[k].r=r; tree[k].c=r-l+1; if(l==r) { tree[k].ln=tree[k].rn=num[l]; tree[k].ls=tree[k].rs=tree[k].ms=1; return; } int m=(tree[k].l+tree[k].r)/2; build(l,m,k*2); build(m+1,r,2*k+1); up(k); } int query(int l,int r,int k) { if(tree[k].l>=l&&tree[k].r<=r) return tree[k].ms; int m=(tree[k].l+tree[k].r)/2,ans=0; if(l<=m) ans = max(ans,query(l,r,2*k)); if(r>m) ans=max(ans,query(l,r,2*k+1)); if(tree[k*2].rn<tree[k*2+1].ln)//如果左子樹的右邊界值小於右子樹的左邊界值 ans=max(ans,min(m-l+1,tree[k*2].rs)+min(r-m,tree[k*2+1].ls)); return ans; } void insert(int i,int t,int m) { if(tree[i].l == tree[i].r) { tree[i].ln = tree[i].rn = m; return; } int mid = (tree[i].l+tree[i].r)>>1; if(t<=mid) insert(2*i,t,m); if(t>mid) insert(2*i+1,t,m); up(i); } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%d%*c",&num[i]); build(1,n,1); while(m--) { getchar(); char c; int a,b; scanf("%c %d %d",&c,&a,&b); //cout<<c<<a<<b<<endl; if(c=='Q') printf("%d\n",query(a+1,b+1,1)); else insert(1,a+1,b); } } }