这是一个最长上升子序列,只不过,不是简单的数字增加而已。
LIS
LIS
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(dp[i]>dp[j]&&dp[i]<dp[j]+1){
dp[i]=dp[j]+1;
}
}
}
此外还可以用另一种方式求最长上升子序列的长度。
利用栈遍历整个数列如果当前元素大于栈顶元素,入栈,否则,替换掉比第一个比他大的元素,
最后栈的深度就是最长的长度。
利用lower_bound()很简单的可以是实现
int stack[maxn];
const int INF=03fffffff;
int a[maxn];
for(int i=0;i<maxn;i++)stack[i]=INF+2;
//核心代码
for(int i=0;<maxn;i++){
*lower_bound(stack,stack+maxn,a[i])=a[i]
}
return lower_bound(stack,stack+maxn,INF+2)-stack;
动态规划 ,首先按照w从小到大,然后按照speed,从大到小排序
然后进行动态规划转移方程。
dp[i] 表示以i 结尾的最大长度。
dp[i]=dp[j]+1 {1<=j
#include <iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=1005;
struct Mouse{
int w;
int speed;
int id;
bool operator<(Mouse b){
//sort by w asc and speed des
if(w<b.w)return true;
else if(w==b.w){
return speed>b.speed;
}else{
return false;
}
}
};
Mouse mice[maxn];
int dp[maxn];// dp[i] means the max num if mice[i] is add in the sequence after
int cnt=0;
int pre[maxn];
int res[maxn];
void DP(){
int mm=0;
int maxleni=1; // default is 1 the start
for(int i=1;i<=cnt;i++){
//j must start from 1
for(int j=1;j<i;j++){
if(mice[i].w>mice[j].w&&mice[i].speed<mice[j].speed&&dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
pre[i]=j;
if(dp[i]>mm){
mm=dp[i];
maxleni=i;
}
}
}
}
//
int i=0;
int t=maxleni;
while(t!=0){
res[i++]=t;
t=pre[t];
}
printf("%d\n",i);
while(i>0){
i--;
printf("%d\n",mice[res[i]].id);
}
}
int main()
{
int a,b;
cnt=0;
while(scanf("%d%d",&a,&b)!=EOF){
cnt++;
mice[cnt].w=a;
mice[cnt].speed=b;
mice[cnt].id=cnt;
dp[cnt]=1;
pre[cnt]=0;
}
sort(mice+1,mice+cnt+1);
DP();
return 0;
}

985

被折叠的 条评论
为什么被折叠?



