#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 10010;
struct triple
{
int row, col, val;
bool operator < (const triple& t) const
{
return row < t.row;
}
};
struct matrix{
triple data[N];
int n, m, num;
};
void reverse(matrix &t)
{
swap(t.n, t.m);
for(int k = 0; k < t.num; ++ k)
swap(t.data[k].row, t.data[k].col);
sort(t.data, t.data + t.num);//按行为主序排列
}
int main()
{
matrix t;
int n, m, num;
scanf("%d%d%d", &n, &m, &num);
t.n = n; t.m = m; t.num = num;//三元组的行数,列数以及非零元素个数
int u[1000][1000], u2[1000][1000];
memset(u, 0, sizeof u);
memset(u2, 0, sizeof u2);
for(int k = 0; k < num; k ++)
{
int row, col, val;
scanf("%d%d%d", &row, &col, &val);
t.data[k].row = row; t.data[k].col = col; t.data[k].val = val;
}
printf("原三元组:\n");
printf("行数为%d, 列数为%d, 非零元素个数为%d\n", t.n, t.m, t.num);
printf("%2c %2c %2c\n",'i','j','v');
for(int i = 0; i < num; i ++)
printf("%2d %2d %2d\n", t.data[i].row, t.data[i].col, t.data[i].val);
cout << endl;
for(int s = 0; s < num; s ++)
{
int a, b, c;
a = t.data[s].row; b = t.data[s].col; c = t.data[s].val;
u[a][b] = c;
}
printf("原矩阵:\n");
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= m; j ++)
printf("%2d ", u[i][j]);
cout << endl;
}
cout << endl;
reverse(t);
printf("转置后的三元组:\n");
printf("行数为%d, 列数为%d, 非零元素个数为%d\n", t.n, t.m, t.num);
printf("%2c %2c %2c\n",'i','j','v');
for(int i = 0; i < num; i ++)
printf("%2d %2d %2d\n", t.data[i].row, t.data[i].col, t.data[i].val);
cout << endl;
for(int s = 0; s < num; s ++)
{
int a, b, c;
a = t.data[s].row; b = t.data[s].col; c = t.data[s].val;
u2[a][b] = c;
}
printf("转置后的矩阵:\n");
for(int i = 1; i <= m; i ++)
{
for(int j = 1; j <= n; j ++)
printf("%2d ", u2[i][j]);
cout << endl;
}
}
测试样例
输入:
6 7 8
1 2 12
1 3 9
3 1 -3
3 6 14
4 3 24
5 2 18
6 1 15
6 4 -7
输出:
原三元组:
行数为6, 列数为7, 元素个数为8
i j v
1 2 12
1 3 9
3 1 -3
3 6 14
4 3 24
5 2 18
6 1 15
6 4 -7
原矩阵:
0 12 9 0 0 0 0
0 0 0 0 0 0 0
-3 0 0 0 0 14 0
0 0 24 0 0 0 0
0 18 0 0 0 0 0
15 0 0 -7 0 0 0
转置后的三元组:
行数为7, 列数为6, 元素个数为8
i j v
1 3 -3
1 6 15
2 1 12
2 5 18
3 1 9
3 4 24
4 6 -7
6 3 14
转置后的矩阵:
0 0 -3 0 0 15
12 0 0 0 18 0
9 0 0 24 0 0
0 0 0 0 0 -7
0 0 0 0 0 0
0 0 14 0 0 0
0 0 0 0 0 0