Home > Backend Development > C++ > body text

In C program, translate array range query with elements with same frequency

WBOY
Release: 2023-09-09 20:45:12
forward
1327 people have browsed it

In C program, translate array range query with elements with same frequency

Here we will see an interesting question. We have an array with N elements. We have to execute a query Q as follows:

Q(start, end) means that from start to end, the number "p" appears exactly "p" times. p>

So if the array looks like: {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8}, and the query is -

Q(1 , 8) - Here 1 appears once and 3 appears 3 times. So the answer is 2

Q(0, 2) - here 1 appears once. So the answer is 1

Algorithm

query(s, e) -

Begin
   get the elements and count the frequency of each element ‘e’ into one map
   count := count + 1
   for each key-value pair p, do
      if p.key = p.value, then
         count := count + 1
      done
      return count;
End
Copy after login

Example

#include <iostream>
#include <map>
using namespace std;
int query(int start, int end, int arr[]) {
   map<int, int> freq;
   for (int i = start; i <= end; i++) //get element and store frequency
      freq[arr[i]]++;
   int count = 0;
   for (auto x : freq)
      if (x.first == x.second) //when the frequencies are same, increase count count++;
   return count;
}
int main() {
   int A[] = {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8};
   int n = sizeof(A) / sizeof(A[0]);
   int queries[][3] = {{ 0, 1 },
      { 1, 8 },
      { 0, 2 },
      { 1, 6 },
      { 3, 5 },
      { 7, 9 }
   };
   int query_count = sizeof(queries) / sizeof(queries[0]);
   for (int i = 0; i < query_count; i++) {
      int start = queries[i][0];
      int end = queries[i][1];
      cout << "Answer for Query " << (i + 1) << " = " << query(start, end, A) << endl;
   }
}
Copy after login

Output

Answer for Query 1 = 1
Answer for Query 2 = 2
Answer for Query 3 = 1
Answer for Query 4 = 1
Answer for Query 5 = 1
Answer for Query 6 = 0
Copy after login

The above is the detailed content of In C program, translate array range query with elements with same frequency. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!