十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
设一个N*N的方阵A,A中任意元素Aij,当且仅当Aij == Aji(0 <= i <= N-1 && 0 <= j <= N-1),则矩阵A是对称矩阵。以矩阵的对角线为分隔,分为上三角和下三角。

压缩存储称矩阵存储时只需要存储上三角/下三角的数据,所以最多存储n(n+1)/2个数据。
对称矩阵和压缩存储的对应关系:下三角存储i>=j, SymmetricMatrix[i][j] == Array[i*(i+1)/2+j]

0 1 2 3 4
1 0 1 2 3
2 1 0 1 2
3 2 1 0 1
4 3 2 1 0
Symmetry.h中
template < class T>
class Symmetry
{
public:
//构造函数
Symmetry(T* arr, size_t size)
:_arr(new T[size*(size+1)/2])
, _size(size*(size + 1)/2)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (i >= j)
{
_arr[i*(i + 1) / 2 + j] = arr[i*size + j];//把对称矩阵压缩
}
}
}
}
//打印
void Print(size_t size)
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
int row = i;
int col = j;
if (row < col)
{
swap(row, col);
}
cout << _arr[row*(row+ 1) / 2 + col] << " ";
}
cout << endl;
}
cout << endl;
}
protected:
T *_arr;
size_t _size;
};
test.cpp中
#include
using namespace std;
#include "Symmetry.h"
void Test()
{
int arr[5][5] = {
{0,1,2,3,4},
{1,0,1,2,3},
{2,1,0,1,2},
{3,2,1,0,1},
{4,3,2,1,0}
};
Symmetrys((int*)arr, 5);
s.Print(5);
}
int main()
{
Test();
system("pause");
return 0;
} 另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。