2018年上海金马五校程序设计竞赛 Problem O : ±1 Matrix

版权声明:Why is everything so heavy? https://blog.csdn.net/lzc504603913/article/details/80634452

Problem O : ±1 Matrix


Submit (Out of Contest)

Time Limit: 5 s

Description

A matrix in mathematics is a rectangular array of numbers arranged in rows and columns. Given an n×m matrix A and an m×k matrix B, which only contain +1 and -1.

Please design a quick algorithm to calculate the result of multiplying these two matrices. Note that the result is an n×kmatrix.

Input

There are multiple test cases (no more than 10).

For each test case, there are several lines.
The first line contains three integers nm and k (2 ≤ nmk < 1111), which correspond to the sizes of matrices A and Bdescribed above.
Next is a blank line.
The next n lines describe the matrix A. Each of the n lines has m space-separated +1 or -1.
Next is a blank line.
The next m lines describe the matrix B. Each of the m lines has k space-separated +1 or -1.

There is a blank line between every two test cases, and there is no extra empty line at the beginning or end of the input.

Output

For each test case, output an n×k matrix which is the result of multiplying matrices A and B.
You should output n lines. Each line contains k space-separated integers.

Sample Input

2 3 3

-1 -1 1
-1 1 -1

1 -1 1
1 1 1
1 1 1

2 2 2

-1 1
1 1

-1 -1
-1 1

Sample Output

-1 1 -1
-1 1 -1
0 2
-2 0

题意:矩阵相乘,只有1和-1


解题思路:直接暴力明显超时。考虑矩阵相乘最里面那个循环,即计算行×列那个过程,由于乘数只有1,-1,可以优化。考虑样例,计算

-1  -1  1

×

1  1  1

的时候。把-1变为1,1变为0,变成二进制相乘。110*000,因为-1*-1=1,所以其实是一个二进制异或运算。然后统计计算结果中有多少个1即可。这里用bitset就ok了。


#include<iostream>
#include<bitset>
using namespace std;
typedef long long int ll;
const int MAXN=1200;
 
bitset<MAXN> Ai[MAXN];
bitset<MAXN> Bj[MAXN];
 
int ans[MAXN][MAXN];
 
int main(){
 
 
    int N,M,K;
 
    while(~scanf("%d%d%d",&N,&M,&K)){
 
 
        for(int i=0;i<MAXN;i++)
        {
            Ai[i].reset();
            Bj[i].reset();
        }
 
        int temp;
        for(int i=0;i<N;i++)
            for(int j=0;j<M;j++){
                scanf("%d",&temp);
                if(temp==-1)
                {
                    Ai[i][j]=1;
                }
            }
 
        for(int i=0;i<M;i++)
            for(int j=0;j<K;j++){
                scanf("%d",&temp);
                if(temp==-1)
                {
                    Bj[j][i]=1;
                }
            }
 
        bitset<MAXN> bs;
 
        for(int i=0;i<N;i++){
            for(int j=0;j<K;j++){
                bs=Ai[i]^Bj[j];
                ans[i][j]=M-2*bs.count();
            }
        }
 
        for(int i=0;i<N;i++){
            for(int j=0;j<K-1;j++)
                printf("%d ",ans[i][j]);
            printf("%d\n",ans[i][K-1]);
        }
 
 
 
    }
    return 0;
}



猜你喜欢

转载自blog.csdn.net/lzc504603913/article/details/80634452
今日推荐