您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: