-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathPairsuminarray.cpp
More file actions
71 lines (59 loc) · 1.12 KB
/
Pairsuminarray.cpp
File metadata and controls
71 lines (59 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <algorithm>
int pairSum(int *arr, int n, int num)
{
int count=0;
sort(arr, arr+n);
int i=0, j=n-1;
while(i < j){
if(arr[i] + arr[j] == num)
{
if(arr[i] == arr[j])
{
count += (j-i+1)*(j-i)/2;
return count;
}
int countI=0, countJ=0, l=i, k=j;
while(arr[i] == arr[l]){
l++;
countI++;
}
while(arr[j] == arr[k]){
k--;
countJ++;
}
count += countI*countJ;
i = l, j = k;
}
else if(arr[i] + arr[j] < num)
{
i++;
}
else
{
j--;
}
}
return count;
}
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
int x;
cin >> size;
int *input = new int[size];
for (int i = 0; i < size; i++)
{
cin >> input[i];
}
cin >> x;
cout << pairSum(input, size, x) << endl;
delete[] input;
}
return 0;
}