https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&category=616&page=show_problem&problem=4566

注意字母相同的情况和最后只剩下一个字母的情况,在加密前后各判断/更新一次now(插入的字母)值。

/*0.003s*/

const int mx = 2000005; /// 开小了会RE

char k[mx], key[10][10], a[mx];
bool has[30];
p2 pos[30];

void make(char *k)
{
    mem(has, 0);
    int i, cnt = 0;
    for (i = 0; k[i]; ++i)
    {
        if (isalpha(k[i]))
        {
            k[i] &= 31;
            if (!has[k[i]]) pos[k[i]] = MP(cnt / 5, cnt % 5), key[cnt / 5][cnt % 5] = k[i], ++cnt, has[k[i]] = true;
        }
    }
    Forr(i, 1, 27)
    {
        if (i == ('J' & 31)) continue;
        if (!has[i]) pos[i] = MP(cnt / 5, cnt % 5), key[cnt / 5][cnt % 5] = i, ++cnt;
    }
}

void deal(char a, char b)
{
    if (pos[a].first == pos[b].first)
    {
        putchar('A' - 1 + key[pos[a].first][(pos[a].second + 1) % 5]);
        putchar('A' - 1 + key[pos[a].first][(pos[b].second + 1) % 5]);
    }
    else if (pos[a].second == pos[b].second)
    {
        putchar('A' - 1 + key[(pos[a].first + 1) % 5][pos[a].second]);
        putchar('A' - 1 + key[(pos[b].first + 1) % 5][pos[a].second]);
    }
    else
    {
        putchar('A' - 1 + key[pos[a].first][pos[b].second]);
        putchar('A' - 1 + key[pos[b].first][pos[a].second]);
    }
}

int now;

inline void addnow()
{
    now = now % 26 + 1;
    if (now == ('J' & 31)) ++now;
}

int main()
{
    int t, cas, i, cnt;
    SI(t), getchar();
    Forr(cas, 1, t + 1)
    {
        gets(k);
        make(k);
        gets(k);
        cnt = 0;
        for (i = 0; k[i]; ++i) if (isalpha(k[i])) a[cnt++] = k[i] & 31;
        printf("Case %d: ", cas);
        now = 1;
        For(i, cnt)
        {
            if (i + 1 < cnt)
            {
                if (a[i] == a[i + 1])
                {
                    if (now == a[i]) addnow();
                    deal(a[i], now);
                    addnow();
                }
                else deal(a[i], a[i + 1]), ++i;
            }
            else
            {
                if (now == a[i]) addnow();
                deal(a[i], now);
                addnow();
            }
        }
        putchar(10);
    }
    return 0;
}

Comments

comments powered by Disqus