從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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章