[UVA] 10895 - Matrix Transpose
A: Matrix Transpose
A matrix is a rectangular array of elements, most commonly numbers. A matrix with | A: Matrix Transpose |
is a 4-by-3 matrix of integers.
The individual elements of a matrix are usually given lowercase symbols and are distinguished by subscripts. The
th row and
th column of matrix
is usually referred to as
. For example,
. Matrix subscripts are 1-based.
The transpose of a matrix
, denoted
, is formed by interchanging the rows and columns of
. That is, the
th element of
is the
th element of
. For example, the transpose of matrix
above is:
A matrix is said to be sparse if there are relatively few non-zero elements. As a
-by-
matrix has
number of elements, storing all elements of a large sparse matrix may
be inefficient as there would be many zeroes. There are a number of ways
to represent sparse matrices, but essentially they are all the same:
store only the non-zero elements of the matrix along with their row and
column.
You are to write a program to output the transpose of a sparse matrix of integers.
Input
You are given several sparse matrix in a row, each of them described as follows. The first line of the input corresponds to the dimension of the matrix,
4 3 3 1 2 3 1 3 2 2 2 3 4 -1 0 3 1 2 3 5 -2 11Note that for a row with all zero elements, the corresponding set would just be one number, `0', in the first line, followed by a blank line.
You may assume:
- the dimension of the sparse matrix would not exceed 10000-by-10000,
- the number of non-zero element would be no more than 1000,
- each element of the matrix would be in the range of -10000 to 10000, and
- each line has no more than 79 characters.
Output
For each input case, the transpose of the given matrix in the same representation.
Sample Input
4 3 3 1 2 3 1 3 2 2 2 3 4 -1 0 3 1 2 3 5 -2 11
Sample Output
3 4 2 1 4 1 5 3 1 2 4 3 4 -2 3 1 2 4 2 -1 11
很少看到這種輸入格式, 給定 column 的位置, 之後給定元素值。
我有點懶得寫一些複雜的做法, 用內建 priority_queue 解決吧!
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
struct ele {
int v, col, row;
};
struct cmp {
bool operator() (ele a, ele b) {
if(a.col != b.col)
return a.col > b.col;
return a.row > b.row;
}
};
priority_queue<ele, vector<ele>, cmp> pQ;
int main() {
int n, m;
while(scanf("%d %d", &n, &m) == 2) {
ele p[10000];
int i, j, k;
for(i = 0; i < n; i++) {
scanf("%d", &k);
for(j = 0; j < k; j++)
scanf("%d", &p[j].col);
for(j = 0; j < k; j++)
scanf("%d", &p[j].v);
for(j = 0; j < k; j++)
p[j].row = i+1, pQ.push(p[j]);
}
printf("%d %d\n", m, n);
for(i = 1; i <= m; i++) {
int idx = 0;
while(!pQ.empty() && pQ.top().col == i) {
p[idx++] = pQ.top();
pQ.pop();
}
printf("%d", idx);
for(j = 0; j < idx; j++)
printf(" %d", p[j].row);
puts("");
for(j = 0; j < idx; j++) {
if(j) putchar(' ');
printf("%d", p[j].v);
}
puts("");
}
}
return 0;
}