Dating with girls(1)

此博客讨论了一个关于在给定整数集合中寻找满足特定条件配对的问题,即找到一对数字使得它们之和等于给定的目标值,并且考虑到了整数的顺序差异和重复值的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Everyone in the HDU knows that the number of boys is larger than the number of girls. But now, every boy wants to date with pretty girls. The girls like to date with the boys with higher IQ. In order to test the boys ' IQ, The girls make a problem, and the boys who can solve the problem 
correctly and cost less time can date with them.
The problem is that : give you n positive integers and an integer k. You need to calculate how many different solutions the equation x + y = k has . x and y must be among the given n integers. Two solutions are different if x0 != x1 or y0 != y1.
Now smart Acmers, solving the problem as soon as possible. So you can dating with pretty girls. How wonderful!
 

Input

The first line contain an integer T. Then T cases followed. Each case begins with two integers n(2 <= n <= 100000) , k(0 <= k < 2^31). And then the next line contain n integers.
 

Output

For each cases,output the numbers of solutions to the equation.
 

Sample Input

2 5 4 1 2 3 4 5 8 8 1 4 5 7 8 9 2 6
 

Sample Output

3 5
 

解题思路:

题目大意是给定一组数,让你选定两个数,使之相加等于k。选择的数字可以重复使用,选的数字顺序不同记为两种情况。让你求出所有的情况。先对这组数进行排序,然后遍历一遍进行折半查找即可。题目易出错的地方在于给的数字可能是重复的,需要去重处理。我其实把代码编的复杂了,完全可以查找的时候如果这组数出现的数字重复就跳过该数。而我用了vector进行去重处理,真是no zuo no die 啊。。。。。给的代码有多处还可以进行优化。。。。

AC代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 100005;
int main()
{
    int t, n, k;

    scanf("%d", &t);
    while(t--)
    {
        vector<int> a;
        __int64 ans = 0;
        int b;
        bool flag = false;
        scanf("%d%d", &n, &k);
        for(int i = 0; i < n; i++)
        {
            scanf("%d", &b);
            a.push_back(b);
            if(2 * b == k)
                flag = true;
        }
        sort(a.begin(), a.end());
        vector<int> :: iterator it = unique(a.begin(), a.end());  // 傻乎乎的进行了去重处理。。。。
        a.erase(it, a.end());
        for(int i = 0; i < a.end() - a.begin(); i++)
        {
            int low = i, high = a.end() - a.begin() - 1, mid;
            if(a[i] >= k)
                break;
            while(high >= low)
            {
                mid = (high + low) / 2;
                if(a[i] + a[mid] > k)
                    high = mid - 1;
                if(a[i] + a[mid] < k)
                    low = mid + 1;
                if(a[i] + a[mid] == k)
                {
                    ans++;
                    break;
                }
            }
        }
        if(flag)
            printf("%I64d\n", ans * 2 - 1);
        else
            printf("%I64d\n", ans * 2);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值