0
点赞
收藏
分享

微信扫一扫

*step1_入门_ACM水题 小明系列故事——师兄帮帮忙

罗蓁蓁 2022-02-06 阅读 46


思路

这道题用到了快速幂,求解k^t时。

快速幂模板​

模板及解释来自​


1)常规求幂

常规求幂即是根据ans=a*a*a*a。。。

根据b的个数来就行求解

2)二分求幂

二分求幂是可以将乘法进行分组

比如a*a*a*a*a*a=(a*a)*(a*a)*(a*a),这样就将6次乘法变成了3次乘法运算。

所以二分求幂即是根据矩阵乘法的结合律,减少重复计算的次数。

3)快速求幂(位运算)

因为幂数b可以看成是一个二进制,每一个1都可以看成是2的倍数。

a^21=(a^16)*(a^4)*(a^1)。

而21的二进制表示为10101。

而每次将b的二进制从右到左与1进行&运算。

模板函数

#include<iostream>
using namespace std;
double Pow1(double, int);//常规求幂
double Pow2(double, int);//二分求幂
double Pow3(double, int);//快速求幂,位运算
int main(){
double a;
int b;
while (cin >> a >> b){
double ans1 = Pow1(a, b);
cout << "常规求幂 : " << ans1 << endl;

double ans2 = Pow2(a, b);
cout << "二分求幂 : " << ans2 << endl;

double ans3 = Pow3(a, b);
cout << "快速求幂 : " << ans3 << endl;
cout << endl;
cout << "----------------------------" << endl;
cout << endl;
}
system("pause");
return 0;
}

//常规求幂
double Pow1(double a, int b){
if (b == 0)
return 1;
if (b > 0){
double r = 1;
while (b--){
r *= a;
}
return r;
}
if (b < 0){
double r = 1;
int c = -b;
while (c--){
r *= a;
}
return 1/r;
}

}

//二分求幂
double Pow2(double a, int b){
if (b == 0){
return 1;
}
if (b > 0){
double r = 1, base = a;
while (b != 0){
if (b % 2){
r *= base;
}
base *= base;
b /= 2;
}
return r;
}
if (b < 0){
double r = 1, base = a;
int c = -b;
while (c){
if (c %2){
r *= base;
}
c /=2;
base *= base;
}
return 1 / r;
}

}

//快速求幂,位运算
double Pow3(double a, int b){
if (b == 0){
return 1;
}
if (b > 0){
double r = 1, base = a;
while (b){
if (b & 1){
r *= base;
}
b >>=1;
base *= base;
}
return r;
}
else{
double r = 1, base = a;
int c = -b;
while (c){
if (c & 1){
r *= base;
}
c >>=1;
base *= base;
}
return 1 / r;
}
}


AC代码

#include<iostream>
#define ll long long unsigned

using namespace std;

const ll maxn= 1e9+7;
ll a[10005];
ll b[10005];

ll Pow3(ll a, int b){
if (b == 0){
return 1;
}
if (b > 0){
ll r = 1, base = a;
while (b){
if (b & 1){
r *= base;
r%=maxn;
}
b >>=1;
base *= base;
base%=maxn;
}
return r;
}
else{
ll r = 1, base = a;
int c = -b;
while (c){
if (c & 1){
r *= base;
}
c >>=1;
base *= base;
}
return 1 / r;
}
}

int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int T;cin>>T;
while(T--){
int n,t,k;
cin>>n>>t>>k;
for(int i=0;i<n;i++){
cin>>a[i];
}
int pos=t;//第一个数的位置
pos%=n;
for(int i=0;i<n;i++){
b[pos]=a[i];
pos++;pos%=n;
}
int bei=Pow3(k,t);

b[0]=b[0]*bei%maxn;
cout<<b[0];
for(int i=1;i<n;i++){
b[i]=b[i]*bei%maxn;
cout<<" "<<b[i];
}cout<<endl;
}
return 0;
}




举报

相关推荐

0 条评论