这次求二维数组的最大子连通数组:
这次的要求有点偏难在好多同学的指导下才完成此任务
1 #include<iostream> 2 using namespace std; 3 4 struct point 5 { 6 int x, y; 7 }; 8 9 int add(int a[5][5], int i, int j, int k) 10 { 11 int n; 12 int b = 0; 13 for (n = j; n <= i + j; n++) 14 { 15 b += a[n][k]; 16 } 17 return b; 18 } 19 20 void main () 21 { 22 int x=5,y=5,i, j, k, l; 23 int sum = 0, s, h, e; 24 point head; 25 point end; 26 int a[5][5]; 27 int b[5]; 28 cout << "请输入数组中的数:" << endl; 29 for (i = 0; i<x; i++) 30 { 31 for (j = 0; j<y; j++) 32 { 33 cin>>a[i][j]; 34 } 35 } 36 for (i = 0; i<x; i++) 37 { 38 for (j = 0; i + j<x; j++) 39 { 40 s = 0; 41 h = 0; 42 e = 0; 43 for (k = 0; k<y; k++) 44 { 45 b[k] = add(a, i, j, k); 46 47 } 48 49 for (l = 0; l<x; l++) 50 51 { 52 53 s += b[l]; 54 55 if (s>0) 56 57 { 58 59 e++; 60 61 } 62 63 else 64 65 { 66 67 s = 0; 68 69 h = l + 1; 70 71 e++; 72 73 } 74 75 if (s>sum) 76 77 { 78 79 sum = s; 80 81 head.x = h; 82 83 head.y = j; 84 85 end.x = e; 86 87 end.y = i + j; 88 89 } 90 91 } 92 93 if (s>0 && h != 0) 94 95 { 96 97 l = 0; 98 99 e = e - x; 100 101 while (s>0 && e != h - 1) 102 103 { 104 105 s += b[l]; 106 107 l++; 108 109 e++; 110 111 if (s>sum) 112 113 { 114 115 sum = s; 116 117 head.x = h; 118 119 head.y = j; 120 121 end.x = e; 122 123 end.y = i + j; 124 125 } 126 127 } 128 129 } 130 131 } 132 133 } 134 cout<<"最大子数组的和为:"<<sum<<endl; 135 cout<<"最大子数组为:"<<endl; 136 if (end.x>head.x) 137 { 138 for (i = head.y; i <= end.y; i++) 139 { 140 for (j = head.x; j<end.x; j++) 141 { 142 cout<<a[i][j]<<" "; 143 } 144 cout << endl; 145 } 146 } 147 else 148 { 149 for (i = head.y; i <= end.y; i++) 150 { 151 for (j = head.x; j < x; j++) 152 { 153 cout << a[i][j] << " "; 154 } 155 for (j = 0; j < end.x; j++) 156 { 157 cout << a[i][j] << " "; 158 } 159 cout << endl; 160 } 161 } 162 system("pause"); 163 }
合作人:靳琪