设计思路:
通过之前一维环,进行拓展,成数组。
代码:
1 //XiaoSong Du 2015/4/20 2 #include <iostream> 3 #include <time.h> 4 using namespace std; 5 #define M 3 6 #define N 6 7 8 void main() 9 { 10 int a[M][2*N]={0},b[2*N],d = 0,d1 = 0; 11 int maxd[2*N]={0} ,end1[2*N] = {0},end2 = 0; 12 int i_max = 0,j_max = 0 ,jj = -1,j1 = 0,j2 = -1; 13 14 srand((unsigned int)time(0)); 15 16 for (int i = 0;i < M;i++) 17 { 18 for (int j = 0;j < N;j++) 19 { 20 a[i][j] = rand()%50 - 25; 21 a[i][j+N] = a[i][j]; 22 cout << a[i][j] << " "; 23 } 24 cout << endl; 25 } 26 27 maxd[0] = a[0][0]; 28 for (int i = 0;i < M;i++)//i为0,表示1行,i为1表示两行数··· 29 { 30 for (int i_hang = 0;i_hang < M-i;i_hang++)//当1行是循环3次 31 { 32 for (int j = 0;j < 2*N;j++)//赋初值 33 { 34 b[j] = 0; 35 } 36 for (int i_hang1 = i_hang;i_hang1 <= i_hang+i;i_hang1++)//每次循环i次赋值 37 { 38 for (int j = 0;j < 2*N;j++) 39 { 40 b[j] += a[i_hang1][j]; 41 } 42 } 43 d = 0;j2 = -1;j1=0;jj=-1; 44 for (int ii = 0;ii < 2*N;ii++) 45 { 46 d += b[ii]; 47 if (d > maxd[j1-1]) 48 { 49 maxd[j1] = d; 50 end1[j1] = ii; 51 i_max = i; //最大的时候是i行; 52 j_max = i_hang; // 53 j1++; 54 j2 = jj; 55 } 56 if(d < 0) 57 { 58 d = 0; 59 jj = ii; 60 } 61 62 if (end1[j1-1] - j2 > N) //如果end1[j1-1] - j2大于N个数,那么就获取end1[j1-2] 63 { 64 j1--; 65 break; 66 } 67 } 68 end2 = j2+1; 69 } 70 } 71 cout << "子数组为:" << endl; 72 73 for (int k = 0;k <= i_max;k++) 74 { 75 for (int i = end2;i <= end1[j1-1];i++) 76 { 77 cout << a[j_max+k][i] << " "; 78 } 79 cout << endl; 80 } 81 cout << endl; 82 cout << "和为: " << maxd[j1-1] << endl; 83 }
结果截图:
总结:
在整合的过程中发生了一列错误,以至于到时间都没完善代码,只能先把博客发表,之后慢慢完善。程序多次运行后会出错误,可是大概是思路僵化的原因,就是解决不了。暂时先凉一下吧。
时间: 2024-10-17 09:54:22