解题思路:采用桶排序思想,将每个课程看成一个桶,再把每个课程对应学生放入桶,其中学生名单的采用二叉排序树结构存储
#include <stdio.h> #include <malloc.h> #include <string.h> #define MaxSize 2503 #define MaxS 4 typedef char Element[MaxS+1]; typedef struct TNode *Tree; struct TNode{ Element Name; struct TNode *Left,*Right; }; typedef struct HashTbl *HashTable; struct HashTbl{ int Num; Tree Next; }; HashTable InitialHashTable(int Size); void Insert(HashTable H,int CourseNo,Element Name); Tree BuildBiSearchTree(Tree T,Element Name); void Trav(Tree T); void Out(HashTable H,int M); int main() { int N,M,i,j,n,CourseNo; Element Name; HashTable H; scanf("%d %d",&N,&M); H=InitialHashTable(M+1); for(i=0;i<N;i++) { scanf("%s%d",&Name,&n); for(j=0;j<n;j++) { scanf("%d",&CourseNo); Insert(H,CourseNo,Name); } } Out(H,M); return 0; } HashTable InitialHashTable(int Size) { HashTable H=malloc(sizeof(struct HashTbl)*Size); while(Size) { H[--Size].Next=NULL; H[Size].Num=0; } return H; } void Insert(HashTable H,int CourseNo,Element Name) { Tree T=H[CourseNo].Next; H[CourseNo].Num++; H[CourseNo].Next=BuildBiSearchTree(T,Name); } Tree BuildBiSearchTree(Tree T,Element Name) { if(!T) { T=malloc(sizeof(struct TNode)); strcpy(T->Name,Name); T->Left=NULL; T->Right=NULL; } else if(strcmp(Name,T->Name)<0) { T->Left=BuildBiSearchTree(T->Left,Name); } else { T->Right=BuildBiSearchTree(T->Right,Name); } return T; } void Trav(Tree T) { if(T) { Trav(T->Left); printf("%s ",T->Name); Trav(T->Right); } } void Out(HashTable H,int M) { int i; for(i=1;i<=M;i++) { printf("%d %d ",i,H[i].Num); Tree T=H[i].Next; Trav(T); } }