http://acm.hdu.edu.cn/showproblem.php?pid=1003
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
以为每行输入数字以空格隔开,以回车符作为一组的结束标志
//Problem 1003:Max Sum #include "stdio.h" int main(){ int Case,c=1; scanf("%d",&Case); int i,j,thisSum,maxSum; int a[50]; while (c<=Case) { thisSum=maxSum=0; int n=0; int begin,end; for(i=0;;i++) { scanf("%d",&a[i]); n++; //计算输入个数 if(getchar()=='\n')break; //遇回车中断 } for (i=0;i<n ;i++ ) { thisSum=0;//this line is important for (j=i;j<n ;j++ ) { thisSum=thisSum+a[j]; if (thisSum>maxSum) { maxSum=thisSum; begin=i+1; end=j+1; printf("%d %d %d\n",maxSum,begin,end); } } } printf("Case %d\n",c); c++; printf("%d %d %d\n",maxSum,begin,end); } return 0; }
//Problem 1003:Max Sum #include "stdio.h" int main(){ int Case,c=1; scanf("%d",&Case); int i,j,thisSum,maxSum; int a[50]; while (c<=Case) { thisSum=maxSum=0; int n=0; int begin,end; //数组长度 scanf("%d",&n); //录入数组 for (i=0;i<n ;i++ ) { scanf("%d",&a[i]); } //开始计算 for (i=0;i<n ;i++ ) { thisSum=0;//this line is important for (j=i;j<n ;j++ ) { thisSum=thisSum+a[j]; if (thisSum>maxSum) { maxSum=thisSum; begin=i+1; end=j+1; } } } printf("Case %d\n",c); c++; printf("%d %d %d\n",maxSum,begin,end); } return 0; }
本代码上机在本地运行正常,但提交之后却显示答案错误
http://acm.hdu.edu.cn/discuss/problem/post/reply.php?postid=19403&messageid=1&deep=0
动态规划是较好的方案,还没学到,同时还没找到枚举的方法提交通过不了的原因
#define maxn 100010 int a[maxn],dp; int main() { int i,n,t,j,u,v,s=1,m,x; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&a[i]); printf("Case %d:\n",s++); dp=m=a[1]; u=v=x=1; for(i=2;i<=n;i++) { if(dp>=0) dp+=a[i]; else dp=a[i],x=i; if(m<dp) v=i,m=dp,u=x; } printf("%d %d %d\n",m,u,v); if(t!=0) printf("\n"); } return 0; }
#include <stdio.h> // 此处若为10000则在线运行会超时 #define maxn 50 int a[maxn]; int main() { int i,j,t,n,s=1; //测试个数 scanf("%d",&t); while(t--) { scanf("%d",&n); //从1开始数 for(i=1;i<=n;i++) scanf("%d",&a[i]); //s记录第几次 printf("Case %d:\n",s++); int thisSum,maxSum,begin,end; maxSum=a[1]; begin=end=1; for (i=1;i<=n ;i++ ) { thisSum=0;//this line is important for (j=i;j<n ;j++ ) { thisSum=thisSum+a[j]; if (thisSum>maxSum) { maxSum=thisSum; begin=i; end=j; } } } printf("%d %d %d\n",maxSum,begin,end); if(t!=0) printf("\n"); } return 0; }
g++运行之后一直是【Runtime Error
(ACCESS_VIOLATION)】