forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_Sum._ashish4321.cpp
More file actions
57 lines (54 loc) · 795 Bytes
/
2_Sum._ashish4321.cpp
File metadata and controls
57 lines (54 loc) · 795 Bytes
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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node
{
ll val;
ll pos;
};
bool cmp(node a, node b)
{
return (a.val<b.val);
}
int main(void)
{
// Input number of elements of array
ll n;
cin>>n;
// Initialize the struct for n elements
node nums[n];
ll a;
for(ll i=0;i<n;i++)
{
cin>>a;
nums[i].val=a;
nums[i].pos=i;
}
// sort the struct according to val
sort(nums,nums+n,cmp);
// Input target sum required
ll target;
cin>>target;
// To find two indices of array whose sum is target
ll low=0;
ll high=n-1;
ll sum=INT_MIN;
while(sum!=target)
{
sum=(nums[low].val+nums[high].val);
if(sum>target)
{
high--;
}
else if(sum<target)
{
low++;
}
else
{
break;
}
}
cout<<nums[low].pos<<" "<<nums[high].pos;
return 0;
}