CF 977F Consecutive Subsequence 离散化+dp

题意:

给定长度为n的序列a[] (n<=1e5 && a[i] <= 1e9),要求输出最长的相邻数值差一的最长上升序列;

思路:

如果a[i]很小的话,我们可以用dp[j]表示以j结尾的序列的最大长度,

然后从左往右遍历,对于当前a[i],我们可以得到递推式:dp[a[i]] = max( dp[a[i]], dp[a[i]-1]+1 );

然后想到对a[] 离散化,这样得到得值小于等于a[]的长度;

同时保存最长上升序列的结尾的值,然后从后往前遍历输出;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 7;
const ll mod = 1e9+7;
int n, a[maxn], ans = 0, anss;
map<int, int> mp;
int dp[maxn];
void print(int anss) {
    stack<int> sk;
    for(int i = n; i >= 1; --i) {
        if(a[i] == anss) { sk.push(i); anss--; }
    }
    while(true) {
        int t = sk.top(); sk.pop();
        cout << t;
        if(sk.empty()) break;
        else cout << " ";
    }
}
int main() {
    scanf("%d", &n);
    int id = 1;
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &a[i]);
        if(!mp[a[i]]) { mp[a[i]] = id++; }
        int t = mp[a[i]];
        dp[t] = max(dp[t], dp[mp[a[i]-1]]+1);
        if(dp[t] > ans) { ans = dp[t]; anss = a[i];}
    }
    printf("%d\n", ans);
    print(anss);
    return 0;
}







猜你喜欢

转载自blog.csdn.net/xiang_6/article/details/80385906