思路:
这也是根据同学使用将矩阵转化为图的思路将结果得出了,所以我就沿着这个思路一步一步的分析了一下。开始先将将二维矩阵转换成图的存储形式,当两个相邻的数之间是联通的时,记长度为1,否则就是0;将整个图从每个点都开始遍历一遍,遍历过程中时,当和小于0时断开两点间的路,当和大于最大和时改变最大和的值,取以每个点为起点遍历的和的最大值即时最大联通子数组的和。遍历时,选取已遍历的联通子数组周围最大值遍历。经过重复的几次遍历就可以确定此数组中最大连通数组和了。
题目要求:
放在一个input.txt的文件中
数组里面有正数有负数
返回联通子数组和最大的值
#include<fstream> #include<iostream> #define N 100 #include<ctime> using namespace std; typedef struct { int d[N]; int a[N][N]; int x; }A; void set(A &p, int x, int y) //x,y分别是行数和列数 { p.x = x*y; srand((unsigned)time(NULL)); for (int i = 1; i <= p.x; i++) { p.d[i] = rand() % 10; if (rand() % 2 == 1) p.d[i] = p.d[i] * (-1); } //随机生成数组的数 for (int i = 1; i <= p.x; i += y) { for (int j = i; j <= i + y - 2; j++) { p.a[j][j + 1] = 1; p.a[j + 1][j] = 1; } } for (int i = 1 + y; i<p.x; i += y) { for (int j = i; j <= i + x - 1; j++) { p.a[j][j - y] = 1; p.a[j - y][j] = 1; } } //将随机生成的一维数组转换成二维的图的形式 } void bianli(A &p, int v, int visit[], int &b, int &max, int x) { visit[v] = 1; max += p.d[v]; if (max >= b) b = max; int a = 0, bo = 0; for (int w = 1; w <= p.x; w++) { for (int c = 1; c <= p.x; c++) { if ((visit[w] == 0) && (p.a[c][w] == 1) && (visit[c] == 1)) { a = w; bo = 1; break; } } if (bo == 1) break; } for (int w = 1; w <= p.x; w++) { for (int c = 1; c <= p.x; c++) { if ((visit[w] == 0) && (p.a[c][w] == 1) && (visit[c] == 1)) { if (p.d[a]<p.d[w]) a = w; } } } if (b + p.d[a]<0) { p.a[v][a] = 0; } else bianli(p, a, visit, b, max, x); } //遍历 int NoVisit(int visit[], A p) { int k = 0, i; for (i = 1; i <= p.x; i++) { if (visit[i] == 0) { k = i; break; } } return k; } //判断图中没有visit的项 int main() { cout << "请输入数组行数和列数:" << endl; int x, y; cin >> x >> y; A p; set(p, x, y); ofstream fout("D:\\input.txt",ios::binary); for (int i = 1; i <= p.x; i++) { fout << p.d[i] ; if (p.a[i][i + 1] == 1) fout << " "; else fout << endl; } int v = 1, b[N] = { 0 }, h = 0; for (int i = 1; i <= p.x; i++) { if (p.d[i]<0) { b[i] = p.d[i]; } else { int visit[N] = { 0 }; int max = 0; bianli(p, i, visit, b[i], max, x); } } int max = b[1]; for (int i = 2; i <= p.x; i++) { if (b[i]>max) max = b[i]; } fout << "最大联通子数组的和为:" << max << endl; }
时间: 2024-10-03 21:53:34