본문 바로가기

HackerRank/Data Structures

Dynamic Array

  • Create a list, , of  empty sequences, where each sequence is indexed from  to . The elements within each of the  sequences also use -indexing.
  • Create an integer, , and initialize it to .
  • The  types of queries that can be performed on your list of sequences () are described below:
    1. Query: 1 x y
      1. Find the sequence, , at index  in .
      2. Append integer  to sequence .
    2. Query: 2 x y
      1. Find the sequence, , at index  in .
      2. Find the value of element  in  (where  is the size of ) and assign it to .
      3. Print the new value of  on a new line

Task 
Given , and  queries, execute each query.

Note:  is the bitwise XOR operation, which corresponds to the ^ operator in most languages. Learn more about it on Wikipedia.

Input Format

The first line contains two space-separated integers,  (the number of sequences) and  (the number of queries), respectively. 
Each of the  subsequent lines contains a query in the format defined above.

Constraints

  • It is guaranteed that query type  will never query an empty sequence or index.

Output Format

For each type  query, print the updated value of  on a new line.

Sample Input

2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1

Sample Output

7
3

Explanation

Initial Values: 
 
 
 = [ ] 
 = [ ]

Query 0: Append  to sequence 
 
 = [5] 
 = [ ]

Query 1: Append  to sequence 
 = [5] 
 = [7]

Query 2: Append  to sequence 
 
 = [5, 3] 
 = [7]

Query 3: Assign the value at index  of sequence  to , print 
 
 = [5, 3] 
 = [7]

7

Query 4: Assign the value at index  of sequence  to , print 
 
 = [5, 3] 
 = [7]

3





이 문제는 C 언어 풀이에서도 나왔는데, C++로 Data Structures를 선택해도 나오는 것을 보니, 꼭 C 언어로 풀어야 하는 것은 아닌 것 같다.


일단 문제의 요지는 위 설명문의 조건 문장이다.


조건에 명시된대로 풀이를 하게 되면 되는데, 조건이 조금(?) 꼬여 있어서 하나씩 쉽게 풀이를 해보면 된다.


Query Type이 1인 경우, 주어진 SeqList에서 (x ^ LastAnswer) % N)의 인덱스에 y 값을 추가한다. 여기서 x는 첫번째 입력값, y는 두번째 입력값.


Query Type이 2 인 경우가 조금 헷갈릴 수 있다.

우선 Query Type 1인 경우처럼 (x ^ LastAnswer) % N)의 Index를 찾고, 그 인덱스가 가지고 있는 데이터 중에서, (y % 해당 시퀀스의 size()) 의 인덱스에 있는 값이 최종 LastAnswer가 된다.



C++의 Vector를 이용해서 작성하면 다음과 같은 코드가 될 수 있다.




C 언어로 풀이를 해놓은 코드가 있는데, 결국 vector를 사용하지 못하니까 malloc을 이용하여 메모리 컨트롤을 하고, realloc을 이용해서 매번 메모리를 다시 잡아주는 형태로 진행되었다. for 루프문 안쪽의 분기 처리를 보면 쉽게 이해를 할 수 있다.




'HackerRank > Data Structures' 카테고리의 다른 글

Insert a node at the head of a linked list  (0) 2018.09.06
Insert a Node at the Tail of a Linked List  (0) 2018.09.06
Print the Elements of a Linked List  (0) 2018.09.06
Sparse Arrays  (0) 2018.09.04
Left Rotation  (0) 2018.09.04