Hrbust OJ 1734 a + b + c=0(双指针法)



                                                                      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");
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值