#include <iostream>
#include <vector>
using namespace std;
class SymmetricMatrix {
private:
int n; // 矩阵的阶数
vector<int> elements; // 存储下三角的元素
public:
// 构造函数
SymmetricMatrix(int size) : n(size), elements((size * (size + 1)) / 2, 0) {}
// 从键盘输入矩阵的下三角元素
void inputMatrix() {
cout << "请输入对称矩阵的下三角元素(包括对角线):" << endl;
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
if (i == j) {
cout << "元素[" << i << "][" << j << "]: ";
} else {
cout << "元素[" << i << "][" << j << "]: ";
}
cin >> elements[i * (2 * n - i - 1) / 2 + j - i];
}
}
}
// 输出对称矩阵
void printMatrix() {
cout << "对称矩阵为:" << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i > j) {
cout << elements[j * (2 * n - j - 1) / 2 + i - j] << " ";
} else {
cout << elements[i * (2 * n - i - 1) / 2 + j - i] << " ";
}
}
cout << endl;
}
}
// 查找元素值
int getElement(int row, int col) {
if (row < 0 || row >= n || col < 0 || col >= n) {
cout << "行号或列号超出矩阵范围。" << endl;
return -1; // 返回-1表示查找失败
}
if (row < col) {
swap(row, col); // 确保row不小于col,因为只存储下三角
}
return elements[row * (2 * n - row - 1) / 2 + col - row];
}
};
int main() {
int order;
cout << "请输入对称矩阵的阶数:" << endl;
cin >> order;
SymmetricMatrix sm(order);
sm.inputMatrix();
sm.printMatrix();
int row, col;
cout << "请输入要查找的行号和列号:" << endl;
cin >> row >> col;
int value = sm.getElement(row, col);
if (value != -1) {
cout << "元素[" << row << "][" << col << "]的值为:" << value << endl;
}
return 0;
}