DEV Community

Anurag Pandey
Anurag Pandey

Posted on

Day 8: Stacking up

Disclaimer:

I am a beginner in competitive programming, and this is me documenting my learnings. So, anything I say is just what I think at the moment and should not be taken as hard truths.

Problem 1: cAPS lOCK

Based on some property, give answer.

#define all(x) begin(x), end(x)

main() {
  string s;
  cin >> s;

  int n = s.length();
  bool first = islower(s[0]);
  bool c = count_if(all(s), [](char c){ return isupper(c); });
  // check condition
  if((c == n) || (first && (c == n-1))) {
    for(auto& e: s) {
      if(isupper(e)) cout << tolower(e);
      else cout << toupper(e);
    }  
  } else {
    cout << s;
  }
}
Enter fullscreen mode Exit fullscreen mode

To toggle case we can also use bitwise operators. It grossly simplyfies the code.

for(auto& c: s) {
  cout << (char) (c^32); // toggle case
}
Enter fullscreen mode Exit fullscreen mode

New cpp standard algorithm used:

Problem 2: Xenia and Ringroad

Simple math problem.

#define forn(i, n) for(int i = 0; i < n; i++)

main() {
  ll n, m;
  cin >> n >> m;
  ll ans = 0, curr = 1; 
  forn(_, m) {
    ll next;
    cin >> next;
    if(next >= curr) ans += (next-curr);
    else {
      ans += (n-curr)+next;
    }
    curr = next;
  }
  cout << ans;
}
Enter fullscreen mode Exit fullscreen mode

Algorithm

We didn't learn any new algorithm today.
I should practice more problems, so that when I get stuck somewhere, I could try to learn a new algorithm.
Also knowing the basics should help, rather than learning all complex algorithms at once.
Sticking to learn new algorithm if and when required and doubling the questions to be practiced.

Sources

Top comments (0)