对称矩阵的存储:
代码如下:
#include <iostream>
using namespace std;int main()
{int n;cin >> n;int *a;a = new int[(n*(n + 1)) / 2];for (int i = 0; i < (n*(n + 1)) / 2; i++){cin >> a[i];}for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){if (i >= j){int idx = (i*(i - 1)) / 2 + (j - 1);cout << a[idx] << " ";}else{int idx = (j*(j - 1)) / 2 + (i - 1);cout << a[idx] << " ";}}cout << endl;}return 0;
}
三角矩阵的存储:
代码如下:
#include <iostream>
using namespace std;int main()
{int *a;int n;cin >> n;int N = ((n*(n + 1)) / 2) + 1;a = new int[N];for (int i = 0; i < N; i++){cin >> a[i];}for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){if (i >= j){int idx = (i*(i - 1)) / 2 + (j - 1);cout << a[idx] << " ";}else{cout << a[N - 1] << " ";}}cout << endl;}return 0;
}