cjweffort

博客园 首页 联系 订阅 管理

the final judge data is so big that so many times test result is time limit.To refer the idea from the Internet,solve this problem need to utilize the hash thinking.

As a student name consists of 3 capital English letters plus a one-digit number,from 0 to 26*26*26*10*(courses+2)(the total number of courses),every students who select a course can correspond to one hash key.Obviouly every name has a start hash key and an end hash key which can act as two borders.We will insert the key and border keys into arrar and sort the array.

Final to find the courses distinct students select,just to search the borders and easily can find the result.

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

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

const int N=3*2500*200+3;
int keyArr[N];
//used this array to get hash key
bool tag[26][26][26][10];

int getBorderKey(char *name,int totalCourse){
	int tt[8];
	for(int i=0;i<3;i++)
		tt[i]=name[i]-'A';
	tt[3]=name[3]-'0';
	int dis=(int)(long)(&tag[tt[0]][tt[1]][tt[2]][tt[3]])-
		(int)(long)(&tag[0][0][0][0]);
	return dis*(totalCourse+2);

}

int binarySearch(int key,int low,int high){
	if(low<=high){
		int mid=low+(high-low)/2;
		if(key==keyArr[mid])
			return mid;
		else if(key<keyArr[mid])
			return binarySearch(key,low,mid-1);
		else
			return binarySearch(key,mid+1,high);
	}
	return -1;
}

int main()
{
    int totalStudents,totalCourse;
	scanf("%d%d",&totalStudents,&totalCourse);
	memset(tag,0,sizeof(tag));
	int cnt=0;
	for(int i=0;i<totalCourse;i++){
		int courseNum,num;
		scanf("%d%d",&courseNum,&num);
		while(num--){
			char name[8];
			scanf("%s",name);
			int borderkey=getBorderKey(name,totalCourse);
			int key=borderkey+courseNum;
			int sKey=borderkey,eKey=borderkey+totalCourse+1;
			if(!tag[name[0]-'A'][name[1]-'A'][name[2]-'A'][name[3]-'0']){
				tag[name[0]-'A'][name[1]-'A'][name[2]-'A'][name[3]-'0']=true;
				keyArr[cnt++]=sKey;
				keyArr[cnt++]=eKey;
			}
			keyArr[cnt++]=key;
		}
	}
	sort(keyArr,keyArr+cnt);
	for(int i=0;i<totalStudents;i++){
		char query[8];
		scanf("%s",query);
		printf("%s",query);
		//get the border
		int borderKey=getBorderKey(query,totalCourse);
		int startKey=borderKey,endKey=borderKey+totalCourse+1;
		int startIndex=binarySearch(startKey,0,cnt);
		int endIndex=binarySearch(endKey,0,cnt);
		if(startIndex==-1){
			printf(" 0\n");
			continue;
		}
		printf(" %d",endIndex-startIndex-1);
		for(int j=startIndex+1;j<endIndex;j++){
			printf(" %d",keyArr[j]-startKey);
		}
		printf("\n");
	}
    return 0;
}


posted on 2013-03-12 20:11  cjweffort  阅读(174)  评论(0编辑  收藏  举报