POJ 1552 Double(我的水题之路——二重循环正逆比较)

Doubles
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 15191   Accepted: 8618

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

Source

Mid-Central USA 2003

给一列数,问这列数中有多少对i,j,其中i=2*j

用个一个数组将这列随机数存储起来,然后判断其中两个是否有2倍的关系,有两种比较容易想到的方便方式。
1)先将这一列数组进行排序,然后用二重循环判断后面的是否为前面某一个的2倍。如代码1
2)不进行排序,直接比较,比较的时候,先比较j== i*2,后比较i==j*2,因为这个关系是不可逆的,所以可以直接用两个并列判断。但是如果在以后做题中,这种正逆比较的并列判断语句,必须考虑清楚,是否两个条件不可以互换。如,代码2
时间复杂度上来说,第一个做法,浪费的一个排序的时间复杂度,第二种做法,直接用的二重循环完成,显然第二种更好一些。

代码1(1AC):
#include <cstdio>
#include <cstdlib>
#include <algorithm>

using namespace std;

int list[25];

int main(void){
    int i, j, len;
    int sum;
    int num;

    while (scanf("%d", &num), num != -1){
        for (i = 0; num != 0; i++){
            list[i] = num;
            scanf("%d", &num);
        }
        len = i;
        sort(list, list + len);
        for (i = sum = 0; i < len; i++){
            for (j = i; j < len; j++){
                if (list[i] * 2 == list[j]){
                    sum++;
                }
            }
        }
        printf("%d\n", sum);
    }
    return 0;
}

代码2(1AC):
#include <cstdio>
#include <cstdlib>

int list[25];

int main(void){
    int i, j, len;
    int sum;
    int num;

    while (scanf("%d", &num), num != -1){
        for (i = 0; num != 0; i++){
            list[i] = num;
            scanf("%d", &num);
        }
        len = i;
        for (i = sum = 0; i < len; i++){
            for (j = i; j < len; j++){
                if (list[i] * 2 == list[j]){
                    sum++;
                }
                if (list[j] * 2 == list[i]){
                    sum++;
                }
            }
        }
        printf("%d\n", sum);
    }
    return 0;
}


你可能感兴趣的:(list,Integer,input,each,output,Numbers)