NguyenDangQuan's blog

By NguyenDangQuan, history, 5 years ago, In English

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.net/contest/1343/submission/77570494 Accepted: https://codeforces.net/contest/1343/submission/77570825

  • Vote: I like it
  • +10
  • Vote: I do not like it

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

Put the link to the submission.

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

    I have just updated the submissions links, sorry for the inconvenience

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

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

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

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?

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

    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.

»
5 years ago, # |
  Vote: I like it +17 Vote: I do not like it

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!

»
5 years ago, # |
  Vote: I like it +7 Vote: I do not like it

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.