首页 > 学院 > 开发设计 > 正文

hdu5256 序列变换 dp LIS

2019-11-08 01:45:49
字体:
来源:转载
供稿:网友

点击打开链接

思路:

lis的变形,唯一不同的是条件a[i] - i > a[j] - j + 1,i>j。因为要确保这两个元素之间能插入i - j + 1个元素

每个数先减去它的下标,防止下面的情况发生:加入序列是1,2,2,2,3,这样求上升子序列是3,也就是要修改2个,但是中间的两个2,变化范围又不能超过(1,3)那么这样求的也就不对,但是减掉之后,相当于给中间重复的数留下了修改的空间解释下为什么可以减而保持正确性:因为题目所求时严格递增,假设是2,3, 4,那么变成1, 1, 1,所以在LIS里非严格递增就可以了这也是为什么要在upper_bound的位置插入另外:lower_bound返回第一个>=key的位置;upper_bound返回第一个>key的位置,这样相减才是key的个数
求严格递增的LIS的方法(非严格递增的LIS只要把lower_bound改成upper_bound)
		memset(b,0x3f,sizeof(b));		int mx = -1;		for(int i=1; i<=n; i++){			int pos = lower_bound(b+1,b+1+n,a[i])-b;			b[pos] = a[i];			mx = max(mx,pos);		}
代码:
#include <bits/stdc++.h>using namespace std;const int maxn = 1e5+10;int n,a[maxn],b[maxn];// int dp(){// 	int len=1;// 	b[1] = a[1];// 	for(int i=2; i<=n; i++){// 		if(a[i]>=b[len]){// 			len++;// 			b[len] = a[i];// 		}else{// 			int pos = upper_bound(b+1,b+len,a[i])-b;// 			b[pos] = a[i];// 		}// 	}// 	return len;// }int main(){	int T; scanf("%d",&T);	for(int cas=1; cas<=T; cas++){		scanf("%d",&n);		for(int i=1; i<=n; i++){			scanf("%d",&a[i]);			a[i] -= i;		}		memset(b,0x3f,sizeof(b));		int mx = -1;		for(int i=1; i<=n; i++){			int pos = upper_bound(b+1,b+1+n,a[i])-b;			b[pos] = a[i];			mx = max(mx,pos);		}		int ans = n-mx;		PRintf("Case #%d:/n%d/n",cas,ans);		// int ans = n-dp();		// printf("Case #%d:/n%d/n",cas,ans);	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表