爱思创 150247 Consecutive Subsequence 题解
思路:
此题跟最长上升子序列类似
可以使用动态规划做
\(dp[i]\) 意思为在阶段i(以数字 i 为结尾)的最长递增序列
转移方程为 \(dp[a[i]] = dp[a[i] - 1] + 1;\)
最长子序列的长度k在代码中是 \(ans\),此子序列中最大的数为 \(maxi\),则最小数为 \(maxi - ans + 1\)
输出子序列时找到最小值,输出,输出后更改最小值
#include<bits/stdc++.h>
using namespace std;
map<long long, int> dp;
int a[10000005];
int main()
{
int n, ans = 0;
long long x, maxi = 0;
cin >> n;
for(int i = 1; i <= n; i ++)
{
cin >> a[i];
dp[a[i]] = dp[a[i] - 1] + 1;//转移方程
if(dp[a[i]] > ans) ans = dp[a[i]], maxi = a[i];//更新长度和最大值
}
cout << ans << endl;
for(int i = 1; i <= n; i ++)
{
if(a[i] == maxi - ans + 1)//找到最小值
{
cout << i << ' ';
maxi ++;//更改最小值
}
}
return 0;
}
hello, I'm yuzihang, if you need to copy this, please quote this url: https://www.cnblogs.com/yuzihang/articles/16678396.html

浙公网安备 33010602011771号