POJ 2533 3903(最长递增子序列)

题目链接:http://poj.org/problem?id=2533

题目链接:http://poj.org/problem?id=3903

2533是裸的最长递增子序列。

3903需要用到二分优化,否则至改动2533代码的数组大小是过不了的。


POJ 2533:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;

const int INF=0x3f3f3f3f;
const int maxn=1005;
int n;
int a[maxn],dp[maxn];

int main(){
#ifndef ONLINE_JUDGE
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
#endif
    while(scanf("%d",&n)!=EOF){
    	for(int i=1;i<=n;i++)
    		scanf("%d",&a[i]);
    	memset(dp,0,sizeof(dp));
    	for(int i=1;i<=n;i++){
    		for(int j=1;j<i;j++){
    			if(a[i]>a[j]&&dp[i]<dp[j]+1){
    				dp[i]=dp[j]+1;
    			}
    		}
    	}
    	int ans=0;
    	for(int i=1;i<=n;i++)
    		ans=max(dp[i],ans);
    	printf("%d\n",ans+1);
    }
	return 0;
}

POJ 3903:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;

const int INF=0x3f3f3f3f;
const int maxn=100005;
int n;
int a[maxn],dp[maxn];

int Binary_Search(int *a,int len,int n){
	int left=0,right=len,mid=(left+right)/2;
	while(left<=right){
		if(n>a[mid]) left=mid+1;
		else if(n<a[mid]) right=mid-1;
		else return mid;
		mid=(left+right)/2;
	}
	return left;
}

int main(){
#ifndef ONLINE_JUDGE
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);
#endif
    while(scanf("%d",&n)!=EOF){
    	for(int i=0;i<n;i++)
    		scanf("%d",&a[i]);
    	dp[0]=-1,dp[1]=a[0];
    	int len=1;
    	for(int i=1;i<n;i++){
    		int tmp=Binary_Search(dp,len,a[i]);
    		dp[tmp]=a[i];
    		if(tmp>len) len=tmp;
    	}
    	printf("%d\n",len);
    }
	return 0;
}


你可能感兴趣的:(POJ 2533 3903(最长递增子序列))