Max Sum
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 125 Accepted Submission(s) : 27
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Case 1: 14 1 4 Case 2:7 1 6
最大字段和 多了输出起始位置
先回顾一下最大字段和的状态转移方程
dp[i]=max(a[i],0) (i=1)
dp[i]=max(dp[i-1]+a[i],0)(2<+i<=n)
dp[i]是以i结尾的最大字段和
有了这个基础 这个题就容易了 因为样例2中是从头输出到尾 所以max判断是要注意 是<0不是<=0
对数组做累加 <0是则跳出当前状态 记下当前的末尾 也就是下一个状态的开始位置 重复即可
最大连续子序列跟这个一模一样 代码基本不用动 把位置改成当前位置的价值就OK了
#include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; int a[100001]; struct G { int m; int s; int e; }ans; int maxx(int a,int b) { if(a>b)return a; else return b; } bool cmp(G A,G B) { return A.m>B.m; } int main() { int i,j,k,t,max,n; scanf("%d",&t); int c=1; for(;c<=t;c++) { scanf("%d",&n); int flag=0; memset(a,0,sizeof(a)); if(n==0)break; for(i=1;i<=n;i++) { scanf("%d",&a[i]); } max=a[1];//数据初始化 ans.m=a[1]; ans.s=1; ans.e=1; k=1; for(i=2;i<=n;i++) { if(max<0) { max=0; //恢复0 k=i; //记下上一个状态的末位置 } max+=a[i]; if(ans.m<max) { ans.m=max; ans.s=k; ans.e=i; } } printf("Case %d:\n%d %d %d\n",c,ans.m,ans.s,ans.e); if(c!=t)printf("\n"); } return 0; }
最大连续子序列
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 63 Accepted Submission(s) : 29
Problem Description给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ..., <br>Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个, <br>例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和 <br>为20。 <br>在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该 <br>子序列的第一个和最后一个元素。<br>
Input测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。<br>
Output对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元 <br>素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。 <br>
Sample Input6 -2 11 -4 13 -5 -2 10 -10 1 2 3 4 -5 -23 3 7 -21 6 5 -8 3 2 5 0 1 10 3 -1 -5 -2 3 -1 0 -2 0
Sample Output#include<iostream>20 11 13 10 1 4 10 3 5 10 10 10 0 -1 -2 0 0 0
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int a[10001];
struct G
{
int m;
int s;
int e;
}ans;
int maxx(int a,int b)
{
if(a>b)return a;
else return b;
}
bool cmp(G A,G B)
{
return A.m>B.m;
}
int main()
{
int i,j,k,max,n;
while(cin>>n)
{
int flag=0;
memset(a,0,sizeof(a));
if(n==0)break;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]>=0)
flag=1;
}
max=a[1];
ans.m=a[1];
ans.s=1;
ans.e=1;
for(i=2;i<=n;i++)
{
if(max<0)
{
max=0;
k=i;
}
max+=a[i];
if(ans.m<max)
{
ans.m=max;
ans.s=k;
ans.e=i;
}
}
if(flag==1)cout<<ans.m<<" "<<a[ans.s]<<" "<<a[ans.e]<<endl;
else cout<<0<<" "<<a[1]<<" "<<a[n]<<endl;
}
return 0;
}