標籤:
題目要求:
輸入一個二維整形數組,數組裡有正數也有負數。
求所有子數組的和的最大值。
設計思想:
把二維數組看成圖的形式,然後採取遍曆的方法。
當和小於0時放棄,其他疊加和。
代碼:
#include<iostream>#include<ctime>using namespace std;#define N 100typedef struct{ int dian[N]; int xian[N][N]; int dianx, xianx;}A;void set(A &shu, int x, int y){ shu.dianx = x*y; srand((unsigned)time(NULL)); for (int i = 1; i <= shu.dianx; i++) { shu.dian[i] = rand() % 10; if (rand() % 2 == 1) shu.dian[i] = shu.dian[i] * (-1); } for (int i = 1; i <= shu.dianx; i += y) { for (int j = i; j <= i + y - 2; j++) { shu.xian[j][j + 1] = 1; shu.xian[j + 1][j] = 1; } } for (int i = 1 + y; i<shu.dianx; i += y) { for (int j = i; j <= i + x - 1; j++) { shu.xian[j][j - y] = 1; shu.xian[j - y][j] = 1; } }}void output(A shu){ for (int i = 1; i <= shu.dianx; i++) { cout << shu.dian[i] ; if (shu.xian[i][i + 1] == 1) cout << " "; else cout << endl; }}void bianli(A &shu, int v, int visit[], int &b, int &max, int x){ visit[v] = 1; max += shu.dian[v]; if (max >= b) b = max; int a = 0, bo = 0; for (int w = 1; w <= shu.dianx; w++) { for (int c = 1; c <= shu.dianx; c++) { if ((visit[w] == 0) && (shu.xian[c][w] == 1) && (visit[c] == 1)) { a = w; bo = 1; break; } } if (bo == 1) break; } for (int w = 1; w <= shu.dianx; w++) { for (int c = 1; c <= shu.dianx; c++) { if ((visit[w] == 0) && (shu.xian[c][w] == 1) && (visit[c] == 1)) { if (shu.dian[a]<shu.dian[w]) a = w; } } } if (b + shu.dian[a]<0) { shu.xian[v][a] = 0; } else bianli(shu, a, visit, b, max, x);}int NoVisit(int visit[], A shu){ int k = 0, i; for (i = 1; i <= shu.dianx; i++) { if (visit[i] == 0) { k = i; break; } } return k;}int main(){ cout << "請輸入數組行列數:" << endl; int x, y; cin >> x >> y; A shu; set(shu, x, y); output(shu); int v = 1, b[N] = { 0 }, h = 0; for (int i = 1; i <= shu.dianx; i++) { if (shu.dian[i]<0) { b[i] = shu.dian[i]; } else { int visit[N] = { 0 }; int max = 0; bianli(shu, i, visit, b[i], max, x); } } int max = b[1]; for (int i = 2; i <= shu.dianx; i++) { if (b[i]>max) max = b[i]; } cout << "最大聯通子數組的和為:" << max << endl;}View Code
:
總結:
雖然有了前幾次關於數組的題目做鋪墊和遞進,但是這道題真的挺難。搜尋資料也不多。
思路很重要,思路確定了才能解析程式的編寫。
最大聯通子數組