题解:B3739 [信息与未来 2018] 整数乘方
Mark_Pei
·
·
题解
Solution。
要解决这个问题,我们要一步步地模拟题意(废话)。可以看出这道题数据较大,所以我们要用高精度计算 a^n,再转换为字符串 A 和 B,最后统计奇偶数字符的个数,计算 A−B。
献上解题思路:
计算 a^n,由于 n 的最大值是 100,所以 a^n 可能非常大,超出 long long 范围,需要使用高精度计算。
转换为字符串,将 a^n 的结果转换为字符串,方便逐个字符检查。
统计奇偶数字符,遍历字符串,统计奇数字符和偶数字符的个数。
计算 A−B:输出结果。
好习惯,分析一下时间复杂度:
高精度乘法:O(m×n),其中
计算 $a^n$:$O(n×m^2)$,其中 $m$ 是 $a$ 的位数。
统计奇偶数字符:$O(d)$,其中 $d$ 是 $a^n$ 的位数。
**所以**,总的时间复杂度为 $O(n×m^2)$。
**AC** ~~code~~
```cpp
#include <bits/stdc++.h>
using namespace std;
string mul(string x,string y)//高精度计算
{
int l1 = x.size(), l2 = y.size();
string res(l1 + l2, '0');
for (int i = l1 - 1; i >= 0; i--)
{
for (int j = l2 - 1; j >= 0; j--)
{
int t = (x[i] - '0') * (y[j] - '0') + (res[i + j + 1] - '0');
res[i + j + 1] = t % 10 + '0';
res[i + j] += t / 10;
}
}
size_t p = res.find_first_not_of('0');
return p != string::npos ? res.substr(p) : "0";
}
string pow(int a,int n)//计算a^n
{
string r="1";
string b=to_string(a);
while (n--) r=mul(r,b);
return r;
}
int cal(string s)//计算A-B
{
int A=0,B=0;
for (char c : s)
{
int d = c - '0';
if (d % 2) A++;
else B++;
}
return A-B;
}
int main()
{
int a,n;
cin>>a>>n;
string s=pow(a, n);
cout<<cal(s);
return 0;
}
```