As you know our star "gachn" is a rising star in competitive programming but nowadays he is upset because of a task was given to him by his mentor. His teacher gave him a task: The task is that he has been given an array of N integers. his teacher gave him Q queries to solve. For each query he has to tell the teacher the number of distinct integers from Ai.Ai+1.Ai+2.......AN.
Example:
Input: n = 5, q = 3, a = {1, 2, 3, 2, 1}, queries = {2, 1, 4}
Output:
3 3 2
Approach:
C++
#include <bits/stdc++.h>using namespace std;int main(){int n = 5, q = 3;vector<int> a = {1, 2, 3, 2, 1};vector<int> queries = {2, 1, 4};int distinct[n];int dNums = 0;set<int> numbers;for (int i = n - 1; i >= 0; i--){if (numbers.count(a[i]) == 0){numbers.insert(a[i]);distinct[i] = ++dNums;}elsedistinct[i] = dNums;}for (int i = 0; i < q; i++){cout << distinct[queries[i] - 1] << endl;}return 0;}
No comments:
Post a Comment