题目链接
题解
题中所给的最长上升子序列其实就是一个限制条件
我们要构造出最大的以\(i\)开头的最长下降子序列,就需要编号大的点的权值尽量小
相同时当然就没有贡献,所以我们不妨令权值为一个\(1\)到\(n\)的排列
考虑如何满足限制条件
对于所有\(a[i] = v\)的点,点与点之间一定是单调下降的,连边
对于位置\(i\),如果\(a[i] = v\),那么\(i\)至少要比上一个\(a[j] = v - 1\)的位置大,连边
然后用大顶堆拓扑排序即可得到每个点最优的权值
\(O(nlogn)\)求一遍最长下降子序列长度即可
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define cls(s) memset(s,0x3f3f3f3f,sizeof(s))
using namespace std;
const int maxn = 100005,maxm = 100005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int h[maxn],ne = 2,de[maxn];
struct EDGE{int to,nxt;}ed[maxn << 1];
inline void build(int u,int v){
ed[ne] = (EDGE){v,h[u]}; h[u] = ne++;
de[v]++;
}
int last[maxn],n,a[maxn],cnt,x[maxn],f[maxn],bac[maxn];
priority_queue<int> q;
void work(){
REP(i,n) if (!de[i]) q.push(i);
int u;
while (!q.empty()){
u = q.top(); q.pop();
x[u] = ++cnt;
Redge(u) if (!(--de[to = ed[k].to])) q.push(to);
}
}
int getn(int t){
int l = 0,r = n,mid;
while (l < r){
mid = (l + r + 1) >> 1;
if (bac[mid] < t) l = mid;
else r = mid - 1;
}
return l;
}
void cal(){
cls(bac); bac[0] = 0;
for (int i = n; i; i--){
f[i] = getn(x[i]) + 1;
bac[f[i]] = min(bac[f[i]],x[i]);
}
LL ans = 0;
REP(i,n) ans += f[i];
printf("%lld\n",ans);
}
int main(){
n = read();
REP(i,n) a[i] = read();
for (int i = 1; i <= n; i++){
if (a[i] > 1) build(last[a[i] - 1],i);
if (last[a[i]]) build(i,last[a[i]]);
last[a[i]] = i;
}
work();
cal();
return 0;
}