HDU 4920 Matrix multiplication 解題報告(暴力)

Matrix multiplication

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 862    Accepted Submission(s): 343


Problem Description
Given two matrices A and B of size n×n, find the product of them.

bobo hates big integers. So you are only asked to find the result modulo 3.
 

Input
The input consists of several tests. For each tests:

The first line contains n (1≤n≤800). Each of the following n lines contain n integers -- the description of the matrix A. The j-th integer in the i-th line equals Aij. The next n lines describe the matrix B in similar format (0≤Aij,Bij≤109).
 

Output
For each tests:

Print n lines. Each of them contain n integers -- the matrix A×B in similar format.
 

Sample Input
1 0 1 2 0 1 2 3 4 5 6 7
 

Sample Output
0 0 1 2 1
 

Author
Xiaoxu Guo (ftiasch)
 

Source
 
    解題報告:直接乘的複雜度略高,優化一點就可以過了。這裏統計按行來計算了,代碼如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <iomanip>
using namespace std;
#define ff(i, n) for(int i=0;i<(n);i++)
#define fff(i, n, m) for(int i=(n);i<=(m);i++)
#define dff(i, n, m) for(int i=(n);i>=(m);i--)
#define bit(n) (1LL<<(n))
typedef long long LL;
typedef unsigned long long ULL;
const LL inf=1e15;
void work();
int main()
{
#ifdef ACM
    freopen("input.in", "r", stdin);
//    freopen("input.in", "w", stdout);
#endif // ACM
    work();
}

/***************************************************/

int a[888][888];
int b[888][888];
int ans[888];
int last[888];
int n, tmp;

void add(int * x, int * y)
{
    ff(i, n) x[i] += y[i];
}

void sub(int * x, int * y)
{
    ff(i, n) x[i] -= y[i];
}

void work()
{
    while(scanf("%d", &n) == 1)
    {
        ff(i, n) ff(j, n)
            scanf("%d", &tmp), a[i][j] = tmp%3;
        ff(i, n) ff(j, n)
            scanf("%d", &tmp), b[i][j] = tmp%3;

        memset(ans, 0, sizeof(ans));
        memset(last, 0, sizeof(last));
        ff(i, n)
        {
            ff(j, n)
            {
                if(a[i][j] - last[j] == 1 || a[i][j] - last[j] == -2)
                    add(ans, b[j]);
                else if(a[i][j] - last[j] == -1 || a[i][j] - last[j] == 2)
                    sub(ans, b[j]);
                last[j] = a[i][j];
            }

            ff(j, n) ans[j] = (ans[j]%3+3)%3;

            printf("%d", ans[0]);
            fff(j, 1, n-1) printf(" %d", ans[j]);
            puts("");
        }
    }
}
發佈了227 篇原創文章 · 獲贊 13 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章