MrArM's blog

By MrArM, 11 years ago, In English

Hi :)

Can any body help me about problem 299 sgu !?

Why my code got Runtime Error on test 11 !! ?

What's wrong with me ?!

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

»
11 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I don't know, how it can be compiled, but it is wrong:

  int n;
  cin>>n;
  string s[n+10];

Use vector instead:

  int n;
  cin>>n;
  std::vector<string> s(n);
  • »
    »
    11 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Can you tell me why !? you say that therse is'nt array of strings !?

    • »
      »
      »
      11 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it
      string s[n+10]
      

      is array, but according C++ standard, array's length must be constant, which is known at compile-time. In your case n is unknown at compile-time, so it is undefined behaviour.

      • »
        »
        »
        »
        11 years ago, # ^ |
          Vote: I like it +11 Vote: I do not like it

        It’s not undefined behaviour. According to the standard, the program is invalid, and a strictly conforming compiler will reject it, i. e. refuse to compile. However, in practice compilers support this as a language extension.

        Note that variable length arrays are perfectly valid in C since C99.

»
11 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Another bug:
1) Use "return a < b;" in cmp function 2) And use

if (cmp(s[i+2], PLUS(s[i], s[i+1])))

Instead

if(!cmp(PLUS(s[i],s[i+1]),s[i+2]))
  • »
    »
    11 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    Accepted! big thanks! :)

    But I don't understand what is difference of them !

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

      There is no problem in

      cmp(PLUS(a, b), c)
      

      here's everything ok. :)

      The potential problem is in

      sort(s.begin(), s.end(), cmp)
      

      because sort and other functions from <algorithm> header expect strict predicate ( less , not lessOrEqual). In some compilers, using lessOrEqual can bring to runtime-assert-check. For example:

      bool BadPredicate(int a, int b)
      {
          return a <= b;
      }
      ...
      int x[] = {1, 2, 1, 2};
      std::sort(x, x + sizeof(x)/sizeof(x[0]), &BadPredicate);
      

      Gives debug-assert in MSVS 2010:

      if (!_Pred(_Left, _Right))
          return (false);
      else if (_Pred(_Right, _Left))
          _DEBUG_ERROR2("invalid operator<", _File, _Line);
      

      But it's not critical for problem acceptance on contest (because problem runs not in debug config), it's right way to make reliable software. :)