Simultaneous Marble Chain Reactions
National Olympiad — Regional round (2012 season)
Submission name: marbles.cpp
Problem summary
Repeatedly find every maximal run of at least three equal-coloured marbles and remove all such runs simultaneously. Stop when no run can be removed.
Input
A string over R,Y,G,B.
Output
The remaining string, or EMPTY when all marbles disappear.
Constraints
3 ≤ initial string length ≤ 1024.
Worked example
Input and output for the worked example discussed below.
Input
BRRRRGGYYYGGB
Output
BB
Solution analysis
- One round must inspect the old sequence without changing it in place. Scan maximal equal-character runs and copy only runs of length 1 or 2 into a fresh string.
- After the whole round, compare the new length with the previous length. If unchanged, no eligible run existed and the process is finished. Otherwise use the new string for the next round; newly adjacent marbles may now form another removable run.
- In the sample the first round removes RRRR and YYY simultaneously, leaving BGGGGB. The second removes GGGG and leaves BB. Removing one run and immediately rescanning before other original removals can produce a different, incorrect result.
Why it works
The run scan finds all and only maximal same-colour blocks in the current sequence. Copying precisely those shorter than three implements a simultaneous deletion round. Each changing round shortens the sequence, so the algorithm terminates at exactly the first sequence with no removable run.
Watch out. Deletion is simultaneous, not a left-to-right cascading stack rule. Flush the final run. Print the exact uppercase EMPTY only for an empty result.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
#include<string>
using namespace std;
int main(){
string marbles;
cin>>marbles;
while(true){
string next;
for(size_t start=0;start<marbles.size();){
size_t end=start+1;
while(end<marbles.size()&&marbles[end]==marbles[start]){
end++;
}
// Copy survivors only after identifying a complete old run.
if(end-start<3){
next.append(marbles,start,end-start);
}
start=end;
}
if(next.size()==marbles.size()){
break;
}
marbles=next;
}
cout<<(marbles.empty()?"EMPTY":marbles)<<'\n';
}