PAT B1038 统计同成绩学生超时问题

输入格式:

输入在第 1 行给出不超过 105​​ 的正整数 N,即学生总人数。随后一行给出 N 名学生的百分制整数成绩,中间以空格分隔。最后一行给出要查询的分数个数 K(不超过 N 的正整数),随后是 K 个分数,中间以空格分隔。

输出格式:

在一行中按查询顺序给出得分等于指定分数的学生人数,中间以空格分隔,但行末不得有多余空格。

输入样例:

10
60 75 90 55 75 99 82 90 75 50
3 75 90 88

输出样例:

3 2 0


  这道题的思路还是比较简单直接的。用一维数组的下标作为成绩来统计相应成绩学生的个数。
我的代码如下:
#include <iostream>

using namespace std;

int main()
{
    int studentCnt,tempScore;
    int findCnt,tempNum;
    int scoreCnt[101]={0};//初始化数组
    cin >> studentCnt;
    for(int i=0; i<studentCnt; ++i)
    {
        cin >> tempScore;
        scoreCnt[tempScore] ++;//统计每个成绩学生的个数
    }
    cin >> findCnt;
    bool symbolFlag = false;
    for(int i=0; i<findCnt; ++i)
    {
        cin >> tempNum;
        if(symbolFlag)
            cout << " ";
        else
            symbolFlag = true;
        cout << scoreCnt[tempNum];//输出要查询成绩对应的学生个数
    }
    return 0;
}
不过提交发现,测试点3出现超时问题。时间复杂度主要在于for循环中的代码。
于是我把cin和cout用scanf和sprintf进行替换,再次提交,成功通过。
更详细原因可参考博文:https://blog.csdn.net/qq1169091731/article/details/51926460

总之,在OJ上做题尽量使用scanf和printf,尤其是有大量数据需要输入输出时。

替换后代码:
#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    int studentCnt,tempScore;
    int findCnt,tempNum;
    int scoreCnt[101]={0};
    scanf("%d",&studentCnt);
    for(int i=0; i<studentCnt; ++i)
    {
        scanf("%d",&tempScore);
        scoreCnt[tempScore] ++;
    }
    scanf("%d",&findCnt);
    bool symbolFlag = false;
    for(int i=0; i<findCnt; ++i)
    {
        scanf("%d",&tempNum);
        if(symbolFlag)
            printf(" ");
        else
            symbolFlag = true;
        printf("%d",scoreCnt[tempNum]);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/codewars/p/10353213.html