51nod 1140 矩阵相乘结果的判断 随机算法

题目来源: POJ
基准时间限制:1 秒 空间限制:131072 KB 分值: 80 难度:5级算法题
 收藏
 关注
给出三个N*N的矩阵A, B, C,问A * B是否等于C?
 
Input
第1行,1个数N。(0 <= N <= 500)
第2 - N + 1行:每行N个数,对应矩阵A的元素。(0 <= M[i] <= 16)
第N + 2 - 2N + 1行:每行N个数,对应矩阵B的元素。(0 <= M[i] <= 16)
第2N + 2 - 3N + 1行:每行N个数,对应矩阵C的元素。
Output
如果相等输出Yes,否则输出No。
Input示例
2
1 0
0 1
0 1
1 0
0 1
1 0
Output示例
Yes


这份代码基本是照着别人的思路写的...
一开始自己写的随机是找随机的行和列然后计算看是否正确 但是只能过前面的数据 后面几组数据大的试了十几次不是WA就是T...
看来就算写随机算法还是要找优化一点的


#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <iomanip>
#include <math.h>
#include <map>
#include <time.h>
using namespace std;
#define FIN     freopen("input.txt","r",stdin);
#define FOUT    freopen("output.txt","w",stdout);
#define INF     0x3f3f3f3f
#define INFLL   0x3f3f3f3f3f3f3f
#define lson    l,m,rt<<1
#define rson    m+1,r,rt<<1|1
typedef long long LL;
typedef pair<int, int> PII;
using namespace std;

const int maxn = 500 + 5;

int a[maxn][maxn];
int b[maxn][maxn];
int c[maxn][maxn];
int x[maxn][maxn];

int n;

int main() {
    //FIN
    while(~scanf("%d", &n)) {
        int num;

        for(int i = 1; i <= n; i++) {
            x[0][i] = rand() % 10000 + 1;
            x[1][i] = rand() % 10000 + 1;
        }

        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                scanf("%d", &num);
                a[0][j] += x[0][i] * num;
                a[1][j] += x[1][i] * num;
            }
        }

        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                scanf("%d", &num);
                b[0][j] += a[0][i] * num;
                b[1][j] += a[1][i] * num;
            }
        }

        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= n; j++) {
                scanf("%d", &num);
                c[0][j] += x[0][i] * num;
                c[1][j] += x[1][i] * num;
            }
        }

        int flag = 0;
        for(int i = 1; i <= n; i++) {
            if(b[0][i] != c[0][i] || b[1][i] != c[1][i]) flag = 1;
            if(flag) break;
        }

        if(!flag) puts("Yes");
        else puts("No");

    }


    return 0;
}

  

原文地址:https://www.cnblogs.com/Hyouka/p/7447709.html