Weird behaviour of mp size function

problem link : Problem - 1335C - Codeforces
solution link : Submission #93038111 - Codeforces

I just had a question in my mind .

In that solution at first I didn’t assigned mp.size() to p then It was showing weird behavior.But after assignment it is working properly.

Can someone here explain me what’s actually happening if we replace p with mp.size() ?

Put a int in front of mp.size() i.e. (int)mp.size(), its throwing undefined behavior

Can you post the original solution and explain what you mean by “showing weird behaviour”?

LumeWD - Online C++ Compiler & Debugging Tool - Ideone.com.

See this link for 2 testcase it is giving wrong answer .
when I printed (maxi - (mp.size() - 2)
op is : 18446744073709551613

That’s because the type of std::map::size is unsigned, so a negative number - for example, if mp.size() is 1 and you requested mp.size() - 2 - will appear as a huge positive number.

2 Likes

well yes I know that but I want to know why it’s showing undefined behavior.

Oh Tq very much . I didn’t knew that.

1 Like

In future, it’s a very good idea to pay attention to compiler warnings:

simon@simon-laptop][12:39:44]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling makop-blah.cpp
+ g++ -std=c++14 makop-blah.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
makop-blah.cpp: In function ‘int main()’:
makop-blah.cpp:37:37: warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
         else if((maxi - mp.size())  >= 0) {
                 ~~~~~~~~~~~~~~~~~~~~^~~~

2 Likes