hdu1003(Max Sum)DP類題目
阿新 • • 發佈:2018-11-25
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2
5
6 -1 5 4 -7
7
0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
題意:這題目是想要說明一串資料中,找出它的最大值,這個最大值得保證是某一個數到另一個數的和。例如:6 -1 5 4 -7,最大值便為14,其計算過程為(6-1+5+4);0 6 -1 1 -6 7 -5,最大值便為7,其計算過程為(0+6-1+1-6+7)。這是比較簡單的DP題,但是這道題最關鍵的,在於換行的問題:具體的輸入輸出應該為:
2
5
6 -1 5 4 -7
Case 1:
14 1 4
7
0 6 -1 1 -6 7 -5 Case 2:
7 1 6 AC程式碼:
#include<stdio.h>
int dp[100005];
int main()
{
int n,m,i,num;
int sum,start,zuo,you;
m=0;
scanf("%d",&n);
while(n--)
{
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&dp[i]);
}
start=0;
zuo=0;
you=0;
sum=dp[0];
for(i=1;i<num;i++)
{
if(dp[i-1]>=0)
{
dp[i]+=dp[i-1];
}
else
{
start=i;
}
if(dp[i]>sum)
{
sum=dp[i];
zuo=start;
you=i;
}
}
if(m)
{
printf("\n");
}
printf("Case %d:\n",++m);
printf("%d %d %d\n",sum,zuo+1,you+1);
}
return 0;
}
5
6 -1 5 4 -7
Case 1:
14 1 4
7
0 6 -1 1 -6 7 -5 Case 2:
7 1 6 AC程式碼:
#include<stdio.h>
int dp[100005];
int main()
{
int n,m,i,num;
int sum,start,zuo,you;
m=0;
scanf("%d",&n);
while(n--)
{
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&dp[i]);
}
start=0;
zuo=0;
you=0;
sum=dp[0];
for(i=1;i<num;i++)
{
if(dp[i-1]>=0)
{
dp[i]+=dp[i-1];
}
else
{
start=i;
}
if(dp[i]>sum)
{
sum=dp[i];
zuo=start;
you=i;
}
}
if(m)
{
printf("\n");
}
printf("Case %d:\n",++m);
printf("%d %d %d\n",sum,zuo+1,you+1);
}
return 0;
}