二分查找

哈理工oj(1710):
Description

有A、 B、 C 三个集合的,其中a∈A, b ∈ B, c ∈ C,求有多少种方式使得a + b = c。
Input

有多组测试数据,请处理到文件结束。

对于每组测试数据,有三行:

第一行为A集合的描述,第一个数为n,表示A集合有n个数,接下来有n个整数a1~an。

第二行为B集合,第三行为C集合,表示含义参考第一行。

每个集合中的数两两不相等。
1<=n<=5000,|ai| <= 1 000 000 000
Output

对于每组测试数据,输出一行,包含一个整数,表示有多少种组合方式。
Sample Input

3 -10 4 -6
3 -10 3 -1
3 3 -4 -6
3 -8 -9 -4
3 9 -10 2
3 -8 -7 5
3 -4 -6 -2
3 9 -9 -2
3 3 -13 -4

Sample Output

2
2
3

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<deque>
using namespace std;
int a[5001],b[5001],c[5001];
int main()
{
    int n1;
    while(~scanf("%d",&n1))
    {

        int n2,n3;
        for(int i=1;i<=n1;i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a+1,a+n1+1);
        scanf("%d",&n2);
        for(int i=1;i<=n2;i++)
        {
            scanf("%d",&b[i]);
        }
        sort(b+1,b+n2+1);
        scanf("%d",&n3);
        for(int i=1;i<=n3;i++)
        {
            scanf("%d",&c[i]);
        }
        sort(c+1,c+n3+1);

        int sum=0;

        for(int i=1;i<=n3;i++)
        {
            int ri=n1,le=1;
            while(ri>0&&le<=n2)
            {
                if(a[ri]+b[le]==c[i])
                {
                    ri--;
                    le++;
                    sum++;

                }
                else if(a[ri]+b[le]<c[i])
                {
                    le++;
                }
                else ri--;
            }
        }
        printf("%d\n",sum);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值