题目链接:
http://poj.org/problem?id=2533
http://acm.hdu.edu.cn/showproblem.php?pid=1087
最长上升子序列问题:
思路1:dp[i]表示以i结尾的最长上升子序列
转移方程:dp[i]=max{dp[j]+1};
思路2:dp[i]表示长度为i的最小元素
升序排列:
iterator lower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。
iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。
区间 前闭后开。[first,last)。 所有元素均小于key则返回key的地址。
代码1:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=1005;
int a[N],dp[N];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int Max=0;
for(int i=1;i<=n;i++)
{
dp[i]=1;
for(int j=1;j<i;j++)if(a[j]<a[i]){
dp[i]=max(dp[i],dp[j]+1);
}
Max=max(dp[i],Max);
}
printf("%d\n",Max);
return 0;
}
代码2:
#include<cstdio>
#include<algorithm>
#include<cstring>
#define inf 1<<30
using namespace std;
const int N=500005;
struct node{
int a,b;
}st[N];
int dp[N];
bool cmp(node n1,node n2){
return n1.a<n2.a;
}
int main()
{
int n;int ca=1;
while(scanf("%d",&n)!=EOF)
{
fill(dp,dp+n+1,inf);
for(int i=1;i<=n;i++)
scanf("%d%d",&st[i].a,&st[i].b);
sort(st+1,st+n+1,cmp);
for(int i=1;i<=n;i++){
*lower_bound(dp+1,dp+n+1,st[i].b)=st[i].b;
}
int ans=lower_bound(dp+1,dp+n+1,inf)-dp-1;
printf("Case %d:\n",ca++);
if(ans>1)
printf("My king, at most %d roads can be built.\n\n",lower_bound(dp+1,dp+n+1,inf)-dp-1);
else
printf("My king, at most 1 road can be built.\n\n");
}
return 0;
}