1. 程式人生 > >hdu1303(Doubles)二分查詢類

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;
}