HDU 1003 求最大子段和的动态规划

http://acm.hdu.edu.cn/showproblem.php?pid=1003

算法基本思路:

/*
 * 此题是动态规划找到 a[1……n] 中 最大的字段和
 * 令  b[j] 为 在 子段中 k->j 是最大值 k∈ (1,j)
 * 那么 状态转移方程 为  b[j] = max{ b[j-1]+a[j] , a[j]};
 */


import java.util.Scanner;


/*
 * 此题是动态规划找到 a[1……n] 中 最大的字段和
 * 令  b[j] 为 在 子段中 k->j 是最大值 k∈ (1,j) 
 * 那么 状态转移方程 为  b[j] = max{ b[j-1]+a[j] , a[j]};
 */
public class HDU1003 {

	private int sum=0, b=0;
	private static int inf = (-1)*1<<30;
	private int s,t;
	public void dp( int a[],int n){
		sum = inf ;b = inf ;s=0;t=0;
		int stemp=0, ttemp = 0;
		for(int i=0; i<n; i++){
			if(b>=0){
				b+= a[i];
				ttemp = i;
			}else{
				b = a[i];
				stemp = i;
				ttemp = i;
			}
			if(sum < b){
				sum = b;
				s = stemp+1;
				t = ttemp+1;
			}
		}
	}
	public void solve(){
		Scanner sc = new Scanner(System.in);
		int n,c;
		int a[];
		n = sc.nextInt();
		for( int i=1; i<=n;i++){
			c = sc.nextInt();
			a = new int[c];
			for(int j=0; j<c; j++ ){
				a[j] = sc.nextInt();
			}
			dp(a,c);
			System.out.println("Case "+i+":");
			System.out.println(sum+" "+s+" "+t);
			if( i <n){
				System.out.println();
			}
		}
	}
	public static void main(String[] args) {
		new HDU1003().solve();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值