动态规划:What Goes Up

此博客介绍了一个算法,用于从整数序列中找出最长的严格递增子序列。包含输入输出规范、代码实现及样例解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转:http://blog.youkuaiyun.com/kongming_acm/article/details/5725922

1263: What Goes Up


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s8192K896219Standard

Write a program that will select the longest strictly increasing subsequence from a sequence of integers.

Input

The input file will contain a sequence of integers (positive, negative, and/or zero). Each line of the input file will contain one integer.

Output

The output for this program will be a line indicating the length of the longest subsequence, a newline, a dash character ('-'), a newline, and then the subsequence itself printed with one integer per line. If the input contains more than one longest subsequence, the output file should print the one that occurs last in the input file.

 

Notice that the second 8 was not included -- the subsequence must be strictly increasing.

Sample Input

 

-7 10 9 2 3 8 8 6

Sample Output

 

4 - -7 2 3 6

 

 

package com.iteye.caoruntao.zoj;

import java.util.Scanner;

/**
 * @author caoruntao
 *
 */
public class WhatGoesUp {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 0;
		int a[] = new int[10000];
		int dp[] = new int[10000];
		dp[0] = 1;
		int pre[] = new int[10000];
		pre[0] = -1;
		int num[] = new int[10000];
		
		Scanner sc = new Scanner(System.in);
		while(sc.hasNextInt()){
			a[n++] = sc.nextInt();
		}
		sc.close();
		
		for(int i=0; i<n; i++){
			dp[i] = 1;
			pre[i] = -1;
			for(int j=0; j<i; j++){
				if(a[j] < a[i] && dp[i] <= dp[j]+1){
					dp[i] = dp[j]+1;
					pre[i] = j;
				}
			}
		}
		
		int maxLen = 0;
		int maxIndex = 0;
		for(int i=0; i<n; i++){
			if(maxLen < dp[i]){
				maxLen = dp[i];
				maxIndex = i;
			}
		}
		
		int l = 0;
		int k = maxIndex;
		while(k != -1){
			num[l++] = a[k];
			k = pre[k];
		}
		System.out.println(maxLen);
		System.out.println("-");
		for(int j=l-1; j>=0; j++){
			System.out.println(num[j]);
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值