题解 AT750 【A + B】

· · 题解

AT750 A + B

\LARGE\mathtt{Solution:}

朴素算法加一点小优化.

\mathtt{sum}:\text{储存}\mathtt{A+B}\text{的和}

然而很遗憾,第64个点 \color{white}\colorbox{#052242}{\texttt{ TLE }} 了. 不过经过我的奇思妙想,我想出了一种奇 \mathtt{miu} 的优化:

测试点中,肯定会有连续询问 'Q' 的情况, 所以遇到这种情况我们只需要输出上一次操作结果即可.

就 \color{white}\colorbox{#52C41A}{\texttt{ AC }} 了,虽然是 \mathtt{10.20s} ...

代码:

#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <string.h>

#define SWAP(_a,_b) ((_a)^=(_b)^=(_a)^=(_b))

char A[300007], B[300007], op,lastOP,sum[300007];
int a[300007], b[3000007];
int la, lb, lmax, N, opIndex, ans;

void Init()
{
    int i;
    scanf("%d%s%s", &N,&A,&B);
    getchar();
    la = strlen(A);
    lb = strlen(B);
    // 倒序存储
    for (i = 0; i < la; ++i)a[la - 1 - i] = A[i] - '0';
    for (i = 0; i < lb; ++i)b[lb - 1 - i] = B[i] - '0';

    lmax = la > lb ? la + 1 : lb + 1; // +1是因为相加后可能会有进位
}

void AddOne(int _index)
{
    sum[_index]++;
    if (sum[_index] >= 2)
    {
        while (_index < lmax)
        {
            sum[_index + 1]++;
            sum[_index] -= 2;
            if (sum[_index + 1] == 1)break;
            _index++;
        }
    }
}


void LowOne(int _index)
{
    sum[_index]--;
    if (sum[_index] < 0)
    {
        while (_index < lmax)
        {
            sum[_index + 1]--;
            sum[_index] += 2;
            if (sum[_index + 1] == 0)break;
            _index++;
        }
    }
}

int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    Init();
    int i;
    for (i = 0; i < lmax; ++i)
    {
        sum[i] += a[i] + b[i];
        if (sum[i] >= 2) {
            sum[i] -= 2;
            sum[i + 1]++;
        }
    }
    while (N--)
    {
        scanf("%c", &op);
        if(op== 'Q')
        {
            op=getchar();
            if (lastOP == 'Q')
            {
                printf("%d\n", ans);
                continue;
            }
            ans = 0;            
            for (i = lmax; i >=0; --i)
            {
                if (a[i] != sum[i])
                {
                    ans += i;
                    break;
                }
                if (a[i]==1)ans++;
            }
            printf("%d\n", ans);
        }
        else if (op == 'A')
        {
            scanf("%d", &opIndex);
            getchar();
            a[opIndex] ? LowOne(opIndex) : AddOne(opIndex);
            a[opIndex] = !a[opIndex];
        }
        else if (op == 'B')
        {
            scanf("%d", &opIndex);
            getchar();
            b[opIndex] ? LowOne(opIndex) : AddOne(opIndex);
            b[opIndex] = !b[opIndex];
        }
        lastOP = op;
    }
    return 0;
}

与 P1001 A+B Problem 只差一个 Problem 难度就上天了...

刚刚重新交了一遍,尽然变成 \mathtt{8.19s} 了,真就 网速 == 评测姬速度 ???