最长上升子序列模型 AcWing 1010. 拦截导弹

最长上升子序列模型 AcWing 1010. 拦截导弹

原题链接

AcWing 1010. 拦截导弹

算法标签

DP 线性DP 最长上升子序列

思路

在这里插入图片描述
摘自该题解

代码

#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>=b;--i)
using namespace std;
const int N = 1005, INF = 0x3f3f3f3f;
// f1[i]表示此时第i套导弹拦截系统所拦截的最后一个导弹的高度
int f[N], f1[N], a[N];
inline int read(){
   int s=0,w=1;
   char ch=getchar();
   while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
   while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
   return s*w;
}
void put(int x) {
    if(x<0) putchar('-'),x=-x;
    if(x>=10) put(x/10);
    putchar(x%10^48);
}
vector<string> get(string str){
    vector<string> res;
    string word;
    for (auto c: str){
        if (c == ' '){
            res.push_back(word);
            word = "";
        }
        else word += c;
    }
    res.push_back(word);
    return res;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	string s;
	getline(cin, s);
	vector<string> v=get(s);
	int ans=0, cnt=0, n=v.size();// cnt代表现有子序列长度
	rep(i, 0, n){
	    a[i]=stoi(v[i]);
	}
	// 以i结尾下降序列
	rep(i, 0, n){
	    f[i]=1;
	    rep(j, 0, i){
	        if(a[j]>=a[i]){
	            f[i]=max(f[i], f[j]+1);
	        }
	    }
	    ans=max(ans, f[i]);
	    int k=0;
        while(k<cnt&&f1[k]<a[i]){
            k++;    
        } 
        // a[i]开创一套新拦截系统   
        if(k==cnt){
            f1[cnt++]=a[i];  
        } 
        // a[i]成为第k套拦截系统最后一个导弹高度
        else{
            f1[k]=a[i];    
        }
	}
	printf("%lld\n%lld\n", ans, cnt);
}

y总代码

#include <sstream>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1010;

int n;
int h[N], f[N], q[N];

int main()
{
    string line;
    getline(cin, line);
    stringstream ssin(line);
    while (ssin >> h[n]) n ++ ;

    int res = 0, cnt = 0;
    for (int i = 0; i < n; i ++ )
    {
        f[i] = 1;
        for (int j = 0; j < i; j ++ )
            if (h[i] <= h[j])
                f[i] = max(f[i], f[j] + 1);
        res = max(res, f[i]);

        int k = 0;
        while (k < cnt && q[k] < h[i]) k ++ ;
        if (k == cnt) q[cnt ++ ] = h[i];
        else q[k] = h[i];
    }

    printf("%d\n", res);
    printf("%d\n", cnt);
    return 0;
}

tips

读入处理
输入流高级语法

    string line;
    getline(cin, line);
    stringstream ssin(line);
    while (ssin >> h[n]) n ++ ;

while (cin >> h[ ++ n]);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞滕人生TYF

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值