HDOJ 2037 今年暑假不AC 【暴力解决】⊙﹏⊙b汗

本文探讨了活动选择问题的两种解决方案:一种是通过回溯搜索算法来寻找最大数量不冲突的活动集合;另一种是采用贪心算法,对活动结束时间进行排序,从而高效地找到最优解。通过具体的代码实现展示了这两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <algorithm>
using namespace std;
#define PLINE printf("\n------------------\n")
struct time
{
	int s,e;
}t[101];

int n, ans;

bool cmp(struct time a, struct time b)
{
	return a.s < b.s;
}
void search(int d, int num, int e)
{
	
	if(d == n)//刚开始竟然把层数写错了,╮(╯▽╰)╭,以后还是搞统一吧
	{
		if(num > ans)
			ans = num;
		
		return;
	}
	if(t[d].s >= e)
		search(d+1, num+1, t[d].e);
		
	search(d+1, num, e);
}
	
int main()
{
	int i;
	while(scanf("%d", &n) && n )
	{
		ans = 0;
		for(i=0; i<n; i++)
			scanf("%d%d", &t[i].s, &t[i].e);
			
		sort(t, t+n, cmp);

		search(0, 0, 0);

		printf("%d\n", ans);
	}
	return 0;
}

//贪心解法
include <stdio.h>
#include <algorithm>
using namespace std;
#define PLINE printf("\n------------------\n")
struct time
{
	int s,e;
}t[101];

bool cmp(struct time a, struct time b)
{
	return a.e < b.e;
}
	
int main()
{
	int i, n, ans, e;
	while(scanf("%d", &n) && n )
	{
		ans = 0;
		for(i=0; i<n; i++)
			scanf("%d%d", &t[i].s, &t[i].e);
			
		sort(t, t+n, cmp);
		e = 0;
		for(i=0; i<n; i++)
			if(t[i].s >= e)
			{
				e = t[i].e;
				ans++;
			}
		printf("%d\n", ans);
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值