hdu1303(Doubles)二分查找类

Problem Description
As part of an arithmetic competency program, your students will be given randomly generated lists of from 2 to 15 unique positive integers and asked to determine how many items in each list are twice some other item in the same list. You will need a program to help you with the grading. This program should be able to scan the lists and output the correct answer for each one. For example, given the list
1 4 3 2 9 7 18 22
your program should answer 3, as 2 is twice 1, 4 is twice 2, and 18 is twice 9.
 
Input
The input file will consist of one or more lists of numbers. There will be one list of numbers per line. Each list will contain from 2 to 15 unique positive integers. No integer will be larger than 99. Each line will be terminated with the integer 0, which is not considered part of the list. A line with the single number -1 will mark the end of the file. The example input below shows 3 separate lists. Some lists may not contain any doubles.
 
Output
The output will consist of one line per input list, containing a count of the items that are double some other item.
 
Sample Input
1 4 3 2 9 7 18 22 0
2 4 8 10 0
7 5 11 13 1 3 0
-1
 
Sample Output
3
2
0
 
题意:这道题目是想要说明在一串数组中,例如:{1 4 3 2 9 7 18 22 0}中,2是1的2倍,4是2的2倍,18是9的2倍,所以这里就有3对2倍的数对{2,1}、{4,2}、{18,9};而{2 4 8 10 0}同理可得{2,4}、{4,8},所以输出2。
这道题中要注意的是为了节约循环次数,我们可以使用二分查找的方法,其关键代码如下:
int find(int a[],int len,int n)
{
    int l=0,r=len-1,mid;
    while(l<=r)
    {
        mid=(r+l)/2;
        if(a[mid]==n)
            return 1;
        else if(a[mid]<n)
            l=mid+1;
        else if(a[mid]>n)
            r=mid-1;
    }
    return 0;
}
此外还有2点要注意的是:
1、多组输入,直到某一组的第一个数为-1时,结束程序。
2、每一组的最后一个数字为0,用0来标志结束。
 
AC代码如下:
#include<string.h>
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int find(int a[],int len,int n)
{
    int l=0,r=len-1,mid;
    while(l<=r)
    {
        mid=(r+l)/2;
        if(a[mid]==n)
            return 1;
        else if(a[mid]<n)
            l=mid+1;
        else if(a[mid]>n)
            r=mid-1;
    }
    return 0;
}
int main()
{
    int t,sum,i,j,k;
    while(scanf("%d",&t)!=EOF&&t!=-1)
    {
        i=0;
        int num[20001]={0};
        num[i++]=t;
        while(scanf("%d",&t)&&t)
        {
            num[i++]=t;
        }
        sort(num,num+i);
        sum=0;
        for(j=0;j<i;j++)
            sum+=find(num,i,2*num[j]);
        printf("%d\n",sum);
        i=0;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LSRzsy/p/10085201.html