-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimal2sum.cpp
More file actions
60 lines (58 loc) · 1.35 KB
/
optimal2sum.cpp
File metadata and controls
60 lines (58 loc) · 1.35 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
#include <bits/stdc++.h>
using namespace std;
string exists(vector<int>&a, int target){
int n = a.size();
vector<pair<int, int>> nwi;
for(int i = 0; i<n; i++){
nwi.push_back({a[i], i});
}
sort(nwi.begin(), nwi.end());
int left = 0, right = n-1;
while(left<right){
int sum = nwi[left].first + nwi[right].first;
if(sum == target){
return "YES";
}
else if(sum < target){
left++;
}
else{
right--;
}
}
return "NO";
}
vector<int>indices(vector<int>&a, int target){
int n = a.size();
vector<pair<int, int>> nwi;
for(int i = 0; i<n; i++){
nwi.push_back({a[i], i});
}
sort(nwi.begin(), nwi.end());
int left = 0, right = n-1;
while(left<right){
int sum = nwi[left].first + nwi[right].first;
if(sum == target){
return {nwi[left].second, nwi[right].second};
}
else if(sum < target){
left++;
}
else{
right--;
}
}
return {-1, -1};
}
int main(){
int n, target;
cin >> n >> target;
vector<int>a(n);
for(int i = 0; i<n; i++){
cin >> a[i];
}
cout << exists(a, target) << endl;
vector<int> res = indices(a, target);
cout << "[ " << res[0] << ", " << res[1] << " ]" << endl;
return 0;
}