bzoj3173: [Tjoi2013]最長上升子序列(樹狀數組)

題目傳送門

php

解法:
由於他是從小到大插。
那麼新插入一個值對於前面插入的點的影響是沒有的。。
因此樹狀數組直接求解答案。


node

關鍵是插入的序列不知道啊。
感受這題難在這。。
想了半天想了個O(n)求序列。
結果wa美滋滋。發現錯誤後從新想。
發現O(n)還求不了了。。



ios

通常位置都是知足二分性的。。
若是不少權值插在同一位置。
那麼後面插入的位置是要在前面的。
因此從後往前問求解每一個數的位置。


數組

代碼實現:spa

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
struct node {
  
  int x,w;}a[110000];int n,s[110000],sum[110000];
bool cmp(node n1,node n2) {
  
  if(n1.w!=n2.w)return n1.w<n2.w;return n1.x>n2.x;}
int lowbit(int x) {
  
  return x&-x;}
void change1(int x,int p) {
  
  while(x<=n) {sum[x]=max(sum[x],p);x+=lowbit(x);}}
void change2(int x) {
  
  while(x<=n) {sum[x]++;x+=lowbit(x);}}
int find_sum(int x) {
  
  int ans=0;while(x>0) {ans+=sum[x];x-=lowbit(x);}return ans;}
int find_max(int x) {
  
  int ans=0;while(x>0) {ans=max(ans,sum[x]);x-=lowbit(x);}return ans;}
int main() {
    scanf("%d",&n);
    for(int i=1;i<=n;i++) scanf("%d",&s[i]),s[i]++;
    memset(sum,0,sizeof(sum));
    for(int i=n;i>=1;i--) {
        int l=1,r=n,ans=0;
        while(l<=r) {
            int mid=(l+r)/2;int t=mid-find_sum(mid);
            if(t<s[i])l=mid+1;
            else {
  
  if(t==s[i])ans=mid;r=mid-1;}
        }s[i]=ans;change2(s[i]);
    }
    memset(sum,0,sizeof(sum));int ans=0;
    for(int i=1;i<=n;i++) {
  
  int t=find_max(s[i])+1;change1(s[i],t);ans=max(ans,t);printf("%d\n",ans);}
    return 0;
}
相關文章
相關標籤/搜索