hdu1003(蒟蒻在成長)
阿新 • • 發佈:2018-11-11
</pre>Max Sum</h1><strong><span style="font-family:Arial;font-size:12px;color:green;font-weight:bold">Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 224167 Accepted Submission(s): 52732</span></strong><div class="panel_title" align="left">Problem Description</div><div class="panel_content">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.</div><div class="panel_bottom"> </div><div class="panel_title" align="left">Input</div><div class="panel_content">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).</div><div class="panel_bottom"> </div><div class="panel_title" align="left">Output</div><div class="panel_content">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.</div><div class="panel_bottom"> </div><div class="panel_title" align="left">Sample Input</div><div class="panel_content"><pre><div style="font-family:Courier New,Courier,monospace">2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5</div>
Sample Output Case 1: 14 1 4 Case 2: 7 1 6
最大子數列和 內容不再詳述
暴力演算法優化:除去負數為開頭的子數列 對於大資料依然TLE
還是把目光投向最不擅長的DP。。。
分析問題:對於a[1]---a[n]
以第一個數為結尾:maxsum[1]=a[1]
以第二個數:maxsum[2]=max(a[1]+a[2],a[2])
以第三個數:maxsum[3]=max(a[1]+a[2]+a[3],a[2]+a[3],a[3])=max(maxsum[2]+a[3],a[3])
不難推理出maxsum[n]=max(maxsum[n-1]+a[n],a[n])
那麼以max記錄當前最大子數列和,以ans表示maxsum。顯然若ans<0,加上a[n]後一定小於a[n],故令ans=0即可使ans=a[n],若ans>0則直接加上a[n]一定大於a[n].
最後是記錄開頭和結尾位置,顯然我們需要先使開頭為1,在max被更新時,結尾即+1,而在ans<0時,開頭將變成當前位的下一位。temp存在的目的是在存在多組相同資料時,記錄第一次最大值得出現位置。避免出現開頭是最後一次最大子數列的開頭,而結尾是第一次最大子數列的結尾。(即開頭結尾要同時更新)
原始碼:
package sduoj無限滾動;
import java.util.Scanner;
import java.math.*;
public class haaha
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int T=s.nextInt();
int cout=1;
int[] a=new int[100000];
for (int i=1;i<=T;i++)
{
int ans=0;int max=-1000000000;
int k=s.nextInt();
int start=1,end=k,temp=1;
for (int j=1;j<=k;j++)
{
a[j]=s.nextInt();
ans+=a[j];
if (ans>max)
{
max=ans;
start=temp;
end=j;
}
if (ans<0)
{
ans=0;
temp=j+1;
}
}
if(cout == 1)
{
System.out.println("Case "+i+":");
System.out.println(max+" "+start+" "+end);
cout = 0;
}
else
{
System.out.println();
System.out.println("Case "+i+":");
System.out.println(max+" "+start+" "+end);
}
}
}
}