We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

I learned a funny thing by doing this... in C++, the vector.size() method returns an unsigned int, so subtraction might silently wrap around to a large number, instead of a negative one. I can't believe I've never encountered this problem before...

int n,k;
cin >> n >> k;
vector <int> impt;
int impt_sum=0;
int unimpt_sum=0;
for (int i=0;i<n;i++) {
int luck,type;
cin >> luck >> type;
if (type) {
impt.push_back(luck);
impt_sum+=luck;
}
else
unimpt_sum+=luck;
}
sort(impt.begin(),impt.end());
int isize=impt.size();
if (k<=isize) for (int i=isize-k-1;i>=0;i--) impt_sum-=(2*impt[i]);
cout << impt_sum+unimpt_sum;

## Luck Balance

You are viewing a single comment's thread. Return to all comments →

I learned a funny thing by doing this... in C++, the vector.size() method returns an

unsignedint, so subtraction might silently wrap around to a large number, instead of a negative one. I can't believe I've never encountered this problem before...I haven't used C++ in over a decade but this implementation certainly makes sense. Would I have caught it right away - probably not!

Had same problem. Was getting segmentation fault. Thanks buddy.

then what changes u did ?

then how did u solved the thing ??

u can cast unsigned int (which is returned by vector.size()) to int

thx buddy..