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

Автор sonjoydabnath, 11 лет назад, По-английски

While looking for how other people solved the problem I see a solution (1620364) of 182D - Общие делители by RAD . In this solution He tried to initialize and access a negative index of a Array! I 've always known that it's not possible. Can anybody explain me how he did this or, how negative index working on an Array ?

A significant part of RAD's code:


void calc_hash(const string &s, int64 *&h) { h = new int64[110000] + 1; h[-1] = 0; //initiating a negative index with a value of 0!! forn(i, s.size()) h[i] = h[i - 1] * 313 + s[i]; } ......... ...... .... . ... //code snippet from the main function int ans = 0; for (int len = min((int)s1.size(), (int)s2.size()); len >= 1; len--) if (s1.size() % len == 0 && s2.size() % len == 0) { int64 ha = h1[len - 1]; for (int i = len - 1; i < (int)s1.size(); i += len) if (h1[i] - h1[i - len] * pw[len] != ha) //here i-len sometimes could be negative, goto bad; //but it's Not giving RTE :O for (int i = len - 1; i < (int)s2.size(); i += len) if (h2[i] - h2[i - len] * pw[len] != ha) goto bad; ans++; bad:; } cout << ans << endl;
  • Проголосовать: нравится
  • +11
  • Проголосовать: не нравится

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

Ehhhh... Did you see the line above that h[ - 1]?

In C++ tab[5] is changed by compiler to reference to value at address tab + 5 and that is why you can also write 5[tab] and that is why h[ - 1] is reference to value at address h - 1 and since h = newint64[110000] + 1; we get h - 1 = h = newint64[110000] which is perfectly valid.

Personally, I hate 0-based indexing and that example is main reason why — because 1-based indexing allows us to set some guards at position 0. I can't understand how 0-based indexing lovers write their dp where for example dp[i] = 2·dp[i - 1] + 5 holds, but they can't use that formula for i = 0 >_>...

»
11 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится -12 Проголосовать: не нравится

int a[1];

for(int i = 100; i < 1000; i++) cout << a[i] <<" ";

Also will work!