用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