头歌实训作业 算法设计与分析-贪心算法(第3关:活动安排问题)

任务描述

本关任务:求解活动安排问题。

假定一个有n个活动(activity)的集合S={a 1 ,a 2,....,a n},这些活动使用同一个资源(例如同一个阶梯教室),而这个资源在某个时刻只能供一个活动使用。每个活动a i都有一个开始时间s i和一个结束时间f i,其中0<=s i<f i<=32767。如果被选中,任务a i 发生在半开时间区间[s i ,f i )期间。如果两个活动a i和a j满足[s i ,f i )和[s j ,f j )不重叠,则称它们是兼容的。也就说,若s i >=f j 或s j >=f i ,则a i和a j 是兼容的。在活动选择问题中,我们希望选出一个最大兼容活动集。

编程要求

根据提示,在右侧编辑器补充代码,计算并输出可兼容活动的最大数量。

测试说明

输入格式:

第一行一个整数n(n≤1000);

接下来的n行,每行两个整数,第一个s i​ ,第二个是f i​ (0<=s i <f i <=32767)。

输出格式:

输出最多能安排的活动个数。

输入样例:

11

3 5

1 4

12 14

8 12

0 6

8 11

6 10

5 7

3 8

5 9

2 13

输出样例:

4

样例解释:

最大可兼容活动数量为4。安排的4个活动为1 4, 5 7, 8 11和12 14。

测试代码:

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Action
{	
	/* 请在这里填写答案 */

/**********  Begin  **********/




/**********  End  **********/ 
};

int n;
vector<struct Action> A;	
//求解结果表示
vector<bool> flag;					//标记选择的活动
int Count = 0;					//选取的兼容活动个数

void solve()					//求解最大兼容活动子集
{
	/* 请在这里填写答案 */

/**********  Begin  **********/




/**********  End  **********/ 
}
int main()
{
	cin>>n;
	for(int i = 0; i < n; i++){
		Action t;
		cin>>t.b>>t.e;
		A.push_back(t);	
	}

	solve();

	cout<<Count<<endl;
	
	return 0;
}

补充代码:

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Action
{	
	/* 请在这里填写答案 */

/**********  Begin  **********/
int b;
int e;
bool operator < (const Action &s) const{
    return e < s.e;
}


/**********  End  **********/ 
};

int n;
vector<struct Action> A;	
//求解结果表示
vector<bool> flag;					//标记选择的活动
int Count = 0;					//选取的兼容活动个数

void solve()					//求解最大兼容活动子集
{
	/* 请在这里填写答案 */

/**********  Begin  **********/
sort(A.begin(), A.end());
int preEnd = 0;
for(int i=0 ; i<n; i++){
    if(A[i].b >= preEnd){
        flag.push_back(true);
        preEnd = A[i].e;
        Count++;
    }
    else{
        flag.push_back(false);
    }
}



/**********  End  **********/ 
}
int main()
{
	cin>>n;
	for(int i = 0; i < n; i++){
		Action t;
		cin>>t.b>>t.e;
		A.push_back(t);	
	}

	solve();

	cout<<Count<<endl;
	
	return 0;
}
相关推荐
Cccp.1233 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
千里码aicood3 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
做cv的小昊3 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له4 小时前
World-In-World: World Models in a Closed-Loop World
算法
Discipline10296 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
XuCoder6 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法
小羊没烦恼!6 小时前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#
weixin_307779136 小时前
基于睿擎工业开发平台的预训练视觉模型轻量化适配与低代码部署优化
开发语言·算法
hold?fish:palm7 小时前
45 二叉树的右视图
开发语言·c++·算法