从PAT甲级1047题说开去

原题:https://www.patest.cn/contests/pat-a-practise/1047
题意大概就是说,给定学生的id和该生选修的课程id,要根据课程id从大到小的顺序把选修这门课的学生打印出来,打印的时候学生依照字母表顺序打印。

我一看,25分题,说明是略有难度的,但是直觉上这题并不复杂,然后查了一下大神们的答案,比如:http://blog.csdn.net/sunbaigui/article/details/8656971
大部分都选择不使用字符串而是选择char类型的数组存放字符串,因为遇到了超时的问题。研读代码后发现,他们以课程为单位进行排序,也就是说,每处理一门课程就要进行一次排序。我认为可以直接对所有的学生先进行排序,建立一个课程数*学生数的表格,类型为bool,表示该课程是否有学生修读,然后依次输出。

我的方案是:先一次性读完所有的字符串,然后直接排序,之后再逐行将排序过的字符串送到流中,再读一遍,将定义的课程数*学生数表格中相应位置为1,然后输出。思路很简单,在自己的VS里也运行成功了,但是上传后告诉我段错误。我表示???

后来从这个bbs上找到了答案:http://bbs.csdn.net/topics/260036862/
是由于我在函数内定义的数组太大了,导致堆栈溢出,方法包括定义全局变量和定义动态数组。两个方法都尝试了一遍,结果告诉我内存溢出了。
定义动态数组的方法:http://blog.csdn.net/kangroger/article/details/37773929

其实仔细想来,也不一定不会超时,定义大数组解决问题也不是良好的编程习惯,还是老老实实按照大神们的做法弄吧。

以下是最后一个测试点内存溢出的代码,我个人认为流处理动态数组还是在做题时挺好用的东西。

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
using namespace std;

const int MAX_COURSE = 2501;
const int MAX_STUDENT = 40000;

int main()
{
    vector<string> all_data;
    int stu_num, cou_num; cin >> stu_num >> cou_num;
    int row = cou_num+1, col = stu_num;
    bool **course_student_flag = new bool*[row];
    for (int i = 0; i<row; i++)
        course_student_flag[i] = new bool[col];
    for (int i = 0; i<cou_num; ++i)
    {
        for (int j = 0; j<stu_num; ++j)
            course_student_flag[i][j] = false;
    }
    int course_student_num[MAX_COURSE] = { 0 };

    getchar();
    for (int i = 0; i < stu_num; ++i)
    {
        string temp; getline(cin, temp);
        all_data.push_back(temp);
    }
    sort(all_data.begin(), all_data.end());
    for (int i = 0; i < stu_num; ++i)
    {
        stringstream ss(all_data[i]);
        string temp;
        int single_num;
        int course_id;
        ss >> temp >> single_num;
        for (int j = 0; j < single_num; ++j)
        {
            ss >> course_id;
            course_student_flag[course_id][i]=true;
            ++course_student_num[course_id];
        }
    }
    for (int i = 1; i <= cou_num; ++i)
    {
        cout << i << " " << course_student_num[i] << endl;
        for (int j = 0; j < stu_num; ++j)
        {
            if (course_student_flag[i][j] != 0) cout << all_data[j][0] << all_data[j][1] << all_data[j][2] << all_data[j][3] << endl;
        }
    }
    for (int i = 0; i<row; i++)
        delete[]course_student_flag[i];
    delete[]course_student_flag;
    getchar(); getchar();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章