Dynamic Array

  • Create a 2-dimensional array, arr, of  empty arrays. All arrays are zero indexed.
  • Create an integer, , and initialize it to .
  • There are  types of queries:
    1. Query: 1 x y
      1. Find the list within  at index .
      2. Append the integer  to the .
    2. Query: 2 x y
      1. Find the list within  at index .
      2. Find the value of element  where  is the number of elements in lastAnswer$.
      3. Print the new value of  on a new line

Example:

Input:  n=2,q=5,queries={{1,0,5},{1,1,7},{1,0,3},{2,1,0},{2,1,1}}
Output: 7
3

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<intdynamicArray(int nvector<vector<int>> queries)
{
    vector<intres;
    int lastAnswer = 0;
    vector<vector<int>> v(nvector<int>());
    int zxy;
    int q = queries.size();
    for (int i = 0i < qi++)
    {

        z = queries[i][0];
        x = queries[i][1];
        y = queries[i][2];
        if (z == 1)
        {

            int p = (x ^ lastAnswer) % n;
            v[p].push_back(y);
        }
        else if (z == 2)
        {
            int p = (x ^ lastAnswer) % n;
            lastAnswer = v[p][y % v[p].size()];
            res.push_back(lastAnswer);
        }
    }
    return res;
}

int main()
{
    int n = 2q = 5;
    vector<vector<int>> queries = {{105}, {117}, {103}, {210}, {211}};
    vector<intres = dynamicArray(nqueries);
    for (int i = 0i < res.size(); i++)
    {
        cout << res[i] << "\n";
    }
    return 0;
}


No comments:

Post a Comment