Points:
900
Time limit:
1.0s
Memory limit:
512M
Input:
stdin
Output:
stdout
You are given an array of \(n\) integers, and your task is to find two values (at distinct positions) whose sum is \(x\).
Input
- The first input line has two integers \(n\) and \(x\): the array size and the target sum.
- The second line has \(n\) integers \(a_1,a_2,\ldots,a_n\): the array values.
Output
- Print two integers: the positions of the values. If there are several solutions, you may print any of them. If there are no solutions, print
IMPOSSIBLE
.
Constraints
- \(1 \leq n \leq 2\cdot 10^5\)
- \(1 \leq x,a_i \leq 10^9\)
Example
Sample input
4 8
2 7 5 1
Sample output
2 4
Comments
using namespace std;
ll n,x;
pii a[200001];
int search(ll l,ll r, ll x)
{
ll ans=-1;
while (l<=r)
{
ll mid=(l+r) / 2;
if (a[mid].first==x)
{
ans=mid;
return ans;
}
if (a[mid].first>x) r=mid-1; else l=mid+1;
}
return ans;
}
int main()
{
cin>>n>>x;
for(int i=1;i<=n;i++)
{
cin>>a[i].first;
a[i].second=i;
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
ll k=x-a[i].first;
ll vt=search(1,n,k);
if (vt!=-1 && a[i].first+a[vt].first==x && a[i].second!=a[vt].second)
{
if (a[i].second<a[vt].second) cout<<a[i].second<<" "<<a[vt].second; else cout<<a[vt].second<<" "<<a[i].second;
return 0;
}
}
cout<<"IMPOSSIBLE";
}
bài này chỉ cần dùng chặt nhị phân với dùng kiểu pair là ra r:))
mình gửi code của mình mn tham khảo:)))
include <bits/stdc++.h>
define ll long long
define pii pair <ll,ll>
using namespace std;
ll n,x;
pii a[200001];
int search(ll l,ll r, ll x)
{
ll ans=-1;
while (l<=r)
{
ll mid=(l+r) / 2;
if (a[mid].first==x)
{
ans=mid;
return ans;
}
if (a[mid].first>x) r=mid-1; else l=mid+1;
}
return ans;
}
int main()
{
cin>>n>>x;
for(int i=1;i<=n;i++)
{
cin>>a[i].first;
a[i].second=i;
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
ll k=x-a[i].first;
ll vt=search(1,n,k);
if (vt!=-1 && a[i].first+a[vt].first==x && a[i].second!=a[vt].second)
{
if (a[i].second<a[vt].second) cout<<a[i].second<<" "<<a[vt].second; else cout<<a[vt].second<<" "<<a[i].second;
return 0;
}
}
cout<<"IMPOSSIBLE";
}
This comment is hidden due to too much negative feedback. Click here to view it.
This comment is hidden due to too much negative feedback. Click here to view it.