标签:
题目要求:
输入一个二维整形数组,数组里有正数也有负数。
求所有子数组的和的最大值。
设计思想:
把二维数组看成图的形式,然后采取遍历的方法。
当和小于0时放弃,其他叠加和。
代码:
#include<iostream> #include<ctime> using namespace std; #define N 100 typedef 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; }
截图:
总结:
虽然有了前几次关于数组的题目做铺垫和递进,但是这道题真的挺难。搜索资料也不多。
思路很重要,思路确定了才能解析程序的编写。
标签:
原文地址:http://www.cnblogs.com/15732115368zhm/p/4570083.html