Official

A - Decisive Battle Editorial by en_translator


If you are new to learning programming and do not know where to start, please try Problem A “Welcome to AtCoder” from practice contest. There you can find a sample code for each language.
Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in “AtCoder Beginners Selection” (https://atcoder.jp/contests/abs).


As the problem statement clarifies, \(S\) has an odd length, so it never happens that E and W occur the same number of times; one of E and W is more frequent than the other.

There are various approaches to decide which occurs more; we will present one example.

  • Prepare a variable \(h=0\).
  • Inspect the characters of \(S\) one by one. For each character, if you encounter E, add \(1\) to \(h\), and if you encounter W, subtract \(1\) from \(h\).
  • After inspecting all characters, if \(h>0\), then there are more E than W; otherwise, there are more W than E.

This way, we can determine which is majority using only one variable, ignoring the actual count of each character.

This implementation can be realized by, for example, combining for and if statements.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  string s;
  cin >> s;
  int h=0;
  for(auto &nx : s){
    if(nx=='E'){h++;}
    else{h--;}
  }
  if(h>0){cout << "East\n";}
  else{cout << "West\n";}
  return 0;
}

posted:
last update: