跳到正文

题解

题解:B3739 [信息与未来 2018] 整数乘方

Mark_Pei约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年3月8日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 3 分钟
题目
B3739

版本

  1. v1当前

Solution。

要解决这个问题,我们要一步步地模拟题意(废话)。可以看出这道题数据较大,所以我们要用高精度计算 ana^n,再转换为字符串 AA 和 BB,最后统计奇偶数字符的个数,计算 A−BA−B。

献上解题思路:

计算 ana^n,由于 nn 的最大值是 100100,所以 ana^n 可能非常大,超出 long long 范围,需要使用高精度计算。

转换为字符串,将 ana^n 的结果转换为字符串,方便逐个字符检查。

统计奇偶数字符,遍历字符串,统计奇数字符和偶数字符的个数。

计算 A−BA−B:输出结果。

好习惯,分析一下时间复杂度:

高精度乘法:O(m×n)O(m×n),其中 mm 和 nn 是两个乘数的位数。

计算 ana^n:O(n×m2)O(n×m^2),其中 mm 是 aa 的位数。

统计奇偶数字符:O(d)O(d),其中 dd 是 ana^n 的位数。

所以,总的时间复杂度为 O(n×m2)O(n×m^2)。

AC code

C++
#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;
}
原文