Lintcode 389 Longest Increasing Continuous subsequence II

来源:互联网 发布:域名不用备案 编辑:程序博客网 时间:2024/04/26 06:17

Give you an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix. (The definition of the longest increasing continuous subsequence here can start at any row or column and go up/down/right/left any direction)


通过最小堆的动态规划迭代依次更新各个二维节点的最长递增序列的值。


这道题我开始用的是dfs,从首元素开始递增遍历更新二维节点的最长递增序列的值,但是最坏复杂度达到了n^4(逆序的时候)。

但是经过仔细一想,发现根本不需要进行深度遍历,只需要从小到大依次对节点的四个方向的值进行更新节点的最长递增序列,并更新最长值,直至便利完整个堆。时间复杂度为堆的构建时间 2(n^2)logn + 出堆时间4*2(n^2)logn,故总的时间复杂度为10(n^2)logn。



struct Point{    int x;    int y;    int v;    Point(int a,int b,int c):x(a),y(b),v(c){}};struct ValCmp{    bool operator() (const Point &A,const Point &B){        return A.v > B.v;    }};class Solution {public:    /**     * @param A an integer matrix     * @return  an integer     */    int longestIncreasingContinuousSubsequenceII(vector<vector<int>>& A) {        // Write your code here        int m = A.size();        if(!m) return 0;        int n = A[0].size();        if(!n) return 0;        int res[m][n],maxres=1;        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                res[i][j] = 1;            }        }        priority_queue<Point,vector<Point,allocator<Point>>,ValCmp> pq;        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                pq.push({i,j,A[i][j]});            }        }        Point tmpp(0,0,0);        int i,j,v;        while(!pq.empty()){            tmpp = pq.top();            pq.pop();            i = tmpp.x;j = tmpp.y;v = tmpp.v;            if(i > 0 && A[i][j] < A[i-1][j] && res[i-1][j] < res[i][j] + 1){//up                res[i-1][j] = res[i][j] + 1;            }            if(j > 0 && A[i][j] < A[i][j-1] && res[i][j-1] < res[i][j] + 1){//left                res[i][j-1] = res[i][j] + 1;            }            if(i < m-1 && A[i][j] < A[i+1][j] && res[i+1][j] < res[i][j] + 1){//down                res[i+1][j] = res[i][j] + 1;            }            if(j < n-1 && A[i][j] < A[i][j+1] && res[i][j+1] < res[i][j] + 1){//right                res[i][j+1] = res[i][j] + 1;            }            maxres = max(maxres,res[i][j]);        }                return maxres;    }};


0 0