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

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

Yesterday I came across a question whereby I need to store the location and the respective element at that location and every time I need to access the location to perform the given operation here the array elements can repeat I know for some of you the doubt may be silly But i am kinda weak in data structure So please help..

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

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

Let's take a specific problem as an example. Say you're given a list of ints 43, 24, 11, 35, 52 and you want to print the indices of where the original elements go after the list gets sorted. So it would be 4 2 1 3 5 in this case.

What you'd do is store it in a vector<pair<int, int>> arr, where arr[i].first is the value at position i, and arr[i].second is the index (i originally, but will change after sorting).

Then sort the array and print out all arr[i].second values.

Another similar use is for permutations. It's often necessary to 'invert' them (not sure if that's correct terminology). So if you have an array perm[i], you want another array ind[i] such that perm[ind[i]] = i (ind[i] stores the index of i in perm). What you do is iterate through perm and set ind[perm[i]] = i for all 0 <= i < n.