1047. Student List for Course (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.
Input Specification:
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.
Output Specification:
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.
Sample Input:10 5 ZOE1 2 4 5 ANN0 3 5 2 1 BOB5 5 3 4 2 1 5 JOE4 1 2 JAY9 4 1 2 5 4 FRA8 3 4 2 5 DON2 2 4 5 AMY7 1 5 KAT3 3 5 4 2 LOR6 4 2 4 1 5Sample Output:
1 4 ANN0 BOB5 JAY9 LOR6 2 7 ANN0 BOB5 FRA8 JAY9 JOE4 KAT3 LOR6 3 1 BOB5 4 7 BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1 5 9 AMY7 ANN0 BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1
分析:由于最终的输出是以课程编号为序,所以每个课程有一个vector,存储选这门课的学生编号。 在输出时,要求按照学生姓名排序输出,所以要对N个学生姓名排序;若每次输出都重新排序,则效率低且重复运算,可以一次性对学生姓名排序,然后建立一个映射表map将原有序号与排序后的序号对应起来。
代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#include "stdio.h"
//此代码使用前,需删除下面两行+后面的system("PAUSE")
ifstream fin("in.txt");
#define cin fin
struct Name
{
char name[5];
int id;
};
int* map = NULL; //映射表指针
bool cmp(const Name& A,const Name& B) //根据Name结构体中name字符数组大小排序
{
const char* aa = A.name;
const char* bb = B.name;
int res = strcmp(aa,bb);
if(res>0)return false;
else return true;
}
bool compare(const int& A,const int& B) //根据映射后大小排序
{
return map[A]<map[B];
}
int main()
{
int n,k;
scanf("%d %d",&n,&k);
//cin>>n>>k;
//char (*p)[5] = new char[n][5]; //new 一个五字节大小数组的数组指针
Name* rec = new Name[n];
vector<int>* course = new vector<int>[k+1]; //为每个course建立一个vector
int i,j,c,t;
for(i=0;i<n;i++)
{
scanf("%s%d",rec[i].name,&c);
//cin>>rec[i].name>>c;
rec[i].id = i;
for(j=0;j<c;j++)
{
//cin>>t;
scanf("%d",&t);
course[t].push_back(i);
}
}
sort(rec,rec+n,cmp); //把name排序
map = new int[n];
for(i=0;i<n;i++) //将name的输入顺序和排序后顺序 映射起来
{
map[rec[i].id]=i;
}
int size;
for(i=1;i<k+1;i++)
{
size = course[i].size();
printf("%d %d\n",i,size); //size为0,也要输出【第二个case】
if(size==0)continue;
//cout<<i<<' '<<size<<endl;
sort(course[i].begin(),course[i].end(),compare); //根据映射的值进行排序
for(j=0;j<size;j++)
{
printf("%s\n",rec[map[course[i][j]]].name);
//cout<<rec[map[course[i][j]]].name<<endl;
}
}
system("PAUSE");
return 0;
}