您的位置:首页 > 其它

51nod oj 1137 1242 <结构体内重载运算符求矩阵乘法>

2016-08-07 22:59 253 查看
链接:1137

重载运算符--重新定义运算符的作用--使返回自己想要的结果-.-

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
int n;
int a[102][102];
void clear(){
n=0;
memset(a,0,sizeof(a));
}
node operator * (const node &b)const{
node c;c.clear();
c.n=n;
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
for (int k=1;k<=n;k++)
c.a[i][j]+=a[i][k]*b.a[k][j];
return c;
}
}a,b,c;
int main()
{
scanf("%d",&a.n);
int nn=a.n;
for (int i=1;i<=nn;i++)
for (int j=1;j<=nn;j++)
scanf("%d",&a.a[i][j]);
b=a;
for (int i=1;i<=nn;i++)
for (int j=1;j<=nn;j++)
scanf("%d",&b.a[i][j]);
c=a*b;
for (int i=1;i<=nn;i++)
{
for (int j=1;j<nn;j++)
printf("%d ",c.a[i][j]);
printf("%d\n",c.a[i][nn]);
}
return 0;
}


题目链接:1242

与这题一样:矩阵快速幂【模板】求Fibonacci数列

原理请看链接的题--

下面这个代码进行了乘法优化--

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
LL yu,n;
struct node{
int n;
LL a[5][5];
void clear(){
memset(a,0,sizeof(a));
}
node operator * (const node &b)const{
node c;c.clear();
c.n=n;
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
{
for (int k=1;k<=n;k++)
{
c.a[i][j]+=a[i][k]*b.a[k][j];
c.a[i][j]%=yu;
}
}
return c;
}
}a,lp;
int main()
{
yu=1000000009;
scanf("%lld",&n);lp.n=2;a.n=2;
lp.a[1][1]=lp.a[2][2]=1;lp.a[1][2]=lp.a[2][1]=0;
a.a[1][1]=a.a[1][2]=a.a[2][1]=1;a.a[2][2]=0;
while (n)
{
if (n%2)
{
lp=lp*a;
}
a=a*a;
n/=2;
}
printf("%lld\n",lp.a[2][1]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: