Sequence
Time Limit: 500msMemory Limit: 65536KB 64-bit integer IO format: %lld Java class name: Main
Prev Submit Status Statistics Next
袁学长又来啦,这次他有一个长度为n的数列a1 a2 … an,他想知道能否在这个数列中找到三个数使它们的和为零,如果有,那么有多少种可能的情况呢?
Input
输入首先是一个正整数t( t ≤ 10),表示t个测试实例。每个测试实例第一行输入一个正整数n(3 ≤ n ≤ 1000),表示数列中有n个数,第二行包含n个数ai(-1×106 ≤ ai ≤ 1×106)。
Output
对于每个测试实例,输出总共有多少可能情况,每个实例的输出占一行。
Sample Input
3
3
1 2 3
6
1 -1 2 -2 3 -3
5
0 2 -2 3 -3
Sample Output
0
2
2
Author
//w点多ans++那里写一个break;
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[10011];
int solve(int low,int high,int x)
{
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]>x)
high=mid-1;
else if(a[mid]<x)
low=mid+1;
else
return 1;
}
return 0;
}
int main()
{
int n,i,t,j;
while(~scanf("%d",&t))
{
while(t--)
{
int ans=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",a+i);
sort(a,a+n);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
int tmp=-1*(a[i]+a[j]);
if(solve(j+1,n-1,tmp))
{
ans++;
}
}
}
printf("%d\n",ans);
}
}
return 0;
}