zoukankan      html  css  js  c++  java
  • 二分-B

    B - Dating with girls(1)

    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.

    Outpu

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

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 
     5 int main(){
     6     int T;
     7     scanf("%d",&T);
     8     while(T--){
     9         int n,k,a[100010],cnt=0;
    10         scanf("%d %d", &n, &k);
    11         for(int i=0;i<n;i++)
    12             scanf("%d", a+i);
    13         sort(a,a+n);
    14         for(int i=0; i<n; i++){
    15             int left = 0, right= n-1;
    16             while(right > left){
    17                 int mid = (left + right)/2;
    18                 if(a[i] + a[mid] > k)     right = mid-1;
    19                 else if(a[i] + a[mid] < k)    left = mid+1;
    20                 else{
    21                     left = mid;
    22                     break;
    23                 }
    24             }
    25             if(a[i]+a[left]==k){
    26                 cnt++;
    27                 if(i!=0&&a[i]==a[i-1])    cnt--;
    28             }
    29         }
    30         printf("%d
    ",cnt);
    31     }
    32 }
  • 相关阅读:
    C++ 模板实现约瑟夫环
    C++实现向文件输出对象并读取对象
    C++实现对本地文件加行号并输出到本地文件
    C++ vector动态容量变化
    C++纯虚函数应用实例
    华为2016研发工程师-删数字
    iOS-宫格拼图
    iOS-审核4.3入坑(已出坑)
    Mac-关闭Mac电脑启动声音(咚~)
    彻底完全卸载SQL Server 2005教程
  • 原文地址:https://www.cnblogs.com/0424lrn/p/12227497.html
Copyright © 2011-2022 走看看