1. 程式人生 > >《演算法競賽入門經典》第三章思考題

《演算法競賽入門經典》第三章思考題

題目1(必要的儲存量)

陣列可以用來儲存很多資料,但在一些情況下,並不需要把資料儲存下來。下面哪些題目可以不借助陣列,哪些必須藉助陣列?請程式設計實現。假設輸入只能讀一遍。
1. 輸入一些數,統計個數。
2. 輸入一些數,求最大值、最小值和平均數。
3. 輸入一些數,哪兩個數最接近。
4. 輸入一些數,求第二大的值。
5. 輸入一些數,求它們的方差。
6. 輸入一些數,統計不超過平均數的個數。

程式碼如下:

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

void count() // 1題
{
    int n, ct = 0
; while(1 == scanf("%d", &n)) ++ct; printf("You've inputted %d numbers\n", ct); } void maxMinAverage() // 2題 { int n, max, min, sum = 0, ct = 0, first = 1; while(1 == scanf("%d", &n)) { if(first) { max = min = n; first = 0; } if(max < n) max = n; if
(n < min) min = n; sum += n; ++ct; } printf("max:%d min:%d average:%.3f\n", max, min, sum*1.0/ct); } void nearest() // 3題 { int nums[100], i = 0, j, k; while(1 == scanf("%d", &nums[i])) ++i; printf("%d\n", i); int a = nums[0], b = nums[1], distance = abs
(nums[0]-nums[1]); for(j = 0; j < i - 1; ++j) for(k = j + 1; k < i; ++k) if(abs(nums[j]-nums[k]) < distance) { distance = abs(nums[j]-nums[k]); a = nums[j]; b = nums[k]; } printf("two nearest numbers: %d %d, distance: %d\n", a, b, distance); } void second() // 4題 { int max, second, n; scanf("%d%d", &max, &second); int t1 = max > second ? max : second; int t2 = max < second ? max : second; max = t1; second = t2; //printf("max:%d second:%d\n", max, second); while(1 == scanf("%d", &n)) { if(n > max) { second = max; max = n; continue; } if(n > second && n != max) second = n; } printf("max:%d second:%d\n", max, second); } void variance() // 5題 { int nums[100]; int ct = 0, n, i; double ave = 0.0, sum = 0.0, psum = 0.0; while(1 == scanf("%d", &n)) { nums[ct++] = n; sum += n; } ave = sum / ct; for(i = 0; i < ct; ++i) psum += (nums[i] - ave) * (nums[i] - ave); printf("variance: %.3f\n", psum / ct); } void smallerThanAve() // 6題 { int nums[100]; int ct = 0, sct = 0, n, i; double ave = 0.0, sum = 0.0; while(1 == scanf("%d", &n)) { nums[ct++] = n; sum += n; } ave = sum / ct; for(i = 0; i < ct; ++i) if(nums[i] < ave) ++sct; printf("%d numbers smaller than average %f\n", sct, ave); } int main() { //count(); //maxMinAverage(); //nearest(); //second(); //variance(); //smallerThanAve(); return 0; }

題目2(統計字元1的個數):

下面的程式意圖在於統計字串中字元1的個數,可惜有瑕疵:

#include<stdio.h>
#define maxn 10000000 + 10
int main()
{
    char s[maxn];
    scanf("%s", s);
    int tot = 0;
    for(int i = 0; i < strlen(s); i++)
        if(s[i] == 1) tot++;
    printf("%d\n", tot);
}

該程式至少有3個問題,其中一個導致程式無法執行,另一個導致結果不正確,還有一個導致效率低下。你能找到它們並改正嗎?

答案:

#include <stdio.h>

int main()
{
    int tot = 0;
    char ch;
    while((ch = getchar()) != EOF)
        if(ch == '1') ++tot;
    printf("%d\n", tot);
}