SDNUOJ 1594(高精度乘法、减法)

Description

There are many problems about a + b, however, there is no problem about a - b.
Now our friend Albert_s gives you a problem about a - b,
to increase the interest of the question, he needs you calculate a ^ b - b ^ a ​.

Input

The input will consist of a series of pairs of integers a and b (1 <= a, b <= 100) ​,
separated by a space, one pair of integers per line.

Output

For each pair of input integers a and b you should output a ^ b - b ^ a ​.

Sample Input

2 1

Sample Output

1

输入的a,b的值都是小于等于100的,可以看的出来,计算的时间复杂度并不高,只是位数特别大,还是比较容易发现是高精度的乘法和减法问题的,但是在比赛的时候是用数组解决的,不知道是不是哪里处理错了一直wa。。。
所以比赛以后去学了一下一种用vector的写法,感觉上要更简洁一些,也更容易理解一些。。。至少不会出现一些奇奇怪怪的错误233

#include
using namespace std;

vector<int> A, B;
int a, b;

bool cmp(vector<int> &A, vector<int> &B)
{
    if(A.size() != B.size()) return A.size() > B.size();
    for(int i = A.size() - 1; i >= 0; i --)
    {
        if(A[i] != B[i]) return A[i] > B[i];
    }
    return true;
}


vector<int> mul(vector<int> &A, int b)
{
    vector<int> C;
    int t = 0;
    for(int i = 0; i < A.size() || t; i ++)
    {
        if(i < A.size()) t += A[i] * b;
        C.push_back(t % 10);
        t /= 10;
    }
    return C;
}

vector<int> sub(vector<int> &A, vector<int> &B)
{
    vector<int> C;
    int t = 0;
    for(int i = 0; i < A.size(); i ++)
    {
        t = A[i] - t;
        if(i < B.size()) t -= B[i];
        C.push_back((t + 10) % 10);
        if(t < 0) t = 1;
        else t = 0;
    }
    while(C.size() > 1 && C.back() == 0) C.pop_back();
    return C;
}


int main()
{
    while(cin >> a >> b)
    {
        A.clear();
        B.clear();
        A.push_back(1);
        B.push_back(1);
        for(int i = 0; i < b; i ++)
        {
            A = mul(A, a);
        }
        for(int i = 0; i < a; i ++)
        {
            B = mul(B, b);
        }
        if(cmp(A, B))
        {
            vector<int> C = sub(A, B);
            for(int i = C.size() - 1; i >= 0; i --) printf("%d", C[i]);
        }
        else
        { 
            vector<int> C = sub(B, A);
            printf("-");
            for(int i = C.size() - 1; i >= 0; i --) printf("%d", C[i]);
        }
        puts("");
    }
    return 0;
}

你可能感兴趣的:(SDNUOJ 1594(高精度乘法、减法))