C/C++教程

用LUA(和C++)刷PAT (Advanced Level) ——1039 Course List for Student

本文主要是介绍用LUA(和C++)刷PAT (Advanced Level) ——1039 Course List for Student,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

用Vector和sort会超时
满分C++:

#include <iostream>
#include <map>

using namespace std;

int main()
{
    int Nstudent, Ncourse;
    cin>>Nstudent>> Ncourse;
    map<string, map<int, bool>> student2course;
    
    for (int i = 0; i < Ncourse; i++){
        int course_name, student_count;
        cin>>course_name>>student_count;
        for (int j = 0; j < student_count; j++){
            string student_name;
            cin>>student_name;
            student2course[student_name][course_name] = true;
        }
    }
    
    for (int i = 0; i < Nstudent; i++){
        string student_name;
        cin>>student_name;
        cout<<student_name;
        
        cout<<" "<<student2course[student_name].size();
        for (auto iter:student2course[student_name])
            cout<<" "<<iter.first;
        
        cout<<endl;
    }
}

超时Lua:

ioread = io.read('*a'):gmatch('%a*%d+')

--para
Nstudent = tonumber(ioread()) Ncourse = tonumber(ioread())
student2course = {}
setmetatable(student2course, {__index = function(t, k) t[k] = {} return t[k] end})

--main
for _ = 1, Ncourse do
    local course_name = tonumber(ioread()) student_count = tonumber(ioread())
    for _ = 1, student_count do
        local student_name = ioread()
        table.insert(student2course[student_name], course_name)
    end
end

for _ = 1, Nstudent do
    local student_name = ioread()
    table.sort(student2course[student_name], function(a, b) return a < b end)
    print(student_name .. " " .. #student2course[student_name] .. (#student2course[student_name] > 0 and " " or "") .. table.concat(student2course[student_name], " "))
end
这篇关于用LUA(和C++)刷PAT (Advanced Level) ——1039 Course List for Student的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!