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

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

Hi, I'm now crazing with memset() and fill() or fill_n(), in the Problem D Div3 Round #636, i used fill_n() and it was TLE, so I changed to memset() and accepted. I dont't understand the way memset work. Can you explain me ? Thank you

*In addition, sometimes i use memset but it doesn't work well Here are my submissions: TLE: https://codeforces.com/contest/1343/submission/77570494 Accepted: https://codeforces.com/contest/1343/submission/77570825

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

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Put the link to the submission.

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by NguyenDangQuan (previous revision, new revision, compare).

»
4 года назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

I also needed a little clarification with regard to how memset works, because doing something like

memset(arr, -2, sizeof(arr));

gives overflow. Can someone please help me with this explanation?

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +17 Проголосовать: не нравится

    memset fills the entire array byte by byte. Thus filling with -2 means filling with 11111110 (2's complement form of -2). In case your array is a int array, each element is of 32 bits or 4 bytes. Hence, each array element will be filled with 11111110 11111110 11111110 11111110 which is -16843010 in decimal form which you have mistaken for overflow. So memset is used to fill only values like 0 (00000000) , -1(11111111) etc. Hope it helps.

»
4 года назад, # |
  Проголосовать: нравится +17 Проголосовать: не нравится

memset fills the array byte by byte. Therefore if you do something like: memset(array, 1, sizeof(array)), you will find that all elements of the array are NOT set to 1 but to $$$16843009 $$$ but instead if you use fill_n(array, N, 1), this will fill all elements of the array with value $$$1$$$. I hope it helps!

»
4 года назад, # |
  Проголосовать: нравится +7 Проголосовать: не нравится

Yes, memset is sometimes faster. It's a more low-level byte thing, while fill is similar to the usual for-loop you'd write to set the values.