hdu4521-小明系列问题——小明序列(线段树区间求最值)
2014-09-26 21:39
337 查看
题意:求最长上升序列的长度(LIS),但是要求相邻的两个数距离至少为d,数据范围较大,普通dp肯定TLE。线段树搞之就可以了,或者优化后的nlogn的dp。
代码为 线段树解法。
代码为 线段树解法。
#include <set> #include <map> #include <cmath> #include <ctime> #include <queue> #include <stack> #include <cctype> #include <cstdio> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef unsigned long long ull; typedef long long ll; const int inf = 0x3f3f3f3f; const double eps = 1e-8; const int maxn = 1e5+10; int dp[maxn],seg[maxn<<2]; //线段树区间求最值 int a[maxn]; void update(int l,int r,int pos,int x,int val) { if (l == r) { seg[pos] = val; return ; } int mid = (l + r) >> 1; if (x <= mid) update(l,mid,pos<<1,x,val); if (x > mid) update(mid+1,r,pos<<1|1,x,val); seg[pos] = max(seg[pos<<1],seg[pos<<1|1]); } int query(int l,int r,int pos,int x,int y) { if (x <= l && y >= r) return seg[pos]; int mid = (l + r) >> 1; int ans1 = 0,ans2 = 0; if (x <= mid) ans1 = query(l,mid,pos<<1,x,y); if (y > mid) ans2 = query(mid+1,r,pos<<1|1,x,y); return max(ans1,ans2); } int main(void) { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif int n,d; while (~scanf ("%d%d",&n,&d)) { memset(seg,0,sizeof(seg)); int len = 0; for (int i = 0; i < n; i++) { scanf ("%d",a+i); a[i] += 2; //因为a[i]可能为0,而我的线段树是从1开始的所以加2 len = max(len,a[i]); } int ans = 1; for (int i = 0; i < n; i++) { dp[i] = query(1,len,1,1,a[i]-1) + 1; //不能等于,所以减1,dp[i]表示以a[i]结尾的最长不降序列长度, if (i >= d) //延迟更新,这是这道题的关键, update(1,len,1,a[i-d],dp[i-d]); ans = max(dp[i],ans); } printf("%d\n",ans); } return 0; }
相关文章推荐
- hdu4521 小明系列问题——小明序列(线段树做法)
- hdu4521 小明系列问题——小明序列(线段树)
- hdu4521 小明系列问题——小明序列 线段树 间隔大于d的最长上升子序列
- hdu4521 小明系列问题——小明序列(LIS变种 (线段树+单点更新解法))
- HDU4521:小明系列问题——小明序列(推广LIS(带区间))
- hdoj 4521 小明系列问题——小明序列 【线段树优化dp or LIS变形】
- hdu4521 小明系列问题——小明序列(条件LIS)
- 线段树(端点更新) hdu-4521 小明系列问题——小明序列
- hdu45221——小明系列问题——小明序列 线段树优化dp
- hdu4521小明系列问题——小明序列【最长上升子序列,间隔】
- hdu-45221-小明系列问题——小明序列-(线段树)
- 小明系列问题——小明序列 (线段树优化的最长上升子序列)
- HDU4521:小明系列问题——小明序列
- HDU 4521 小明系列问题--小明序列(加强版LIS+线段树单点更新)
- 【线段树】 HDOJ 4521 小明系列问题——小明序列
- hdu4521 小明系列的问题——小明序列(LIS变种 (段树+单点更新解决方案))
- HDU 4521 小明系列问题——小明序列 (线段树维护DP)
- 小明系列问题——小明序列 - HDU 4521 线段树
- hdu4521小明系列问题——小明序列
- HDU 4521 小明系列问题——小明序列 (线段树维护DP)