今年暑假不AC(解题报告)

http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1&sectionid=3&problemid=3

乍看之下,感觉要用动态规划。仔细分析题目你会发现,当我们将结束时间排序后,可以使用逐步的贪婪算法求出最优解。

至于为什么要用结束时间排序,因为可以出现开始时间为1结束时间很长的节目。

如 节目1(1-8) 节目2(2-4) 节目3(4-7) 这时的最优解是选择节目2,3。如果使用开始时间排序的话会得到节目1,

而非最优解

#include<iostream>
#include<string.h>
int main()
{
	int n,i=0;
	while(std::cin>>n, n != 0)
	{
		
		int* begin = new int[n];
		int* end = new int[n];
		int* res = new int[n];
		memset(res,0,n*sizeof(int));
		int index = 0;
		for(int i = 0; i < n; i++)
		{
			std::cin>>begin[i]>>end[i];
		}
		for(int i = 0; i < n; i++)
			for(int j = n - 1 ; j > i; j--)
			{
				if(end[j] < end[j - 1])
				{
					int e = end[j];
					end[j] = end[j-1];
					end[j-1] = e;
					int b = begin[j];
					begin[j] = begin[j-1];
					begin[j-1] = b;
				}
				else if(end[j] == end[j-1])
				{
					if(begin[j] < begin[j-1])
					{
						int temp = begin[j];
						begin[j] = begin[j-1];
						begin[j-1] = begin[j];
					}
				}
			}
		for(int i = 0; i < n; i++)
		{
			if(res[index] <= begin[i])
				res[++index] = end[i];
		}
		std::cout<<index<<std::endl;
		delete begin;
		delete end;
		delete res;
	}
	return 0;
}

posted on 2011-07-05 16:20  Bourbon  阅读(745)  评论(0编辑  收藏  举报

导航