CodeForces - 597 C. Subsequences(dp+线段树or树状数组优化)

该博客介绍了如何利用线段树优化动态规划解决CodeForces上的一道题目,目标是找到给定序列中不同元素构成的递增子序列数量。博主详细解释了原DP方程的复杂度问题,并提出利用线段树在O(k*nlogn)时间内求解的方法,给出了相应的代码实现。
摘要由CSDN通过智能技术生成

For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8·1018.

Input
First line contain two integer values n and k (1 ≤ n ≤ 10^5, 0 ≤ k ≤ 10) — the length of sequence and the number of elements in increasing subsequences.

Next n lines contains one integer ai (1 ≤ ai ≤ n) each — elements of sequence. All values ai are different.

Output
Print one integer — the answer to the problem.

Examples
input
5 2
1
2
3
5
4
output
7

大致题意:告诉你n个不同的数 范围1到n,让你统计有多少个长度为k+1的递增数列.

思路:很容易可以想到dp方程:dp[ num[i] ][ len ]=sum(dp[ num[j] ][ len-1 ])(j < i&&num[i] >num[j],1<=len<=k+1),但是这样的转移时间是O(n),总的时间复杂度为O(k*n^2),肯定gg。所以我们考虑如何去优化转移。这里很巧妙的用到了线段树(当然用树状数组也可以)。我们以这n个数为下标建立k+1棵线段树,按照输入的先后顺序,当我们输入一个数num时,我们就可以在logn的时间内求出dp{num][len]的值,即在第len-1棵树中,查询区间1到num-1的和,然后用所求得的值去更新第len棵树上下标为num位置上的值。最后查询一下第k+1棵树中区间1到n的和即可。这样时间复杂度就降到了O(k*nlogn)

代码如下

代码1.

/*
线段树
*/
#include<cstdio> 
#include<iostream>   
#define ll long long int  
#define lson l,m,rt<<1  
#define rson m+1,r,rt<<1|1  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值