HDU 4920 水

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   2014   ar   時間   

矩陣乘法

因為答案要MOD3,所以矩陣中會有很多值為0,對這些不乘就行了,,,,,,,這樣也能水過。。。

BUT :

這樣寫會逾時:            for (int i=1; i<=n; i++)                for (int j=1; j<=n; j++)                    for (int k=1; k<=n; k++)                        c[i][j]+=a[i][k]*b[k][j];這樣寫就能過:        for (int k=1; k<=n; k++)            for (int i=1; i<=n; i++)                for (int j=1; j<=n; j++)                    c[i][j]+=a[i][k]*b[k][j];
BECAUSE:
我們知道記憶體中二維數組是以行為單位連續儲存的,逐列訪問將會每次跳1000*4(bytes)。根據cpu cache的替換策略,將會有大量的cache失效。時間居然會相差很多。 可見利用好cpu cache最佳化我們的程式,是非常有必要掌握的技能。平時寫程式時,也應當盡量使cpu對記憶體的訪問,是儘可能連續的。

#include "stdio.h"#include "string.h"int a[810][810],b[810][810],c[810][810];int main(){    int n,i,j,k;    while (scanf("%d",&n)!=EOF)    {        for (i=1;i<=n;i++)            for (j=1;j<=n;j++)            {                scanf("%d",&a[i][j]);                a[i][j]%=3;            }        for (i=1;i<=n;i++)            for (j=1;j<=n;j++)            {                scanf("%d",&b[i][j]);                b[i][j]%=3;            }        memset(c,0,sizeof(c));        for (k=1;k<=n;k++)            for (i=1;i<=n;i++)            if (a[i][k]!=0)                for (j=1;j<=n;j++)                {                    c[i][j]+=a[i][k]*b[k][j]%3;                }        for (i=1;i<=n;i++)        {            for (j=1;j<n;j++)                printf("%d ",c[i][j]%3);            printf("%d\n",c[i][j]%3);        }    }    return 0;}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.