I have made a program, which prints out numbers in a form of a shape.
I want to be able to calculate the sum of a selected row, e.g. I display a shape of 3 rows
1
1 2
1 2 3
1 2
1
If I wanted to calculate the sum of row 2, it will add 1 and 2 together to show the result.
How would I achieve this?
This is my code so far
#include <iostream>
using namespace std;
int main()
{
int i,k=0,n;
int space = n-1;
cout << "Enter amount of rows: ";
cin >> n;
while(k <= n)
{
for(i = 1; i <= k; i++)
cout<<i;
cout<<endl;
k++;
}
k=n;
while (k)
{
k--;
for (i = 1; i <= k; i++)
cout<<i;
cout<<endl;
}
return 0;
}
Since the numbers in each row begin with 1 and you know the total number of rows from the input n, the sum of numbers in each row can be easily calculated.
You can add the following code after the second while loop:
int rowNo; //For which the sum has to be calculated
cout << "Enter the row for which the sum has to be calculated" << endl;
cin >> rowNo;
int sum = 0;
int totalRows = n * 2 - 1;
if(rowNo <= totalRows)
{
if(rowNo > n)
rowNo = n - rowNo%n;
for (int i = 1; i <= rowNo; i++)
{
sum = sum + i;
}
cout << "Sum is " << sum << endl;
}
else
{
cout << "rowNo: "<< rowNo << " is greater than the total no of rows: " << totalRows << endl;
}
Once you printed all lines, there's no simple way to go back and calculate the sum of the numbers on a specific line.
The simplest way is to calculate the sums of the numbers of all lines (as you print them) and store in e.g. a vector. Then when you need to get the sum of a specific line just get the pre-calculated sum from the vector.
I'm not going to answer your homework for you but I'd like to give you a few ideas on how to improve your code and how to build a solution that is able to calculate the sum of the desired rows.
Don't simply print your shape when the user entered a number, rather build an object that contains the row information and can be printed.
class Shape {
...
private:
std::vector<Row> rows;
public:
Shape( int numberOfRows );
void Print();
...
}
A Row on the other hand could contain only the information about a single rows content
class Row {
...
private:
std::vector<int> content;
public:
void Print();
...
}
All you then need is to find implement a way of requesting a single Row from the Shape and calculate it's sum. The good thing about this way is, that you can easily repeat the 2. step and ask for different rows over and over again.
In your main you would then need to perform the following steps
Ask for the the number of rows
Create a Shape and print it to the screen
Ask a user for a row to calculate the sum of (maybe repetitively)
Calculate the sum and display it to the user (go back to 3. or exit)
EDIT:
I just read that you only had a few basics, so you probably haven't heard about classes yet. So your best bet IMO would be to store the shape in an array ( or an array of arrays ), btw. a std::vector<int> is somewhat similar to a C-Style array (int[]). Then you can still access the data after you have printed it and calculate the sum of a single row.
Related
Hey there! In the following code, I am trying to count frequency of each non zero number
My intention of the code is to update freq after testing each case using nested loop but value of freq is not updating. freq value remains to be either 0 or 1. I tried to debug but still ending up with the same bug.
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
int size;
cin>>size;
int freq=0;
int d[size];
for(int i=0;i<size;i++){ //To create array and store values in it
cin>>d[i];
}
for(int i=0;i<size;i++){
if(d[i]==0 )continue;
for(int j=0;j<size;j++){
if(d[i]==d[j]){
freq=freq+1;
d[j]=0;
}
}
cout<<"Frequency of number "<<d[i]<<" is "<<freq<<endl;
d[i]=0;
freq=0;
}
}
Input:
5
1 1 2 2 5
Expected output:
Frequency of number 1 is 2
Frequency of number 2 is 2
Frequency of number 5 is 1
Actual output:
Frequency of number 0 is 1
Frequency of number 0 is 1
Frequency of number 0 is 1
Frequency of number 0 is 1
Frequency of number 0 is 1
Some one please debug the code and fix it. Open for suggestions.
#include <bits/stdc++.h>
This is not standard C++. Don't use this. Include individual standard headers as you need them.
using namespace std;
This is a bad habit. Don't use this. Either use individual using declarations for identifiers you need, such as using std::cout;, or just prefix everything standard in your code with std:: (this is what most people prefer).
int d[size];
This is not standard C++. Don't use this. Use std::vector instead.
for(int j=0;j<size;j++){
if(d[i]==d[j]){
Assume i == 0. The condition if(d[i]==d[j]) is true when i == j, that is, when j == 0. So the next thing that happens is you zero out d[0].
Now assume i == 1. The condition if(d[i]==d[j]) is true when i == j, that is, when j == 1. So the next thing that happens is you zero out d[1].
Now assume i == 2. The condition if(d[i]==d[j]) is true when i == j, that is, when j == 2. So the next thing that happens is you zero out d[2].
Now assume i == 3 ...
So you zero out every element of the array the first time you see it, and if(d[i]==d[j]) never becomes true when i != j.
This can be fixed by changing the inner loop to
for (int j = i + 1; j < size; j++) {
This will output freq which is off by one, because this loop doesn't count the first element. Change freq = 0 to freq = 1 to fix that. I recommend having one place where you have freq = 1. A good place to place this assignment is just before the inner loop.
Note, I'm using spaces around operators and you should too. Cramped code is hard to read.
Here is a live demo of your program with all the aforementioned problems fixed. No other changes are made.
To build an histogram, you actually need to collect history.
Example:
int main() {
int size;
cin >> size;
int d[size];
int hist[size + 1]{}; // all zeroes - this is for the histogram
for (int i = 0; i < size; i++) { // To create array and store values in it
cin >> d[i];
}
for (int i = 0; i < size; i++) {
++hist[d[i]];
}
for(int i = 0; i < size; ++i) {
cout << "Frequency of number " << i << " is " << hist[i] << endl;
}
}
Note: VLAs (Variable Length Arrays) are not a standard C++ feature. Use std::vector instead.
A slightly different approach would be to not be limited by the size parameter when taking the input values. std::map the value to a count instead:
#include <iostream>
#include <vector>
#include <map>
int main() {
int size;
if(not (std::cin >> size) or size < 1) return 1;
std::map<int, unsigned long long> hist; // number to count map
for(int value; size-- > 0 && std::cin >> value;) {
++hist[value];
}
for(auto[value, count] : hist) {
std::cout << "Frequency of number " << value << " is " << count << '\n';
}
}
I've been assigned the, from what I've seen, fairly common problem when learning dynamic programming of having a nxm matrix of coins with a robot starting at the top left of the matrix [0,0] and trying to reach the bottom right of the matrix while picking up as many coins as possible. The robot is only allowed to move right and down. I have successfully been able to count the maximum number of coins that can be collected from the matrix, my code is below:
#include <iostream>
using namespace std;
int CoinCollection(int coinGrid[5][6])
{
int F[5][6] = {0};
F[0][0] = coinGrid[0][0];
for(int j = 1; j<6; j++)
{
F[0][j] = F[0][j-1]+coinGrid[0][j];
}
for(int i=1; i<5; i++)
{
F[i][0] = F[i-1][0] + coinGrid[i][0];
for(int j = 1; j<6; j++)
{
F[i][j] = max(F[i-1][j], F[i][j-1])+coinGrid[i][j];
}
}
return F[4][5];
}
string RobotPath(int coinGrid[5][6])
{
return "";
}
int main()
{
int grid[5][6] = {
{0,0,0,0,1,0},
{0,1,0,1,0,0},
{0,0,0,1,0,1},
{0,0,1,0,0,1},
{1,0,0,0,1,0} };
cout << "Max amount of coins collected is " << CoinCollection(grid);
cout << "\n\nRobot's path is" << RobotPath(grid);
}
The instructions I have say to hardcode the grid being used, so I don't have to change what I have to be flexible with inputs. The second part of the problem instructs to output the path that the robot should follow to reach the max number of coins (where the RobotPath method is). From the help I've received from my professor, I need to backtrack from the final solution to the beginning for this, but I'm at a loss for how to do this.
#include<iostream>
using namespace std;
int main(){
int n,d1,d2,d3;
cout<<"Enter a 3-digit positive integer"<<endl;
cin>>n;
d1=n/100;
d2=n%100/10;
d3=n%10;
int a[3]{d1,d2,d3};
for (int i = 0; i < 3; ++i) {
if(a[i]!=0){
a[i]=10-a[i];
}
cout<<"The new number is :"<<a[i]<<endl;
}
}
This code takes a 3-digit integer as input and returns a new number in which all non-zero digits in the original are replaced by the distance between the digit and 10, for example, if one of the digits is 2 so the new digit will be 10-2=8. But the problem is with the output.
I want the program to print (The new number is :(here the new digits in the same line)), instead of repeating the message and printing each digit in a separate line. How can I do that??
Thanks in advance.
This for loop,
for (int i = 0; i < 3; ++i) {
if(a[i]!=0){
a[i]=10-a[i];
}
cout<<"The new number is :"<<a[i]<<endl;
}
Is the issue for your problem. This means that your printing The new number is : on every iteration. What we need to do is, print it once and print all the integers after it. Its very simple, just change the position of the std::cout to be before the for loop and we can put in a little optimization; we dont need to store the 10 - a[i], we can directly print it.
cout << "The new number is : ";
for (int i = 0; i < 3; ++i) {
if(a[i] != 0) {
std::cout << (10 - a[i]);
}
}
Bonus: Try not to use using namespace std; as its a bad practice. Basically what it does is, it takes the whole std namespace and dumps it into the global namespace. If its for competitive programming and time is limited, then it would be okay but for general programming, avoid it.
u can print the information out from the for loop or u can do for loop like this
for (int i = 0; i < 3; ++i) {
if(a[i]!=0){
a[i]=10-a[i];
}
if(i == 0)
cout<<"The new number is :";
cout <<a[i];
}
cout << endl
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
My assignment is to have the user type in how many elements are in an array then enter integer number to be put in the array. I then have to sort through the array and find the largest number and print out the elements of the array but if there is a repeat then only print that number one time. I also have to print out the number of times each element in the array occurs. For example if the user types in that there is 5 elements then enters 2, 1, 2, -3, 2 then it should print -3 with 1 count, 1 with 1 count, and 2 with 3 count. So far I have it so it will print out the elements and delete the repeats but I cant get it to print out the correct number of occurrences for each element. This is my code so far.
void findRepeats(int numbers[], int num)
{
int instances = 0;
cout << "Number" << " " << "Occurrences" << endl;
for (int i = 0; i < num; i++)
{
bool matching = false;
instances = 1;
for (int j = 0; (j < i); j++)
{
if (numbers[i] == numbers[j])
{
instances++;
matching = true;
}
}
if (!matching)
cout << numbers[i] << " " << instances << endl;
}
}
Right now its saying all number occur only 1 time
One approach that you could take, is to sort the numbers first, before deciding how many duplicates there are. That way, it will be easier to avoid printing results for the same number more than once, and you also won't have to loop through the entire array for each number.
void findRepeats(int numbers[], int num);
int main(){
int array[] = {2, 1, 2, -3, 2};
findRepeats(array,5);
}
void findRepeats(int numbers[], int num) {
//sort the array first
std::sort(numbers, numbers + num);
int last = numbers[0];
int count = 0;
cout << "Number of Occurrences\n";
for (int i = 0; i < num; i++) {
if (last == numbers[i]) {
++count;
} else {
cout << last << " " << count << '\n';
count = 1;
}
last = numbers[i];
}
if (count > 0) {
cout << last << " " << count << '\n';
}
}
prints:
Number of Occurrences
-3 1
1 1
2 3
I would use map or unordered_map to, well..., map the integer to the number of it's occurrences. It makes things quite simple, as it basically takes care of the duplicates for you.
#include <iostream>
#include <unordered_map>
using namespace std;
void reportCounts(const int numbers[], const size_t size){
unordered_map<int, unsigned int> counts;
//unfortunately range-for here would a little PIA to apply
//or at least I don't know convenient way
for(size_t i = 0; i < size; ++i) {
counts [ numbers[i] ]++; //increase `count` of i-th number
}
//print results
for(auto count : counts ){
cout << count.first << ' ' << count.second << endl;
}
}
int main(){
int array[] = {2, 1, 2, -3, 2};
reportCounts(array,5);
}
Since it's an assignment I am leaving figuring out the c++ shenaningans to you and http://cppreference.com. Keywords are map, map::iterator and maybe associative container which map in an example of.
I do understand that it might be harder to understand than plain implementation of some algorithm, but this is probably close to optimal solution in modern c++, and putting effort into understanding how and why it works should prove beneficial. One should notice how much less of code had to be written, and no algorithm had to be invented. Less implementation time, less place to make mistakes, less testing.
Search your array. For every integer, either record it, or increment your count of it. Repeat process till done, then print it.
How? you say? One approach would be to use parallel arrays to store the unique integers found, and another to store the count of integers. Then print the unique integers and their counts.
Code example of simple search algorithm:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void print(vector<int> valueArray,vector<int> countArray){
for(unsigned int i = 0; i < valueArray.size(); ++i){
cout<<"Found value "<<valueArray[i]<<": "<<countArray[i]<<" times."<<endl;
}
}
void findRepeats(vector<int> testArray,vector<int> &valueArray,vector<int> &countArray){
for(unsigned int i = 0; i < testArray.size(); ++i){
if(valueArray.size() == 0){
valueArray.push_back(testArray[i]);
countArray.push_back(1);
}else{
bool newEntry = true;
for(unsigned int j = 0; j < valueArray.size(); ++j){
if(testArray[i] == valueArray [j]){
countArray[j]++;
newEntry = false;
break;//After find, break out of j-for-loop to save time.
}
}
if(newEntry){
valueArray.push_back(testArray[i]);
countArray.push_back(1);
}
}
}
}
int main(){
vector<int> testArray; //To store all integers entered.
vector<int> valueArray; //To store non-copied integers, dynamically, else handle it yourself.
vector<int> countArray; //To count increments of numbers found, dynamically, else handle it yourself.
testArray = {0,2,5,4,1,3,6,2,5,9,8,7,4,1,2,6,5,4,8,3,2,1,5,8,6,9,8,7,4,4,5,6,8,2,1,3,0,0,1,2,0,2,5,8};//Dummy data.
findRepeats(testArray,valueArray,countArray);//Function to find statistics on testArray.
cout<<"\nPrinting found characters, and number of times found: "<<endl;
print(valueArray,countArray);
return 0;
}
Output would be something like:
Printing found characters, and number of times found:
Found value 0: 4 times.
Found value 2: 7 times.
Found value 5: 6 times.
Found value 4: 5 times.
Found value 1: 5 times.
Found value 3: 3 times.
Found value 6: 4 times.
Found value 9: 2 times.
Found value 8: 6 times.
Found value 7: 2 times.
In the above, I used vectors for simplicity, but if you must do so with c-style arrays, one approach would be to create all three vectors the same size, and keep one integer counter for number of indices used in the valueArray and countArray; they should share, since they're related 1 to 1. And you will need to pass it to the findRepeats function as well.
Having arrays of the same size will ensure that your values and counts will fit in your array; this would happen if every number entered was unique.
I solved this problem but I got TLE Time Limit Exceed on online judge
the output of program is right but i think the way can be improved to be more efficient!
the problem :
Given n integer numbers, count the number of ways in which we can choose two elements such
that their absolute difference is less than 32.
In a more formal way, count the number of pairs (i, j) (1 ≤ i < j ≤ n) such that
|V[i] - V[j]| < 32. |X|
is the absolute value of X.
Input
The first line of input contains one integer T, the number of test cases (1 ≤ T ≤ 128).
Each test case begins with an integer n (1 ≤ n ≤ 10,000).
The next line contains n integers (1 ≤ V[i] ≤ 10,000).
Output
For each test case, print the number of pairs on a single line.
my code in c++ :
int main() {
int T,n,i,j,k,count;
int a[10000];
cin>>T;
for(k=0;k<T;k++)
{ count=0;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(i!=j)
{
if(abs(a[i]-a[j])<32)
count++;
}
}
}
cout<<count<<endl;
}
return 0;
}
I need help how can I solve it in more efficient algorithm ?
Despite my previous (silly) answer, there is no need to sort the data at all. Instead you should count the frequencies of the numbers.
Then all you need to do is keep track of the number of viable numbers to pair with, while iterating over the possible values. Sorry no c++ but java should be readable as well:
int solve (int[] numbers) {
int[] frequencies = new int[10001];
for (int i : numbers) frequencies[i]++;
int solution = 0;
int inRange = 0;
for (int i = 0; i < frequencies.length; i++) {
if (i > 32) inRange -= frequencies[i - 32];
solution += frequencies[i] * inRange;
solution += frequencies[i] * (frequencies[i] - 1) / 2;
inRange += frequencies[i];
}
return solution;
}
#include <bits/stdc++.h>
using namespace std;
int a[10010];
int N;
int search (int x){
int low = 0;
int high = N;
while (low < high)
{
int mid = (low+high)/2;
if (a[mid] >= x) high = mid;
else low = mid+1;
}
return low;
}
int main() {
cin >> N;
for (int i=0 ; i<N ; i++) cin >> a[i];
sort(a,a+N);
long long ans = 0;
for (int i=0 ; i<N ; i++)
{
int t = search(a[i]+32);
ans += (t -i - 1);
}
cout << ans << endl;
return 0;
}
You can sort the numbers, and then use a sliding window. Starting with the smallest number, populate a std::deque with the numbers so long as they are no larger than the smallest number + 31. Then in an outer loop for each number, update the sliding window and add the new size of the sliding window to the counter. Update of the sliding window can be performed in an inner loop, by first pop_front every number that is smaller than the current number of the outer loop, then push_back every number that is not larger than the current number of the outer loop + 31.
One faster solution would be to first sort the array, then iterate through the sorted array and for each element only visit the elements to the right of it until the difference exceeds 31.
Sorting can probably be done via count sort (since you have 1 ≤ V[i] ≤ 10,000). So you get linear time for the sorting part. It might not be necessary though (maybe quicksort suffices in order to get all the points).
Also, you can do a trick for the inner loop (the "going to the right of the current element" part). Keep in mind that if S[i+k]-S[i]<32, then S[i+k]-S[i+1]<32, where S is the sorted version of V. With this trick the whole algorithm turns linear.
This can be done constant number of passes over the data, and actually can be done without being affected by the value of the "interval" (in your case, 32).
This is done by populating an array where a[i] = a[i-1] + number_of_times_i_appears_in_the_data - informally, a[i] holds the total number of elements that are smaller/equals to i.
Code (for a single test case):
static int UPPER_LIMIT = 10001;
static int K = 32;
int frequencies[UPPER_LIMIT] = {0}; // O(U)
int n;
std::cin >> n;
for (int i = 0; i < n; i++) { // O(n)
int x;
std::cin >> x;
frequencies[x] += 1;
}
for (int i = 1; i < UPPER_LIMIT; i++) { // O(U)
frequencies[i] += frequencies[i-1];
}
int count = 0;
for (int i = 1; i < UPPER_LIMIT; i++) { // O(U)
int low_idx = std::max(i-32, 0);
int number_of_elements_with_value_i = frequencies[i] - frequencies[i-1];
if (number_of_elements_with_value_i == 0) continue;
int number_of_elements_with_value_K_close_to_i =
(frequencies[i-1] - frequencies[low_idx]);
std::cout << "i: " << i << " number_of_elements_with_value_i: " << number_of_elements_with_value_i << " number_of_elements_with_value_K_close_to_i: " << number_of_elements_with_value_K_close_to_i << std::endl;
count += number_of_elements_with_value_i * number_of_elements_with_value_K_close_to_i;
// Finally, add "duplicates" of i, this is basically sum of arithmetic
// progression with d=1, a0=0, n=number_of_elements_with_value_i
count += number_of_elements_with_value_i * (number_of_elements_with_value_i-1) /2;
}
std::cout << count;
Working full example on IDEone.
You can sort and then use break to end loop when ever the range goes out.
int main()
{
int t;
cin>>t;
while(t--){
int n,c=0;
cin>>n;
int ar[n];
for(int i=0;i<n;i++)
cin>>ar[i];
sort(ar,ar+n);
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(ar[j]-ar[i] < 32)
c++;
else
break;
}
}
cout<<c<<endl;
}
}
Or, you can use a hash array for the range and mark occurrence of each element and then loop around and check for each element i.e. if x = 32 - y is present or not.
A good approach here is to split the numbers into separate buckets:
constexpr int limit = 10000;
constexpr int diff = 32;
constexpr int bucket_num = (limit/diff)+1;
std::array<std::vector<int>,bucket_num> buckets;
cin>>n;
int number;
for(i=0;i<n;i++)
{
cin >> number;
buckets[number/diff].push_back(number%diff);
}
Obviously the numbers that are in the same bucket are close enough to each other to fit the requirement, so we can just count all the pairs:
int result = std::accumulate(buckets.begin(), buckets.end(), 0,
[](int s, vector<int>& v){ return s + (v.size()*(v.size()-1))/2; });
The numbers that are in non-adjacent buckets cannot form any acceptable pairs, so we can just ignore them.
This leaves the last corner case - adjacent buckets - which can be solved in many ways:
for(int i=0;i<bucket_num-1;i++)
if(buckets[i].size() && buckets[i+1].size())
result += adjacent_buckets(buckets[i], buckets[i+1]);
Personally I like the "occurrence frequency" approach on the one bucket scale, but there may be better options:
int adjacent_buckets(const vector<int>& bucket1, const vector<int>& bucket2)
{
std::array<int,diff> pairs{};
for(int number : bucket1)
{
for(int i=0;i<number;i++)
pairs[i]++;
}
return std::accumulate(bucket2.begin(), bucket2.end(), 0,
[&pairs](int s, int n){ return s + pairs[n]; });
}
This function first builds an array of "numbers from lower bucket that are close enough to i", and then sums the values from that array corresponding to the upper bucket numbers.
In general this approach has O(N) complexity, in the best case it will require pretty much only one pass, and overall should be fast enough.
Working Ideone example
This solution can be considered O(N) to process N input numbers and constant in time to process the input:
#include <iostream>
using namespace std;
void solve()
{
int a[10001] = {0}, N, n, X32 = 0, ret = 0;
cin >> N;
for (int i=0; i<N; ++i)
{
cin >> n;
a[n]++;
}
for (int i=0; i<10001; ++i)
{
if (i >= 32)
X32 -= a[i-32];
if (a[i])
{
ret += a[i] * X32;
ret += a[i] * (a[i]-1)/2;
X32 += a[i];
}
}
cout << ret << endl;
}
int main()
{
int T;
cin >> T;
for (int i=0 ; i<T ; i++)
solve();
}
run this code on ideone
Solution explanation: a[i] represents how many times i was in the input series.
Then you go over entire array and X32 keeps track of number of elements that's withing range from i. The only tricky part really is to calculate properly when some i is repeated multiple times: a[i] * (a[i]-1)/2. That's it.
You should start by sorting the input.
Then if your inner loop detects the distance grows above 32, you can break from it.
Thanks for everyone efforts and time to solve this problem.
I appreciated all Attempts to solve it.
After testing the answers on online judge I found the right and most efficient solution algorithm is Stef's Answer and AbdullahAhmedAbdelmonem's answer also pavel solution is right but it's exactly same as Stef solution in different language C++.
Stef's code got time execution 358 ms in codeforces online judge and accepted.
also AbdullahAhmedAbdelmonem's code got time execution 421 ms in codeforces online judge and accepted.
if they put detailed explanation to there algorithm the bounty will be to one of them.
you can try your solution and submit it to codeforces online judge at this link after choosing problem E. Time Limit Exceeded?
also I found a great algorithm solution and more understandable using frequency array and it's complexity O(n).
in this algorithm you only need to take specific range for each inserted element to the array which is:
begin = element - 32
end = element + 32
and then count number of pair in this range for each inserted element in the frequency array :
int main() {
int T,n,i,j,k,b,e,count;
int v[10000];
int freq[10001];
cin>>T;
for(k=0;k<T;k++)
{
count=0;
cin>>n;
for(i=1;i<=10000;i++)
{
freq[i]=0;
}
for(i=0;i<n;i++)
{
cin>>v[i];
}
for(i=0;i<n;i++)
{
count=count+freq[v[i]];
b=v[i]-31;
e=v[i]+31;
if(b<=0)
b=1;
if(e>10000)
e=10000;
for(j=b;j<=e;j++)
{
freq[j]++;
}
}
cout<<count<<endl;
}
return 0;
}
finally i think the best approach to solve this kind of problems to use frequency array and count number of pairs in specific range because it's time complexity is O(n).