HDU1087 Super Jumping! Jumping! Jumping!(最長上升子序列和)
原題地址:http://acm.hdu.edu.cn/showproblem.php?pid=1087
題意
一道水題,就是要求玩家從棋盤開始跳到結束中間所經過的棋子和最大是多少,注意每個人都必須從一個棋子跳到另一個更大的棋子,且可以穿過任意多個棋子。
思路
典型的LIS的一個變形,但這裏我們不能用O(nlogn)的解法,因爲該解法只能知道最長子序列的長度,而不能知道最長子序列是哪些,所以只能用O(n^2)的解法,狀態轉移方程是:dp[i] = Math.max(dp[i], dp[j] + nums[i]);
AC代碼
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
/**
* Created with IntelliJ IDEA.
*
* @author wanyu
* @Date: 2018-02-13
* @Time: 20:44
* To change this template use File | Settings | File Templates.
* @desc
*/
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while (true) {
in.nextToken();
int n = (int) in.nval;
if (n == 0) break;
int nums[] = new int[n];
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
in.nextToken();
nums[i] = (int) in.nval;
dp[i] = nums[i];//初始化
}
int max = Integer.MIN_VALUE;//保存最大的和
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + nums[i]);
}
max = Math.max(max, dp[i]);
}
}
System.out.println(max);
}
}
}