Codeforces Round #479 (Div. 3) F - Consecutive Subsequence(思维)

the link

题意:给定一串数组,求最长的每个数比其上一个数大一的子序列
解析:
刚开始以为是最长上升子序列的变形,然后就在网上找了半小时的代码,最后才发现是一道并不难的题

#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define inf 0x3f3f3f3f
#define pll pair<ll,ll>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define rep1(i,a,b) for(int i=a;i>=b;i--)
#define rson rt<<1|1,m+1,r
#define lson rt<<1,l,m
using namespace std;
const int N=2e5+100;
int n, arr[N], f[N], ans, maxi, las[N];
map<int, int> mp;
/*
    对于每个位置,用f[i]表示以位置i为结束的序列的长度
    用map记录这个数字的位置
    las数组记录这个位置的上一个位置
    最后用递归逆序输出即可(当然也有别的输出方法)

*/
void outp(int x)
{
    if (x == 0) return;
    outp(las[x]);
    cout<<x<<' ';
}
int main()
{
    cin>>n;
    f[0] = 0;
    maxi = 0;
    for (int i = 1; i <= n; i++)
    {
        cin>>arr[i];
        f[i]=f[mp[arr[i]-1]] + 1;
        las[i]=mp[arr[i]-1];
        mp[arr[i]]=i;
        if (f[i]>maxi) maxi=f[i], ans=i;
    }
    cout<<maxi<<endl;
    outp(ans);
    cout<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ffgcc/article/details/80222975