HDU4920 Matrix multiply (三元组稀疏矩阵)

快要数据结构期末考试了,书看不下去就随便找了一题矩阵乘积的题,然后套用书上稀疏矩阵乘积的方法,提交的时候,满满的自信,觉得肯定不会超时,结果就。。。。超时了。 然后看了别的题解,原来直接暴力相乘也可以。。。主要的优化其实是在输入的时候,一旦数据是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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值