数据结构实验之数组三:快速转置(SDUT 3347)

Problem Description

转置运算是一种最简单的矩阵运算,对于一个m*n的矩阵M( 1 = < m < = 10000,1 = < n < = 10000 ),它的转置矩阵T是一个n*m的矩阵,且T( i , j )=M( j , i )。显然,一个稀疏矩阵的转置仍然是稀疏矩阵。你的任务是对给定一个m*n的稀疏矩阵( m , n < = 10000 ),求该矩阵的转置矩阵并输出。矩阵M和转置后的矩阵T如下图示例所示。
   
   稀疏矩阵M                             稀疏矩阵T


Input

连续输入多组数据,每组数据的第一行是三个整数mu, nu, tu(tu <= 50),分别表示稀疏矩阵的行数、列数和矩阵中非零元素的个数,随后tu行输入稀疏矩阵的非零元素所在的行、列值和非零元素的值,同一行数据之间用空格间隔。(矩阵以行序为主序)


Output

输出转置后的稀疏矩阵的三元组顺序表表示。


Sample Input

3 5 5
1 2 14
1 5 -5
2 2 -7
3 1 36
3 4 28

Sample Output

1 3 36
2 1 14
2 2 -7
4 3 28
5 1 -5

题解:矩阵转置就是把每一列按着行来写,这样就可以想到把坐标sort一下,输出就行了。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
typedef long long int ll;
struct node
{
    int x, y, z;
};
struct node s[55];
bool cmp(struct node a,struct node b)
{
    if(a.y == b.y) return a.x < b.x;
    else return a.y < b.y;
}
int main()
{
    int mu, nu, tu;
    while(~scanf("%d %d %d", &mu, &nu, &tu))
    {
        for(int i = 0; i < tu; i ++)
        {
            scanf("%d %d %d", &s[i].x, &s[i].y, &s[i].z);
        }
        sort(s, s + tu, cmp);
        for(int i = 0; i < tu; i ++)
        {
            printf("%d %d %d\n", s[i].y, s[i].x, s[i].z);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mercury_Lc/article/details/81448813