哈理工OJ 1710 a + b = c(尺取法)

题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1710

a + b = c
Time Limit: 2000 MS Memory Limit: 65536 K
Total Submit: 307(108 users) Total Accepted: 100(82 users) Rating: Special Judge: No
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

【思路分析】首先暴力求的话n*n*n是超时的,所以我们就得换个思路,如果可以降一层for的话时间复杂度是完全足够的。所以我们先对序列进行排序,然后用尺取法去解这道题。
【AC代码】

#include<cstdio>
#include<cstring>
#include<map>
#include<cmath>
#include<algorithm>
using namespace std;

int a[5005],b[5005],c[5005];
int n1,n2,n3;
int main()
{
    while(~scanf("%d",&n1))
    {
        for(int i=1;i<=n1;i++)
        {
            scanf("%d",&a[i]);
        }
        scanf("%d",&n2);
        for(int i=1;i<=n2;i++)
        {
            scanf("%d",&b[i]);
        }
        scanf("%d",&n3);
        for(int i=1;i<=n3;i++)
        {
            scanf("%d",&c[i]);
        }
        int sum=0;
        sort(a+1,a+1+n1);
        sort(b+1,b+1+n2);
        for(int i=1;i<=n3;i++)
        {
            for(int j=1,k=n2;j<=n1&&k>=1;)
            {
                if(a[j]+b[k]>c[i])
                {
                    k--;
                }
                else if(a[j]+b[k]==c[i])
                {
                    sum++;
                    j++;
                    k--;
                }
                else
                {
                    j++;
                }
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值