现在的位置: 首页 > 综合 > 正文

HDU4223&&NYOJ422 首届华中区程序设计邀请赛暨第十届武汉大学程序设计大赛

2013年08月16日 ⁄ 综合 ⁄ 共 2010字 ⁄ 字号 评论关闭

      这道题是武大校赛的题目,和我们OJ以前月赛时的题目一样,只不过我们OJ当时还让求绝对值最大值了,这道题目只让求绝对值最小了。直接用以前的代码就可以ac。就这道题目来说,因为让求绝对值最小的和,所以我们可以先用sum[i]数组保留原数组的前i项和,再对sum数组从小到大排序。这样,最小值就在sum[i]-sum[i-1]和sum[i-1]之间,循环比较久可以了。至于求最大值,排好序后,最大值只可能是sum[n],sum[1],sum[n]-sum[1]中的一个,比较即可。题目:

Dynamic Programming?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 24    Accepted Submission(s): 12


Problem Description
Dynamic Programming, short for DP, is the favorite of iSea. It is a method for solving complex problems by breaking them down into simpler sub-problems. It is applicable to problems exhibiting the properties of overlapping sub-problems which are only slightly
smaller and optimal substructure.
Ok, here is the problem. Given an array with N integers, find a continuous subsequence whose sum’s absolute value is the smallest. Very typical DP problem, right?
 


Input
The first line contains a single integer T, indicating the number of test cases.
Each test case includes an integer N. Then a line with N integers Ai follows.

Technical Specification
1. 1 <= T <= 100
2. 1 <= N <= 1 000
3. -100 000 <= Ai <= 100 000

 


Output
For each test case, output the case number first, then the smallest absolute value of sum.
 


Sample Input
2 2 1 -1 4 1 2 1 -2
 


Sample Output
Case 1: 0 Case 2: 1
 

ac代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <climits>
#include <string.h>
using namespace std;
const int N=1010;
int a[N],sum[N];
int main(){
	//freopen("1.txt","r",stdin);
	int ncase,n,kk=0;
	scanf("%d",&ncase);
	while(ncase--){
	 scanf("%d",&n);
	 memset(sum,0,sizeof(sum));
	 memset(a,0,sizeof(a));
	 for(int i=0;i<n;++i){
	   scanf("%d",&a[i]);
	 }
	 sum[0]=a[0];
	 for(int i=1;i<n;++i)
		 sum[i]=sum[i-1]+a[i];
	 sort(sum,sum+n);
	 int mmax=0;
	 if(fabs((double)(sum[n-1]))>mmax)
		 mmax=fabs((double)(sum[n-1]));
	 if(fabs((double)(sum[0]))>mmax)
		 mmax=fabs((double)(sum[0]));
	 if(fabs((double)(sum[n-1]-sum[0]))>mmax)
		 mmax=fabs((double)(sum[n-1]-sum[0]));
	 int mmin=fabs((double)(sum[0]));
	 for(int i=0;i<n-1;++i){
	   if(fabs((double)(sum[i+1]-sum[i]))<mmin)
		   mmin=fabs((double)(sum[i+1]-sum[i]));
	   if(fabs((double)(sum[i]))<mmin)
		   mmin=fabs((double)(sum[i]));
	 }
	 //printf("%d  %d\n",mmax,mmin);
	 printf("Case %d: %d\n",++kk,mmin);
	}
  return 0;
}        

抱歉!评论已关闭.