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

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

标签: DP


题目链接

分析

虽然是不难的dp,但是放在F题的位置以为很难,我还是想复杂了结果搞了好久才搞出来,而且还遇到了std::unordered_map的坑。CF上有组数据专门卡unordered_map然后就tle了。
因为unordered_map是hash存储,所以会将hash值相同的放在一个桶里,但是在桶中查找的时候复杂度是\(O(n)\)的,在codeforces上找到了如下的优化方法

unordered_map<int,int>mp;
mp.reserve(1024);
mp.max_load_factor(0.25);

这样就不会tle了。
具体原理看下面两个链接吧:
http://codeforces.com/blog/entry/21853
http://en.cppreference.com/w/cpp/container/unordered_map/reserve

代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <map>
#include <unordered_map>
using namespace std;
const int maxn=200050;
int a[maxn];
unordered_map<int,int> dp;
int main(){
    dp.reserve(maxn);
    dp.max_load_factor(0.25);

    int n;
    scanf("%d", &n);
    int M=0,e=0;
    for(int i = 0; i < n; ++i){
        scanf("%d", a+i);
        int& u=dp[a[i]];
        if(dp.count(a[i]-1)) u=max(u,dp[a[i]-1]+1);
        else u=1;
        if(u>M){
            M=u;
            e=a[i];
        }
    }
    int b=e-M+1;
    cout << M << endl;
    for(int i = 0; i < n; ++i){
        if(a[i]==b){
            printf("%d ", i+1);
            b++;
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/sciorz/p/9007384.html