快要数据结构期末考试了,书看不下去就随便找了一题矩阵乘积的题,然后套用书上稀疏矩阵乘积的方法,提交的时候,满满的自信,觉得肯定不会超时,结果就。。。。超时了。 然后看了别的题解,原来直接暴力相乘也可以。。。主要的优化其实是在输入的时候,一旦数据是3的倍数直接当成0处理就行了。
哎呀,结果速度还没有暴力的快,就当是复习了吧。。。
如果G++超时,请改用C++。若C++超时,请改用G++(憋问俺为什么,俺也不知道)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
struct data{
int i,j,key;
};
struct mat{
data str[650000];
int rpos[1000];
};
int n;
void print(mat& a){
int p = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
if(i == a.str[p].i && j == a.str[p].j)
cout << a.str[p++].key;
else
cout << 0 ;
if(j != n-1) cout <<" ";
}
cout << endl;
}
}
void mul(mat& a, mat& b){
int ctmp[1000];
mat c;
int ptr = 0;
for(int i = 0; i < n; ++i){
memset(ctmp,0,sizeof(ctmp));
int as = a.rpos[i];
int at = a.rpos[i+1];
for(int j = as; j < at; ++j){
int brow = a.str[j].j;
int bs = b.rpos[brow];
int bt = b.rpos[brow+1];
for(int k = bs; k < bt; ++k){
int col = b.str[k].j;
ctmp[col] += (a.str[j].key*b.str[k].key) ;
ctmp[col] %= 3;
}
}
for(int l = 0; l < n; ++l){
if(ctmp[l]){
c.str[ptr].key = ctmp[l];
c.str[ptr].i = i; c.str[ptr].j = l;
ptr++;
}
}
}
print(c);
}
int main(){
//freopen("/Users/user/Desktop/1.txt","r",stdin);
int t;
while(~scanf("%d", &t)){
n = t;
mat a,b;
a.rpos[0] = 0;
int p = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
int dig; scanf("%d", &dig);
dig %= 3;
if(dig){
data& e = a.str[p];
e.i = i; e.j = j; e.key = dig ;
p++;
}
}
a.rpos[i+1] = p;
}
b.rpos[0] = 0;
p = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
int dig; scanf("%d",&dig);
dig %= 3;
if(dig){
data& e = b.str[p];
e.i = i; e.j = j; e.key = dig ;
p++;
}
}
b.rpos[i+1] = p;
}
mul(a,b);
}
return 0;
}