1030. 完美数列(25)

原题: https://www.patest.cn/contests/pat-b-practise/1030

测试用例:

// 正常测试
10 8
2 3 20 4 5 1 6 7 8 9
output: 8

// 最小值不是第一项
10 8
2 3 15 4 5 1 6 7 8 9
output: 9

// 最大值重复
10 8
2 3 20 4 5 1 6 7 8 8
output: 9

// 全部都比 min*p 小
10 8
1 2 2 2 5 5 5 5 5 7
output: 10

思路: 首先题意不能理解错, 最小值不一定是排序后, 第一项.
其次要考虑, 全部数列都能用上的情况, 以及最大值并列的情况, 核心代码不超过10行, 大家仔细
分析下.

完整实现:

#include <stdio.h>
#include <stdlib.h>

int compare (const void *a, const void *b);
int main(void) {
    long int p;          // 给定的参数
    long int max;        // 当前所选数列的最大值
    long int min;        // 当前数列的最小值, 不一定用数列的第一项
    long int number = 0; // 最大数列长度
    long int count = 0;  // 计数器
    long int n;
    long int i;
    long int j;
    scanf("%ld %ld", &n, &p);
    long int arr[n];
    
    for (i=0; i<n; i++) {
        scanf("%ld", &arr[i]);
    }
    qsort(arr, n, sizeof(long int), compare);
    // 接下来的双层循环是解本题的核心代码
    for(i=0; i<n; i++) {
        min = arr[i];
        max = min * p;
        for(j=count; j<n; j++) {
            if(arr[j] > max) break;
            // 这种写法自动整合所有数据都小于max的情况
            if(j - i >= number) number = j - i + 1;
        }
        count = j;
        if (count > n) break;
    }
    printf("%ld\n", number);
    // printf("%ld\n", count);
    return 0;
}

// 从小到大排序
int compare (const void *a, const void *b) {
    long int arg1 = *(long int*)a;
    long int arg2 = *(long int*)b;
    return arg1 - arg2;
}

参考: http://www.cnblogs.com/lolybj/p/6202458.html

posted @ 2017-11-12 21:56  阿胜4K  阅读(308)  评论(0编辑  收藏  举报