DEV Community

Anurag Pandey
Anurag Pandey

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay