Tuesday, August 7, 2018

Codeforces 266A Stones on the Table Solution in C (Explained)

Stones on the Table (266A) asks for the minimum number of removals, which sounds like an optimization problem. It turns out to need only one comparison per stone. (This post was previously titled 226A by mistake; the problem is 266A.)

The problem in short

n stones (1 ≤ n ≤ 50) stand in a row, each colored red, green or blue, given as a string of R, G and B. Remove the fewest stones so that no two neighboring stones have the same color. Print that number.

Full statement: Codeforces 266A – Stones on the Table.

Key idea

Think of the row as blocks of equal colors. For example, RRRGGB is the block RRR, then GG, then B.

  • Inside a block of length L, every stone touches a same-colored neighbor, and we must remove at least L − 1 of them to leave one.
  • Keeping exactly one stone per block is enough: neighboring blocks always have different colors by definition.

The total of (L − 1) over all blocks equals the number of positions i where s[i] == s[i - 1]. So the answer is simply the number of adjacent equal pairs.

Examples

  • RRG: one equal pair (R, R) → 1.
  • RRRRR: four equal pairs → 4. Only one stone remains.
  • BRBG: no equal neighbors → 0.

Solution in C

#include <stdio.h>

int main(void) {
    int n;
    char s[55];
    scanf("%d %s", &n, s);

    int removals = 0;
    for (int i = 1; i < n; i++) {
        if (s[i] == s[i - 1])
            removals++;
    }

    printf("%d\n", removals);
    return 0;
}

Why we never need to simulate the removals

If we only ever remove extra stones from inside a block, any two stones that end up next to each other afterwards either came from the same block (and that pair was already counted) or from two different blocks (which have different colors). So removing stones can never create a conflict we did not already count, and counting equal pairs in the original string is enough.

Complexity

One pass: O(n) time and O(1) extra memory.

Common mistakes

  • Starting the loop at i = 0 and comparing with s[-1], which reads outside the array.
  • Counting the blocks instead of the equal pairs. The number of blocks is the number of stones you keep, not remove.

Practice next

96A Football uses the same “compare with the previous character” loop to find long runs.

No comments:

Post a Comment