decoder__'s blog

By decoder__, history, 4 years ago, In English

Can anyone help me why my code is giving runtime error on cf but works fine on my local machine? Code: https://codeforces.net/contest/1215/submission/89127974 Problem: https://codeforces.net/contest/1215/problem/C Will codeforces compiler give an error if a vector is empty and size function is called on the vector ?

  • Vote: I like it
  • -4
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

for (ll i = 0; i < inda.size() - 1; i += 2) {

vector.size() is unsigned type, for empty vector this loop runs until using i as an index causes runtime error.

Better use for (ll i = 0; i+1 < inda.size(); i += 2) {

I assume that testcase would not work on you machine, too.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Can you elaborate on this?

    How thisfor (ll i = 0; i+1 < inda.size(); i += 2) { will work but not this for (ll i = 0; i < inda.size() - 1; i += 2) {

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      size() returns an unsigned integer. Unsigned integers can't be negative. If you do an operation on an unsigned integer that results in a negative value, it wraps around to a positive value. Also, when you do an operation involving signed and unsigned integers, the signed operand is converted to an unsigned integer, resulting in negative values wrapping around.