• *[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;
    }
    

      

  • 相关阅读:
    "#"
    网络请求
    iOS_正则表达式判断手机型号、邮箱、手机号、身份证、昵称、密码等
    程序员
    js交互
    android 性能优化
    Android 开源的项目框架
    Android 开源框架案例
    Android Listview上拉刷新加载框架
    android 上传文件到服务器FIP
  • 原文地址:https://www.cnblogs.com/lautsie/p/4060969.html
Copyright © 2020-2023  润新知