Блог пользователя rashid_aziz

Автор rashid_aziz, история, 19 месяцев назад, По-английски

I recently encountered an interesting performance issue while solving the "Sereja and Brackets". I implemented a Segment Tree-based solution but found that my code was giving a "Time Limit Exceeded" (TLE) on the 13th test case. After some investigation, I discovered that the issue was related to how I was initializing a vector.

Originally, I was adding 3 elements to the vector using push_back() in a loop. To improve the performance, I decided to initialize the vector with a fixed size of 3 upfront, like this: vector t(3, 0). Surprisingly, this simple change made a huge difference, and my code passed all test cases with ease.

After some searching, I discovered that one reason for the performance hit is that when we use push_back() to add elements to a vector, the vector may need to be resized. This resizing involves allocating a new block of memory, copying the existing data to the new block, and then deallocating the old block. This process can be time-consuming, especially if the vector is large or the constraints are tight.

To avoid unnecessary resizing and copying, it's often a good idea to reserve enough space in the vector upfront to accommodate all the elements we need to add. This can be done using the reserve() function. By reserving enough space, we can ensure that the vector doesn't need to be resized as often, and that the performance of our code become much better.

Overall, this experience taught me the importance of carefully considering how vectors are initialized in performance-critical code.

Soltuion 1 link which got TLE

Soltuion 2 link which got accepted

Полный текст и комментарии »

  • Проголосовать: нравится
  • +7
  • Проголосовать: не нравится

Автор rashid_aziz, история, 2 года назад, По-английски

There's a question in my mind that, why do some people are able to achieve candidate master by just solving 600-700 questions, whereas few are not even able to reach expert after solving 1000+ question, I'm really concerned about this because i have started CP few months back and don't want to go on a wrong path, so I wanted to know what mistake these people do? so that i won't repeat those mistakes. for example https://mirror.codeforces.com/profile/Mr_Frodo, he have solved 1000+ question, and still not able to achieve Expert.

Note : I'm not trying to discredit anyone, just asking so that we can I can learn.

Полный текст и комментарии »

  • Проголосовать: нравится
  • -26
  • Проголосовать: не нравится

Автор rashid_aziz, история, 2 года назад, По-английски

include

using namespace std; int main() { string s = "abcd"; int i = -1; while(i < s.size()){ cout << "inside "; i++; } cout << "outside"; return 0; }

why this loop does not run, where as when we initialize i = 0, then it runs properly

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится