資料結構實驗之陣列三:快速轉置(std::stable_sort函式)
阿新 • • 發佈:2018-11-17
資料結構實驗之陣列三:快速轉置
Time Limit: 1000 ms Memory Limit: 65536 KiB
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
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> typedef struct node { int x, y; int c; }q; int cmp(node a, node b) { return a.x<b.x; } int main() { q a[10008]; int mu, nu, tu; int i; while(~scanf("%d %d %d",&mu, &nu,&tu)) { for(i = 0;i < tu;i++) { scanf("%d %d %d",&a[i].y,&a[i].x,&a[i].c); } std::stable_sort(a,a+tu,cmp);//注意這個函式 for(i = 0;i< tu;i++) { printf("%d %d %d\n",a[i].x,a[i].y,a[i].c); } } return 0; }
這裡面最關鍵的就是std:stable_sort()函式。
這個函式是一個穩定排序。
給大家舉個例子,最開始我自己寫的時候不知道這個函式,程式碼是這樣:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
typedef struct node
{
int x, y;
int c;
}q;
int cmp(const void *a, const void *b)
{
q *aa=(q *)a;
q *bb = (q *)b;
return aa->x - bb->x;
}
int main()
{
q a[10008];
int mu, nu, tu;
int i;
while(~scanf("%d %d %d",&mu, &nu,&tu))
{
for(i = 0;i < tu;i++)
{
scanf("%d %d %d",&a[i].y,&a[i].x,&a[i].c);
}
qsort(a,tu,sizeof(a[0]),cmp); //即普通的快排
for(i = 0;i< tu;i++)
{
printf("%d %d %d\n",a[i].x,a[i].y,a[i].c);
}
}
return 0;
}
輸入樣例後輸出:
3 5 5
1 2 14
1 5 -5
2 2 -7
3 1 36
3 4 28//上面數輸入
1 3 36
2 2 -7//仔細看
2 1 14//這兩行
4 3 28
5 1 -5