• *[codility]AscendingPaths


    https://codility.com/programmers/challenges/magnesium2014

    图形上的DP,先按照路径长度排序,然后依次遍历,状态是使用到当前路径为止的情况;每个节点记录以该节点结束的最长路径,这样加入新的路径时去更新。注意路径是双向的~

    #include <vector>
    #include <algorithm>
    using namespace std;
     
    struct Road {
        int start;
        int end;
        int val;
    };
     
    bool cmp(const Road &a, const Road &b) {
        return a.val < b.val;
    }
     
    int solution(int N, vector<int> &A, vector<int> &B, vector<int> &C) {
        int M = A.size();
        vector<Road> roads(M);
        for (int i = 0; i < M; i++) {
            roads[i].start = A[i];
            roads[i].end = B[i];
            roads[i].val = C[i];
        }
        sort(roads.begin(), roads.end(), cmp);
        vector<pair<int, int>> dp(N); // first: the longest length ends with this node; second: the last path val to this node;
        int result = 0;
        for (int i = 0; i < M; i++) {
            int x2y_len = dp[roads[i].end].first;
            int x2y_val = dp[roads[i].end].second;
            if (roads[i].val > dp[roads[i].start].second &&
                dp[roads[i].start].first + 1 > dp[roads[i].end].first) {
                x2y_len = dp[roads[i].start].first + 1;
                x2y_val = roads[i].val;
                result = max(x2y_len, result);
            }
            // the other side
            int y2x_len = dp[roads[i].start].first;
            int y2x_val = dp[roads[i].start].second;
            if (roads[i].val > dp[roads[i].end].second &&
                dp[roads[i].end].first + 1 > dp[roads[i].start].first) {
                y2x_len = dp[roads[i].end].first + 1;
                y2x_val = roads[i].val;
                result = max(y2x_len, result);
            }
            dp[roads[i].end].first = x2y_len;
            dp[roads[i].end].second = x2y_val;
            dp[roads[i].start].first = y2x_len;
            dp[roads[i].start].second = y2x_val;
        }
        return result;
    }
    

      

  • 相关阅读:
    ArrayList和CopyOnWriteArrayList
    UML类关系
    Vmware下mint os的安装
    Java VisualVM无法检测到本地java程序 的 解决办法
    谜之闭包
    虚拟DOM(Virtual DOM)
    ES6箭头函数与普通函数的区别
    HTML中 select 与datalist的异同
    备战前端面试
    javascript获取数组中的最大值/最小值
  • 原文地址:https://www.cnblogs.com/lautsie/p/4060969.html
Copyright © 2020-2023  润新知