DEV Community

Cover image for Day 5: Inconsistent days
Anurag Pandey
Anurag Pandey

Posted on • Updated on • Originally published at geekypandey.github.io

Day 5: Inconsistent days

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.

Two problems a day, keeps doctor away!

Problem 1: Brain's Photos

Simple problem of taking input and comparing it with different values.

main() {
  int n, m; cin >> n >> m;
  bool bw = true;
  for(int i = 0; i < n; i++) {
    for(int j = 0; j < m; j++) {
      char c;
      cin >> c;
      if(c == 'C' || c == 'M' || c == 'Y') bw = false;
    }
  }
  if(bw) cout << "#Black&White";
  else cout << "#Color";
}
Enter fullscreen mode Exit fullscreen mode

This is better style of writing for the given problem. No need to write two for loops. Cleaner code.

main() {
  int n, m; cin >> n >> m;
  bool bw = true;
  char c;
  while(cin >> c) {
    if(c == 'C' || c == 'M' || c == 'Y') bw = false;
  }
  if(bw) cout << "#Black&White";
  else cout << "#Color";
}
Enter fullscreen mode Exit fullscreen mode

Problem 2: Sereja and Dima

Implementing the greedy take and find score of each player.

main() {
  int n;
  cin >> n;
  vector<int> v(n);
  for(auto& e: v) cin >> e;
  int i = 0, j = n-1;
  int s = 0, d = 0;
  bool ser = true;
  while(i <= j) {
    if(v[i] > v[j]) {
      if(ser) s += v[i];
      else d += v[i];
      i++;
    } else {
      if(ser) s += v[j];
      else d += v[j];
      j--;
    }
    ser = !ser;
  }
  cout << s << ' ' << d;
}
Enter fullscreen mode Exit fullscreen mode

More cleaner code and easy to understand.

main() {
  int n;
  cin >> n;
  vector<int> v(n);
  for(auto& e: v) cin >> e;
  int i = 0, j = n-1;
  int s = 0, d = 0;
  bool ser = true;
  while(i <= j) {
    int val = max(v[i], v[j]);
    if(ser) s += val;
    else d += val;
    ser = !ser;
    if(val == v[i]) i++;
    else j--;
  }
  cout << s << ' ' << d;
}
Enter fullscreen mode Exit fullscreen mode

Algorithm

We didn't learn any new algorithm today :-(

Dated: 17th July 2021

Top comments (0)