(For ACMer : 道路千万条,别走这一条)
优点 :七次乘法和十八次加法完成运算
基于递归分治策略
缺点 :不稳定,占内存大
逻辑实现
p1 = (a11 + a22)(b11 + b22)
p2 = (a21 + a22) * b11
p3 = a11 * (b12 - b22)
p4 = a22 * (b21 - b11)
p5 = (a11 + a12) * b22
p6 = (a21 - a11) * (b11 + b22)
p7 = (a12 - a22) * (b21 + b22)
c11 = p1 + p4 - p5 +p7
c12 = p3 + p5
c21 = p2 + p4
c22 = p1 + p3 - p2 + p6
函数实现
void strassen()
{
int p1 = (a[0][0] + a[0][1]) * (b[0][1] + b[1][0]);
int p2 = (a[1][0] + a[1][1]) * b[0][0];
int p3 = (b[0][1] - b[1][1]) * a[0][0];
int p4 = (b[1][0] - b[0][0]) * a[1][1];
int p5 = (a[0][0] - a[0][1]) * b[1][1];
int p6 = (a[1][0] - a[1][1]) * (b[0][0] + b[0][1]);
int p7 = (a[0][1] - a[1][1]) * (b[1][0] + b[1][1]);
int c11 = p1 + p4 - p5 + p7;
int c12 = p3 + p5;
int c21 = p2 + p5;
int c22 = p1 + p3 - p2 + p6;
printf("%d %d %d %d\n",c11,c12,c21,c22);
}
来自百度百科的解释 :Strassen 算法
看起来些许高深,其实不算太难。
参考 Coppersimith - Windograd 算法
或参考Coppersimith – Windograd 算法
推荐 矩阵的快速算法
函数实现
int product ()
{
int i, j, k, l, alpha,beta;
int kmr = ar * br;
int kmc = ac * bc;
for(i = 0; i < ar ; i++)
for( k = 0; k < br; k++)
for(l = 0; i < bc; l++)
{
alpha = br * (i - 1) + k + br;
beta = bc * (j - 1) + l + bc;
c[alpha][beta] = a[i][j] * b[k][l];
}
for(i = 0; i < kmr; i++)
{
for(j = 0; j < kmc; j++)
printf("%d",c[i][j]);
printf("\n");
}
}
void inverse(float mat[][10],int r, int c)
{
float b[10][10],ratio,a[10][10];
int i, j, k;
if(r == c)
{
clrscr();
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
{
a[i][j] = mat[i][j];
b[i][j] = 0;
}
b[i][i] = 1;
}
for(k = 0; k < r; k++)
{
for(i = 0; i < c; i++)
{
if(i == k)
continue;
else
{
ratio = a[i][k] / a[k][k];
for(j = 0; j < c; j++)
{
a[i][j] -= ratio * a[k][j];
b[i][j] -= ratio * b[k][j];
}
}
}
}
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
b[i][j] /= a[i][i];
}
for(i = 0; i < c; i++)
{
for(j = 0; j < c; j++)
printf("%f\t",b[i][j]);
printf("\n");
}
}
clrscr(); 如编译器不通过可换为system("cls")
上三角矩阵
void triu(int m[][3], int rows, int cols )
{
int i = 0;
int j = 0;
for(; i < rows; i++)
{
for( j = 0 ; j < cols ; j++)
{
if(j < i)
printf("0 ");
else
printf("%d ",m[i][j]);
}
printf("\n");
}
}
严格上三角矩阵(将条件j<i改为 <=)
#include
void triu(int m[][3], int rows, int cols )
{
int i = 0;
int j = 0;
for(; i < rows; i++)
{
for( j = 0 ; j < cols ; j++)
{
if(j <= i)
printf("0 ");
else
printf("%d ",m[i][j]);
}
printf("\n");
}
}
void Toeplitz(int rows[10],int cols[10], int r, int c)
{
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
{
if(i-j>=0)
T[i][j] = cols[i-j+1];
if(j-i>0)
T[i][j] = rows[j-i+1];
}
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
printf("%d ",t[i][j]);
printf("\n");
}
}