您的位置:首页 > 理论基础 > 计算机网络

最长不减子序列变形 The Heaviest Non-decreasing Subsequence Problem 南宁网络赛

2017-09-27 21:32 441 查看
题目链接:

The Heaviest Non-decreasing Subsequence Problem 南宁网络赛

大意:

给一个串,每个数字有一个权值,负数权值为 0 ,若数字大于10000 其权值为 5,并减去 10000 。

其余权值为 1。

分析:

容易想到,读到负数忽略。读到 >10000 做处理,将这个数复制 5 遍放进去,转换为权值为 1 ,那么求一个最长不减子序列,len 就是答案。

写的时候注意不是最长上升子序列,以及答案会有 0 的情况,初始 len=0比较好。

因为有相等的情况,用 upper_bound 。

代码实现:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int,int> pii;
#define mem(s,t) memset(s,t,sizeof(s))
#define D(v) cout<<#v<<" "<<v<<endl
#define inf 0x3f3f3f3f
#define pb push_back

//#define LOCAL
const int mod=1e9+7;
const int MAXN =1e6+10;
int a[MAXN],b[MAXN],len=0,n=0,m=0,dp[MAXN];

int main() {
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
string s;
while(getline(cin,s)){
stringstream ss(s);
int x;
while(ss>>x){
if(x<0) continue;
if(x>=10000){
x-=10000;
a[n++]=x;
a[n++]=x;
a[n++]=x;
a[n++]=x;
a[n++]=x;
}else a[n++]=x;
}
for(int i=0;i<n;i++){
if(a[i]>=dp[len]){
dp[++len]=a[i];
}else {
int p=upper_bound(dp,dp+len,a[i])-dp;
dp[p]=a[i];
}
}
printf("%d\n",len);
mem(a,0);
mem(b,0);
mem(dp,0);
n=m=0;
len=0;
}
return 0;
}


Tips:

lower_bound() 与 upper_bound()

对于 1,2,3,4  查找2
lb 返回 2 的位置,而 ub 返回 3 的位置
如果没找到该数都是后一个。


因此若要求最长上升子串, lower_bound 即可。

LIS参考资料:

http://blog.csdn.net/shuangde800/article/details/7474903

定义d[k]:长度为k的上升子序列的最末元素,若有多个长度为k的上升子序列,则记录最小的那个最末元素。

注意d中元素是单调递增的,下面要用到这个性质。

首先len = 1,d[1] = a[1],然后对a[i]:若a[i]>d[len],那么len++,d[len] = a[i];

否则,我们要从d[1]到d[len-1]中找到一个j,满足d[j-1]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐