最长递增子序列
Posted banyouxia
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最长递增子序列相关的知识,希望对你有一定的参考价值。
1037: I want you!
Description
Given an array Ai(0<=i<n), its length is n; We want to find an another array Bi , which is 0 or 1,and its length is n too;
Besides, Ai and Bi meets the following conditions:
If neither A[i]*B[i] nor A[j]*B[j] equals to 0, then A[i]*B[i] < A[j]*B[j];(0<=i<j<n)
Now , we want to know the maximum of ∑Bi(0<=i<n) you can get.
Input
The input consists of multiple test cases。For each test case ,the first line contains one integer n (1<n<=300).Next line contains n integers.
Output
For each case, output the maximum of ∑Bi.
Sample Input
6
1 2 3 4 5 6
4
3 2 3 6
Sample Output
6
3
思路:求最长递增子序列,注意求LIS时要把数组中0去掉单独处理,输出LIS长度+0的个数即为答案。
代码如下:
#include<bits/stdc++.h>
using namespace std;
#define maxn 300 + 10
#define INF 10000000000
#define FOR(i,x,y) for(int i = x; i < y; i++)
#define FORD(j,y,x) for(int j = y; j >= x; j--)
#define mset(x,v) memset(x,v,sizeof(x))
int a[maxn];
int b[maxn];
//数组a的最长递增子序列,时间复杂度O(n^2)
int LIS(int *a,int len){
int maxlen[len];
FOR(i,0,len) maxlen[i] = 1;
FOR(j,1,len){
FOR(i,0,j){
if(a[j] > a[i] && maxlen[j] < maxlen[i] + 1){
maxlen[j] = maxlen[i] + 1;
}
}
}
int max = 0;
FOR(i,0,len){
if(maxlen[i] > max) max = maxlen[i];
}
return max;
}
int main(){
int n;
while(~scanf("%d",&n)){
int c = 0;
int j = 0;
for(int i = 0;i < n;i++){
scanf("%d",&a[i]);
if(a[i]==0) {
c++;
}else{
b[j++] = a[i];//除去0的数组b
}
}
int ans = LIS(b,j);//最长递增子序列的长度
printf("%d ",ans + c);
}
return 0;
}
using namespace std;
#define maxn 300 + 10
#define INF 10000000000
#define FOR(i,x,y) for(int i = x; i < y; i++)
#define FORD(j,y,x) for(int j = y; j >= x; j--)
#define mset(x,v) memset(x,v,sizeof(x))
int a[maxn];
int b[maxn];
//数组a的最长递增子序列,时间复杂度O(n^2)
int LIS(int *a,int len){
int maxlen[len];
FOR(i,0,len) maxlen[i] = 1;
FOR(j,1,len){
FOR(i,0,j){
if(a[j] > a[i] && maxlen[j] < maxlen[i] + 1){
maxlen[j] = maxlen[i] + 1;
}
}
}
int max = 0;
FOR(i,0,len){
if(maxlen[i] > max) max = maxlen[i];
}
return max;
}
int main(){
int n;
while(~scanf("%d",&n)){
int c = 0;
int j = 0;
for(int i = 0;i < n;i++){
scanf("%d",&a[i]);
if(a[i]==0) {
c++;
}else{
b[j++] = a[i];//除去0的数组b
}
}
int ans = LIS(b,j);//最长递增子序列的长度
printf("%d ",ans + c);
}
return 0;
}
以上是关于最长递增子序列的主要内容,如果未能解决你的问题,请参考以下文章