Student List for Course (25)

来源:互联网 发布:淘宝账号已被冻结 编辑:程序博客网 时间:2024/05/16 07:25

题目描述

Zhejiang University has 40000 students and provides 2500 courses.  Now given the registered course list of each student, you are supposed to output the student name lists of all the courses.

输入描述:

Each input file contains one test case.  For each case, the first line contains 2 numbers: N (<=40000), the total number of students, and K (<=2500), the total number of courses.  Then N lines follow, each contains a student's name (3 capital English letters plus a one-digit number), a positive number C (<=20) which is the number of courses that this student has registered, and then followed by C course numbers.  For the sake of simplicity, the courses are numbered from 1 to K.


输出描述:

For each test case, print the student name lists of all the courses in increasing order of the course numbers.  For each course, first print in one line the course number and the number of registered students, separated by a space.  Then output the students' names in alphabetical order.  Each name occupies a line.

输入例子:

10 5ZOE1 2 4 5ANN0 3 5 2 1BOB5 5 3 4 2 1 5JOE4 1 2JAY9 4 1 2 5 4FRA8 3 4 2 5DON2 2 4 5AMY7 1 5KAT3 3 5 4 2LOR6 4 2 4 1 5

输出例子:

1 4ANN0BOB5JAY9LOR62 7ANN0BOB5FRA8JAY9JOE4KAT3LOR63 1BOB54 7BOB5DON2FRA8JAY9KAT3LOR6ZOE15 9AMY7ANN0BOB5DON2FRA8JAY9KAT3LOR6ZOE1


这道题目最大的难点在于容易运行超时。

所以输入输出时绝对不能使用C++的cin和cout(string类型输入:先用字符串形式输入,再用stringstream转换为string类型,string类型输出同理)。

即使如此,此代码在处理最大数据时(40000学生,2500门课),运行时间仍需要大约六七百毫秒。

牛客网上通过没有问题(时间限制一秒),但是PAT甲级真题上时间限制是在400毫秒内,故此代码还需要进一步的修改。


我的代码:

#include<iostream>#include<set>#include<string>#include<sstream>using namespace std;set<string>s[2501];int main(){    int i,n,m,sum,num;    scanf("%d%d%*c",&n,&m);    char a[10];    string name;    while(n--)    {          scanf("%s",a);        stringstream ss;        ss<<a;        ss>>name;        scanf("%d",&sum);        while(sum--)        {            scanf("%d",&num);            s[num-1].insert(name);        }    }    for(i=0;i<m;i++)    {        printf("%d %d\n",i+1,s[i].size());        set<string>::iterator it;        for(it=s[i].begin();it!=s[i].end();it++)        {            stringstream sss;            sss<<*it;            sss>>a;            puts(a);        }    }    return 0;}

原创粉丝点击