一直都没来得及完成关于算法课上的实验任务,今天终于算是有时间把这个给写了。
#include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<iostream> using namespace std; //蛮力法 int maxSum(int a[],int n){ int maxsum=0; int sum=0; for(int i=0;i<n;i++){ sum=a[i]; for(int j=i+1;j<n;j++){ if(sum>=maxsum){ maxsum=sum; } sum+=a[j]; } } return maxsum; } //分治法 int maxSum1(int a[],int left,int right){ int sum=0; if(left==right){ if(a[left]>0) sum=a[left]; else sum=0; } else{ int center=(left+right)/2; int leftsum=maxSum1(a,left,center); int rightsum=maxSum1(a,center+1,right); int s1=0,lefts=0; for(int i=center;i>left;i--){ lefts+=a[i]; if(lefts>s1) s1=lefts; } int s2=0,rights=0; for(int i=center+1;i<=right;i++){ rights+=a[i]; if(rights>s2) s2=rights; } sum=s1+s2; if(sum<leftsum) sum=leftsum; if(sum<rightsum) sum=rightsum; } return sum; } //动态规划 int Dpsum(int a[],int n){ int sum=0; int *b=(int *)malloc(n*sizeof(int)); b[0]=a[0]; for(int i=1;i<n;i++){ if(b[i-1]>0){ b[i]=b[i-1]+a[i]; } else b[i]=a[i]; } for(int j=0;j<n;j++){ if(b[j]>sum) sum=b[j]; } delete []b; return sum; } int main(){ int a[10000]; int n; printf("要输入的序列的个数:"); scanf("%d",&n); printf("要输入的一系列数为:"); for(int i=0;i<n;i++){ scanf("%d",&a[i]); } int ans1=maxSum(a,n); int ans2=maxSum1(a,0,n); int ans3=Dpsum(a,n); printf("最大的子串和为:%d\n",ans1); printf("最大的子串和为:%d\n",ans2); printf("最大的子串和为:%d\n",ans3); return 0; }