仔细回忆一下是怎么求最长递增子序列的?
我们发现对于当前第
i
i
i位,用
f
[
i
]
f[i]
f[i]表示以
i
i
i为结尾的最长上升子序列的长度
再用一个
c
n
t
cnt
cnt表示数量
那么当前 f [ i ] = m a x ( ∑ j = 1 n f [ j ] ) , c n t [ i ] = ∑ f [ j ] = f [ i ] c n t [ j ] f[i]=max(∑_{j=1}^{n} f[j]),cnt[i]=∑_{f[j]=f[i]}cnt[j] f[i]=max(∑j=1nf[j]),cnt[i]=∑f[j]=f[i]cnt[j]
那么我们考虑现在就是要找最大的 f [ j ] f[j] f[j]和 ∑ c n t [ j ] ∑_{cnt[j]} ∑cnt[j]
用个树状数组维护就可以了
#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){
char ch=getchar();
int res=0;
while(!isdigit(ch))ch=getchar();
while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48),ch=getchar();
return res;
}
const int N=500005;
const int mod=1e9+7;
struct node{
int mx,cnt;
inline friend void operator +=(node &a,node &b){
if(a.mx==b.mx)a.cnt=(a.cnt+b.cnt)%mod;
else if(a.mx<b.mx)a.mx=b.mx,a.cnt=b.cnt;
}
};
node tr[N],ans;
int n,cnt;
int a[N],b[N];
inline int lowbit(int x){
return (x&(-x));
}
inline void add(int pos,node k){
for(;pos<=cnt;pos+=lowbit(pos))tr[pos]+=k;
}
inline node query(int pos){
node res=(node){0,1};
for(;pos;pos-=lowbit(pos))
res+=tr[pos];
return res;
}
signed main(){
n=read();
for(int i=1;i<=n;i++)a[i]=b[i]=read();
sort(b+1,b+n+1);
cnt=unique(b+1,b+n+1)-b-1;
for(int i=1;i<=n;i++)a[i]=lower_bound(b+1,b+cnt+1,a[i])-b;
for(int i=1;i<=n;++i){
node p=query(a[i]-1);p.mx++,add(a[i],p),ans+=p;
}
cout<<ans.cnt;
}