I need help in my code

#include
#include
#include<unordered_map>
using namespace std;
int main()
{
int n,target;
cin>>n;
long long a[n];
unordered_map<int,int>ans;
for(int i=0;i<n;i++)
{
cin>>a[i];
ans[a[i]]++;
}
cin>>target;
sort(a,a+n);
for(int i=0;i<n;i++)
{

	int x=target-a[i];
	if(ans[x]>0 && ans[a[i]]>0)
	{
		ans[x]--;
		ans[a[i]]--;
		if(a[i]<=x)
		cout<<a[i]<<" and "<<x<<endl;
		else
		cout<<x<<" and "<<a[i]<<endl;
	}
}
return 0;

}

for the third case it is giving wrong answer
please tell where i am making mistake in this code.

@officialharshit1996 hey,check this test case:
6
-3
1
4
3
6
8
9
your code is printing is
2 and 6
3 and 5
but it should be printing
1 and 8
3 and 6

it is printing the right answer.

please check again the code

@officialharshit1996 hey please check this functional code ,made it more efficient:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.