《算法竞赛入门经典》第三章思考题

来源:互联网 发布:nginx alias用法 编辑:程序博客网 时间:2024/05/17 21:10

题目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 + 10int 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);}
1 0
原创粉丝点击