最长上升子序列模型 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]);