POJ 矩阵相乘 (随机化算法-舍伍德(Sherwood))

周三的算法课,主要讲了随机化算法,介绍了拉斯维加斯算法,简单的理解了为什么要用随机化算法,随机化算法有什么好处。

在处理8皇后问题的时候,穷举法是最费时的,回朔比穷举好点,而当数据量比较大的时候,如1000皇后问题,穷举的化有1000的1000次方,肯定超时,用随机化算法的思路,先随机的在棋盘上放一部分皇后,再来设计算法,会大大节省时间,使算法性能更加优良。

本篇介绍令一种随机化算法,舍伍德(Sherwood)算法

题目:

Matrix Multiplication

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 16118   Accepted: 3485

You are given three n × n matrices A, B and C. Does the equation A × B = C hold true?

Input:

The first line of input contains a positive integer n (n ≤ 500) followed by the the three matrices A, B and C respectively. Each matrix's description is a block of n × n integers.

It guarantees that the elements of A and B are less than 100 in absolute value and elements of C are less than 10,000,000 in absolute value.

Output:

Output "YES" if the equation holds true, otherwise "NO".

Sample Input

2
1 0
2 3
5 1
0 8
5 1
10 26
Sample Output

YES
Hint

Multiple inputs will be tested. So O(n3) algorithm will get TLE.
Source

POJ Monthly--2007.08.05, qzc

 

解题思路:

输入3个n*n的矩阵ABC,计算A*B=C是否成立,若是输出Yes,否则输出No。

正常情况,从A的第一行A[0][j]和B的第一列B[i][0]相乘,看是不是等于C[0][0]。依次遍历所有行所有列。判断是否相等,相等继续,不相等直接返回false。

而如果我们用随机化算法的思想,来解决这个问题的时候,随机化一行一列,row col来判断是否和C[row][col]相等。如果不相等,比如A*B=C不满足,false跳出。

        for(i=1;i<=n;i++)
            temp+=A[row][i]*B[i][col];
        if(temp!=C[row][col])
                return 0;

这种随机化算法和拉斯维加斯算法又有点不同,将算法执行的步骤长短,更偏向于一种概率事件,是一种概率算法。

 

 1 #include <time.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #define maxn 500
 5 int A[maxn][maxn];
 6 int B[maxn][maxn];
 7 int C[maxn][maxn];
 8 int n;
 9  
10 void input(int c[maxn][maxn])
11 {
12     int i,j;
13     for(i=1;i<=n;i++){
14         for(j=1;j<=n;j++)
15         scanf("%d",&c[i][j]);
16     }
17 }
18  
19 int compared()
20 {
21     int row,col;//随机行数,列数
22     int k,i; 
23     for(k=1;k<=30000;k++)
24     {
25         row=rand()%n+1;
26         col=rand()%n+1;
27         int temp=0;
28         for(i=1;i<=n;i++)
29             temp+=A[row][i]*B[i][col];
30         if(temp!=C[row][col])
31                 return 0;
32     }
33     return 1;
34 }
35  
36 int main()
37 {
38     scanf("%d",&n);
39     srand(time(NULL));
40     input(A);
41     input(B);
42     input(C);
43     if(compared())
44         printf("Yes");
45          else
46           printf("No");
47 }

关于随机行数,列数的循环的次数,开小了,担心测不出最终结果,开大了影响效率,大家有没有一些好的建议,欢迎讨论,不当之处,恳请指正

 

总结:

LV算法和Sherwood算法的区别,拉斯维加斯算法不一定能得到解,但一旦得到解一定正确,在N皇后问题中,随机放至皇后越来越多,得到正确解的概率越小,但是代码执行的时间也是大大缩小。而舍伍德算法作为一种概率算法,并不受收入数据的大小影响,但得到结果所花的时间,成为了一种概率事件。

 

posted @ 2015-10-30 13:58  SeeKHit  阅读(1374)  评论(0编辑  收藏  举报