• P1970 花匠


    状态定义是dp中非常重要的,可以直接影响到效率,如此题,第一种思路是:

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 100005;
    struct node {
        int high, value;
        bool operator < (const node &i) const{
            return (this->value < i.value);
        }
    };
    int main() {
        int n;
        scanf("%d", &n);
        int fl[maxn];
        for(int i = 1; i <= n; i++) scanf("%d", &fl[i]);
        int f[maxn], g[maxn];
        priority_queue<node> pf, pg;
        f[1] = 1; g[1] = 1;
        pf.push({fl[1], f[1]}); pg.push({fl[1], g[1]});
        for(int i = 2; i <= n; i++) {
            node x = pf.top();
            node y = pg.top();
            pf.pop(); pg.pop();
            int cnt = 0;
            while(x.high <= fl[i] && cnt < pf.size()) {
                node e = pf.top(); pf.pop();
                pf.push(x); x = e; cnt++;
            }
            cnt = 0;
            while(y.high >= fl[i] && cnt < pg.size()) {
                node e = pg.top(); pg.pop();
                pg.push(y); y = e;cnt++;
            }
            f[i] = 1; g[i] = 1;
            if(x.high > fl[i]) g[i] = x.value + 1;
            if(y.high < fl[i]) f[i] = y.value + 1;
            pf.push({fl[i], f[i]});
            pg.push({fl[i], g[i]});
            pf.push(x);
            pg.push(y);
        }
        int ans = 0;
        for(int i = 1; i <= n; i++) {
            ans = max(ans, f[i]);
            ans = max(ans, g[i]);
        }
        cout << ans;
    }
    

    定义f[i]为以i结束,加上优先队列优化,很麻烦,也容易被卡掉,复杂度不稳定,从O(nlogn)~O(n2)

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 100005;
    int main() {
        int n;
        scanf("%d", &n);
        int fl[maxn];
        for(int i = 1; i <= n; i++) scanf("%d", &fl[i]);
        int f[maxn], g[maxn];
        f[1] = 1; g[1] = 1;
        for(int i = 2; i <= n; i++) {
            if(fl[i] > fl[i-1]) {
                f[i] = max(f[i-1], g[i - 1]+1);
                g[i] = g[i-1];
            }
            else if(fl[i] < fl[i-1]) {
                f[i] = f[i-1];
                g[i] = max(g[i-1], f[i-1] + 1);
            }
            else {
                f[i] = f[i-1];
                g[i] = g[i-1];
            }
        }
        cout << max(f[n], g[n]);
    }
    

    定义f[i]为前i个数,不需要优化,效率高,复杂度降低到了O(n)!
    算法真神奇。

  • 相关阅读:
    python求pi的方法
    Python:字符串格式化
    Python time模块学习
    开源的PaaS平台
    车牌识别技术实现方式及应用场景
    ASP.NET车辆管理系统
    Spark+Hadoop+IDE环境搭建
    大数据平台技术方案及案例
    主流大数据平台及解决方案对比
    大数据平台架构——通用版
  • 原文地址:https://www.cnblogs.com/gengchen/p/6036526.html
Copyright © 2020-2023  润新知