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 }
  • 相关阅读:
    高程第五章(引用类型)
    第四章(变量、作用域、内存问题)
    label语句和break continue的使用(高程第三章)
    高级程序设计第三章
    max取得数组的最大值
    使用bind()扩充作用域
    函数
    数据类型、字符编码、文件处理
    Python入门
    8.8每日作业系列之循环模块运用
  • 原文地址:https://www.cnblogs.com/0424lrn/p/12227497.html
Copyright © 2011-2022 走看看