zoukankan      html  css  js  c++  java
  • [topcoder]ZigZag

    http://community.topcoder.com/stat?c=problem_statement&pm=1259&rd=4493

    动态规划题。如果不用DP,暴力的应当在2^n*n的复杂度吧。动态规划现在我的思维还老停留在一维而且没有第二层循环。但其实如果一开始的复杂度很高,稍微有几个循环,指数级别,一点问题没有。

    题目描述:给出n个数:A[1], A[2], ... , A[n],求最长的子序列的长度,子序列中相邻数之间的差值是正负交替出现的。
    f1[i]表示 最后一个数是A[i]并且A[i]和前一个数的差值为正的最长子序列的长度。
    f2[i]表示最后一个数是A[i]并且A[i]和前一个数的差值为负的最长子序列的长度。
    对于f1[i], 和它有联系的子问题是f2[j] (0<= j < i).f1[i] = max(f1[i], f2[j]+1) (A[i] > A[j])
    对于f2[i], 和它有联系的子问题是 f1j] (0 <= j < I),f2[i] = max(f2[i], f1[j]+10 (A[i] < A[j])
    计算子问题的顺序:A数组下标从小到大,顺推。

    public class ZigZag {
    	public int longestZigZag(int[] sequence) {
    		if (sequence.length == 0) return 0;
    		
    		int[] up = new int[sequence.length];
    		int[] down = new int[sequence.length];		
    		up[0] = 1;
    		down[0] = 1;
    
    		int ret = 0;		
    		for (int i = 1 ; i < sequence.length; i++) {
    			int max_up = 0;
    			int max_down = 0;
    			for (int j = 0; j < i; j++) {
    				if (sequence[j] > sequence[i]) {
    					if (down[j] > max_down) max_down = down[j];
    				}
    				else if (sequence[j] < sequence[i]) {
    					if (up[j] > max_up) max_up = up[j];
    				}
    			}
    			up[i] = max_down + 1;
    			down[i] = max_up + 1;
    			
    			if (up[i] > ret) ret = up[i];
    			if (down[i] > ret) ret = down[i];
    		}		
    		
    		return ret;
    	}
    }
    

      

  • 相关阅读:
    System.IO.MemoryStream.cs
    System.IO.Stream.cs
    System.Web.HttpContext.cs
    System.Text.Encoding.cs
    System.Web.HttpRuntime.cs
    System.Web.Caching.Cache.cs
    System.Diagnostics.Stopwatch.cs
    FrameBuffer
    Java实现 洛谷 P1422 小玉家的电费
    Java实现 洛谷 P1422 小玉家的电费
  • 原文地址:https://www.cnblogs.com/lautsie/p/3250929.html
Copyright © 2011-2022 走看看