HDOJ 2578 Dating with girls(1)

来源:互联网 发布:淘宝如何申请分销 编辑:程序博客网 时间:2024/05/22 13:59

Dating with girls(1)

Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4218    Accepted Submission(s): 1317


Problem 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
25 41 2 3 4 58 81 4 5 7 8 9 2 6
 

Sample Output
35
 


题意给出n和k,还有n个数。就是n个数中 找出两个数x,y。使得 x+y=k。

计算所有的可能。当x0+y0=k。x1+y1=k 。 必须有不相等的。 x0!=x1 or y0!=y1。

例如

4 4

2 2 2 2

正确输出应该是 1 。

所以一定要去重

#include <cstdio>#include <algorithm>using namespace std;const int maxn = 100000 + 10;long long a[maxn], b[maxn], k;int n, cnt;int binary_search(int kk){    int fir = 0, las = cnt - 1;    while (fir <= las){        int middle = (fir + las) / 2;        if (a[middle] == kk)            return 1;        else if (a[middle] < kk)            fir = middle + 1;        else            las = middle - 1;    }    return 0;}int main(){    int t;    int ans;    scanf("%d", &t);    while (t--){        ans = 0;        scanf("%d%I64d", &n, &k);        for (int i = 0; i < n; i++){            scanf("%I64d", &a[i]);        }        sort(a, a + n);        cnt = unique(a, a + n) - a;   //unique函数为去重        for (int i = 0; i < cnt; i++){            b[i] = k - a[i];           // if (binary_search(b[i]) && a[i] != b[i])               // ans = ans + 2;           // else if (binary_search(b[i]) && a[i] == b[i])               // ans = ans + 1;            if (binary_search(b[i]))                ans = ans + 1;        }        printf("%d\n", ans);    }    return 0;}


0 0