cjweffort

博客园 首页 联系 订阅 管理

give the hash key to every student,then sort the students in increasing order of the students name.

to every course,traverse the list of student who select the course,his own hash key will exists.

traverse every students,if he has the hash key(select the course) then must print his name.

as we had sorted the students,so the answer will be in increasing order.

learn to use hash theory,about this problem,time is so value.

// 1047. Student List for Course.cpp: 主项目文件。

#include "stdafx.h"
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using std::sort;
using std::vector;

const int Cmax=2503;
const int Smax=40003;
//the hash key every student reflects,begin from 0
bool hash[Smax];
//construct the hash key
typedef struct Stu{
	char name[5];
	int id;
}Stu;
Stu stu[Smax];
vector<int> courseList[Cmax];

bool cmp(Stu m1,Stu m2){
	return strcmp(m1.name,m2.name)<0;
}

int main()
{
	int students,course;
	scanf("%d%d",&students,&course);
	for(int i=0;i<students;i++){
		int num;
		scanf("%s%d",stu[i].name,&num);
		stu[i].id=i;
		while(num--){
			int temp;
			scanf("%d",&temp);
			courseList[temp].push_back(i);
		}
	}
	sort(stu,stu+students,cmp);
	memset(hash,0,sizeof(hash));
	for(int i=1;i<=course;i++){
		printf("%d %d\n",i,courseList[i].size());
		//if the student exists,give the hash key 
		for(vector<int>::iterator ite=courseList[i].begin();ite!=courseList[i].end();ite++)
			hash[*ite]=true;
		for(int j=0;j<students;j++){
			if(hash[stu[j].id])//hash key exists
				printf("%s\n",stu[j].name);
		}
		for(vector<int>::iterator ite=courseList[i].begin();ite!=courseList[i].end();ite++)
			hash[*ite]=false;
	}
	return 0;
}


posted on 2013-03-12 17:15  cjweffort  阅读(191)  评论(0编辑  收藏  举报