有关考试安排的算法(一):不冲突的算法


分类: 算法 |
版权声明:本文为博主原创文章,未经博主允许不得转载。
http://p.blog.csdn.net/images/p_blog_csdn_net/smallfools/EntryImages/20091208/1.jpg
http://p.blog.csdn.net/images/p_blog_csdn_net/smallfools/EntryImages/20091208/2.jpg
-
truncate
table Exam -
--考场中可同时容纳的考生人数
-
declare
@MaxNumber int -
set
@MaxNumber = 1500 -
--考试场次
-
declare
@ExamScreenings int -
set
@ExamScreenings = 0 -
--单场考试还能安排多少人数
-
declare
@RemainNum int -
--最始化:可安排人数与考场可容纳人数相同
-
set
@RemainNum = @MaxNumber -
--最后一次已安排的考试课程名
-
declare
@LastCourseName varchar(50) -
set
@LastCourseName null= -
--统计每门课程的考试人数,并放入临时表中
-
select
CourseName,count(id) as ExamNum -
into
#tempSelectCourse -
from SelectCourse -
group by CourseName -
order by ExamNum desc -
--显示临时表中的数据
-
select
* from #tempSelectCourse -
--开始循环
-
while
1=1 -
begin
-
--当前选择的考试课程名 -
declare @CurrentCourseName varchar(50) -
set @CurrentCourseName null= -
-
--当前课程的选课人数 -
declare @CurrentExamNum int -
--在临时表中选出选课最多的那门课程(假设该门课程的选课人数小于考场可安排的人数) -
select top 1 @CurrentExamNum = ExamNum, @CurrentCourseName = CourseName from #tempSelectCourse order by ExamNum desc -
--如果当前选择的考试课程名为空,则说明在该场次考试中已经没有可安排的课程 -
if @CurrentCourseName isnull -
begin -
--跳出循环 -
break -
end -
else -
--否则说明还有可安排的课程 -
begin -
--考试场次加1 -
set @ExamScreenings = @ExamScreenings + 1 -
--将当前选择的课程添加到考场安排表里 -
insert Exam (ExamScreenings,Course,ExamNum) values (@ExamScreenings,@CurrentCourseName,@CurrentExamNum) -
--从临时表中删除该门课程 -
delete #tempSelectCourse where CourseName = @CurrentCourseName -
NextCourse: -
--当前考场还能安排多少人进行考试 -
set @RemainNum = @RemainNum - @CurrentExamNum -
--将选课人数少于或等于当前考场还能安排考试人数的记录放在游标里 -
declare aa cursor for -
select ExamNum,CourseName from #tempSelectCourse where ExamNum<=@RemainNum order by ExamNum desc -
--打开游标 -
open aa -
--从游标里取出一条记录 -
fetch next from aa into @CurrentExamNum,@CurrentCourseName -
--判断游标里是否还有记录 -
while(@@fetch_status=0) -
begin -
--判断选课当前课程的学生,在同一场考试中是否还有别的课程需要考试(考试冲突判断) -
if (SELECT count(id) FROM SelectCourse -
INNER JOIN ( -
SELECT SelectCourse.StudentId FROM Exam -
INNER JOIN SelectCourse ON Exam.Course = SelectCourse.CourseName -
WHERE (Exam.ExamScreenings = @ExamScreenings) -
) AS ArrangedCourse -
ON SelectCourse.StudentId = ArrangedCourse.StudentId -
WHERE CourseName=@CurrentCourseName)=0 -
begin -
--如果考试不冲突,则将当前选择的课程添加到考场安排表里 -
insert Exam (ExamScreenings,Course,ExamNum) values (@ExamScreenings,@CurrentCourseName,@CurrentExamNum) -
--从临时表中删除该门课程 -
delete #tempSelectCourse where CourseName = @CurrentCourseName -
--关闭游标,重新计算剩余的课程 -
close aa -
deallocate aa -
goto NextCourse -
end -
--获取下一条记录 -
fetch next from aa into @CurrentExamNum,@CurrentCourseName -
end -
--关闭游标 -
close aa -
deallocate aa -
end -
end
-
--删除临时表
-
drop
table #tempSelectCourse -
原创不容易,转载请注明出处。http://blog.csdn.net/smallfools/archive/2009/12/08/4961307.aspx