數據結構實驗之數組三:快速轉置
Time Limit: 1000MS Memory Limit: 65536KB
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
輸出轉置後的稀疏矩陣的三元組順序表表示。
Example Input
3 5 51 2 141 5 -52 2 -73 1 363 4 28
Example Output
1 3 362 1 142 2 -74 3 285 1 -5
#include <iostream>
using namespace std;
struct node
{
int row;
int col;
int data;
}mp[10010];
void func(int n)
{
int i,j;
struct node t;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(mp[j].col>mp[j+1].col)
{
t=mp[j];
mp[j]=mp[j+1];
mp[j+1]=t;
}
else if(mp[j].col==mp[j+1].col)
{
if(mp[j].row>mp[j+1].row)
{
t=mp[j];
mp[j]=mp[j+1];
mp[j+1]=t;
}
}
}
}
}
int main()
{
int mu,nu,tu;
int i,j;
while(cin>>mu>>nu>>tu)
{
for(i=0;i<tu;i++)
cin>>mp[i].row>>mp[i].col>>mp[i].data;
func(tu);
for(i=0;i<tu;i++)
cout<<mp[i].col<<" "<<mp[i].row<<" "<<mp[i].data<<endl;
}
return 0;
}