a + b + c=0
Description
There is a sequence A containing n integers.
How many combinations can make a + b + c = 0 (a∈A, b∈A, c∈A).
Input
There are multiple test cases. The first line is an positive integer T standing for the number of test cases.
For each test case, the first line is one integer n.
The second line are n integers a1, a2, ..., an, separated by space.
(1<=n<=5000,|ai|<=100 000 000)
Output
For each test case, output all the combination satisfied a + b + c=0, by lexicographical order.
If there doesn't exit, output "<empty>" in one line.
Output a blank line after each test case.
Sample Input
2
6
-1 0 1 2 -1 -4
6
1513 5031 5031 -1582 4769 10
Sample Output
-1 -1 2
-1 0 1
<empty>
题意:给你n个数,输出所有和为0的三个数(去重,按字典序,末尾多一个空格)。
题解:肯定先sort一遍,枚举每个点,双指针指向后一个和最后一个,判断,移动指针。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a[5005];
int n,m;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
sort(a+1,a+n+1);
int flag=0;
for(int i=1,j,k; i<n-1;)
{
k=i+1;
j=n;
while(k<j)
{
if(a[i]+a[k]+a[j]==0)
{
printf("%d %d %d\n",a[i],a[k],a[j]);
flag=1;
while(a[k]==a[k+1])k++;k++;
while(a[j]==a[j-1])j--;j--;
}
else if(a[i]+a[k]+a[j]>0)
{
j--;
}
else if(a[i]+a[k]+a[j]<0)
{
k++;
}
}
while(a[i]==a[i+1])i++;
i++;
}
if(!flag)
printf("<empty>\n");
printf("\n");
}
}