矩阵快速幂求助
  • 板块学术版
  • 楼主xsmfollower
  • 当前回复0
  • 已保存回复0
  • 发布时间2025/1/16 11:48
  • 上次更新2025/1/16 15:46:47
查看原帖
矩阵快速幂求助
1308728
xsmfollower楼主2025/1/16 11:48

https://www.luogu.com.cn/problem/P1349 几乎一样的站外题,只是不取模,有浮点数,输入格式略微变化(先输入前两项再输入递推系数),最后结果四舍五入。

被如下数据 HACK 了:

0 0 2.0 2.0 1000000000

应该输出 00,我输出 nan,但我并没有进行除法啊,代码如下:

#include<cstdio>
using namespace std;
struct Matrix {
  double a[3][3];
  Matrix() { for(int i=1;i<=2;i++) for(int j=1;j<=2;j++) a[i][j]=0; }
}base,ans;
Matrix operator *(Matrix a,Matrix b) {
  Matrix c;
  for(int k=1;k<=2;k++) for(int i=1;i<=2;i++) for(int j=1;j<=2;j++) c.a[i][j]+=a.a[i][k]*b.a[k][j];
  return c;
}
int main() {
  double f0,f1,a,b; int n; scanf("%lf %lf %lf %lf %d",&f0,&f1,&a,&b,&n);
  if(!n) return printf("%.0lf\n",f0),0;
  ans.a[1][1]=f1,ans.a[1][2]=f0,base.a[1][1]=a,base.a[2][1]=b,base.a[1][2]=1,n--;
  while(n) {
  	if(n&1) ans=ans*base;
  	base=base*base,n>>=1;
  }
  printf("%.0lf",ans.a[1][1]);
  return 0;
}

求解释+改正方案

2025/1/16 11:48
加载中...