1 条题解

  • 0
    @ 2026-10-23 18:35:46

    P76046 数组统计报告 — 题解

    专题: 函数
    适用题目: 新生 OJ 本地题包中的 P76046,不要直接用于外站同名题。

    解题思路

    将求和、最大值、偶数计数封装成三个函数,每个函数接收数组和长度。

    复杂度

    时间 O(n)O(n),空间 O(n)O(n)。

    易错点

    C 数组形参接收指针,仍需单独传长度;总和用 long long。

    C11 参考程序

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include <limits.h>
    
    long long array_sum(const int *a,int n){long long s=0;for(int i=0;i<n;i++)s+=a[i];return s;}
    int array_max(const int *a,int n){int mx=a[0];for(int i=1;i<n;i++)if(a[i]>mx)mx=a[i];return mx;}
    int count_even(const int *a,int n){int c=0;for(int i=0;i<n;i++)c+=a[i]%2==0;return c;}
    int main(void) {
        int n;scanf("%d",&n);int *a=malloc(n*sizeof(int));
        for(int i=0;i<n;i++)scanf("%d",&a[i]);
        printf("%lld %d %d\n",array_sum(a,n),array_max(a,n),count_even(a,n));
        free(a);return 0;
    }
    

    C++17 参考程序

    #include <bits/stdc++.h>
    using namespace std;
    
    long long array_sum(const vector<int> &a) {
        long long s = 0;
        for (int x : a) s += x;
        return s;
    }
    int array_max(const vector<int> &a) {
        return *max_element(a.begin(), a.end());
    }
    int count_even(const vector<int> &a) {
        int count = 0;
        for (int x : a) if (x % 2 == 0) count++;
        return count;
    }
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n; cin >> n;
        vector<int> a(n);
        for (int &x : a) cin >> x;
        cout << array_sum(a) << ' ' << array_max(a) << ' ' << count_even(a) << '\n';
        return 0;
    }
    

    题解建议设置为训练结束后开放。普通判题无法验证是否实际使用指定函数或 STL。

    • 1

    信息

    ID
    1815
    时间
    2000ms
    内存
    256MiB
    难度
    2
    标签
    提交数
    0
    已通过
    0
    上传者