C/C++,组合算法——K人活动选择问题(Activity-Selection-Problem)的源程序

本文主要是介绍C/C++,组合算法——K人活动选择问题(Activity-Selection-Problem)的源程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1 活动选择问题

Activity-Selection-Problem with k persons

给定两个大小为 N 的数组S[]和E[]表示商店的开始和结束时间,以及一个整数值 K 表示人数,
任务是找出如果他们基于以下条件最佳地访问每个商店,他们总共可以访问的商店的最大数量:
(1)一家商店只能被一个人光顾;
(2)一个人不能去另一家商店,如果它的时间与它冲突;

Activity Selection problem is a approach of selecting non-conflicting tasks based on start and end time and can be solved in O(N logN) time using a simple greedy approach. Modifications of this problem are complex and interesting which we will explore as well. Suprising, if we use a Dynamic Programming approach, the time complexity will be O(N^3) that is lower performance.

The problem statement for Activity Selection is that "Given a set of n activities with their start and finish times, we need to select maximum number of non-conflicting activities that can be performed by a single person, given that the person can handle only one activity at a time." The Activity Selection problem follows Greedy approach i.e. at every step, we can make a choice that looks best at the moment to get the optimal solution of the complete problem.

Our objective is to complete maximum number of activities. So, choosing the activity which is going to finish first will leave us maximum time to adjust the later activities. This is the intuition that greedily choosing the activity with earliest finish time will give us an optimal solution. By induction on the number of choices made, making the greedy choice at every step produces an optimal solution, so we chose the activity which finishes first. If we sort elements based on their starting time, the activity with least starting time could take the maximum duration for completion, therefore we won't be able to maximise number of activities.

2 文本格式
 

#include <bits/stdc++.h>
using namespace std;

// Comparator
bool compareBy(const pair<int, int>& a,
               const pair<int, int>& b)
{
    if (a.second != b.second)
        return a.second < b.second;
    return a.first < b.first;
}
// Function to find maximum shops
// that can be visited by K persons
int maximumShops(int* opening, int* closing,
    int n, int k)
{
    // Store opening and closing
    // time of shops
    pair<int, int> a[n];

    for (int i = 0; i < n; i++) {
        a[i].first = opening[i];
        a[i].second = closing[i];
    }

    // Sort the pair of array
    sort(a, a + n, compareBy);

    // Stores the result
    int count = 0;

    // Stores current number of persons visiting
    // some shop with their ending time
    multiset<int> st;

    for (int i = 0; i < n; i++) {

        // Check if current shop can be
        // assigned to a person who's
        // already visiting any other shop
        bool flag = false;

        if (!st.empty()) {

            auto it = st.upper_bound(a[i].first);

            if (it != st.begin()) {
                it--;

                // Checks if there is any person whose
                // closing time <= current shop opening
                // time
                if (*it <= a[i].first) {

                    // Erase previous shop visited by the
                    // person satisfying the condition
                    st.erase(it);

                    // Insert new closing time of current
                    // shop for the person satisfying ṭhe
                    // condition
                    st.insert(a[i].second);

                    // Increment the count by one
                    count++;

                    flag = true;
                }
            }
        }

        // In case if no person have closing
        // time <= current shop opening time
        // but there are some persons left
        if (st.size() < k && flag == false) {
            st.insert(a[i].second);
            count++;
        }
    }

    // Finally print the ans
    return count;
}

// Driver Code
int main()
{
    // Given starting and ending time
    int S[] = { 1, 8, 3, 2, 6 };
    int E[] = { 5, 10, 6, 5, 9 };

    // Given K and N
    int K = 2, N = sizeof(S) / sizeof(S[0]);

    // Function call
    cout << maximumShops(S, E, N, K) << endl;
}
 

3 代码格式

#include <bits/stdc++.h>
using namespace std;// Comparator
bool compareBy(const pair<int, int>& a,const pair<int, int>& b)
{if (a.second != b.second)return a.second < b.second;return a.first < b.first;
}
// Function to find maximum shops
// that can be visited by K persons
int maximumShops(int* opening, int* closing,int n, int k)
{// Store opening and closing// time of shopspair<int, int> a[n];for (int i = 0; i < n; i++) {a[i].first = opening[i];a[i].second = closing[i];}// Sort the pair of arraysort(a, a + n, compareBy);// Stores the resultint count = 0;// Stores current number of persons visiting// some shop with their ending timemultiset<int> st;for (int i = 0; i < n; i++) {// Check if current shop can be// assigned to a person who's// already visiting any other shopbool flag = false;if (!st.empty()) {auto it = st.upper_bound(a[i].first);if (it != st.begin()) {it--;// Checks if there is any person whose// closing time <= current shop opening// timeif (*it <= a[i].first) {// Erase previous shop visited by the// person satisfying the conditionst.erase(it);// Insert new closing time of current// shop for the person satisfying ṭhe// conditionst.insert(a[i].second);// Increment the count by onecount++;flag = true;}}}// In case if no person have closing// time <= current shop opening time// but there are some persons leftif (st.size() < k && flag == false) {st.insert(a[i].second);count++;}}// Finally print the ansreturn count;
}// Driver Code
int main()
{// Given starting and ending timeint S[] = { 1, 8, 3, 2, 6 };int E[] = { 5, 10, 6, 5, 9 };// Given K and Nint K = 2, N = sizeof(S) / sizeof(S[0]);// Function callcout << maximumShops(S, E, N, K) << endl;
}

这篇关于C/C++,组合算法——K人活动选择问题(Activity-Selection-Problem)的源程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/458393

相关文章

linux生产者,消费者问题

pthread_cond_wait() :用于阻塞当前线程,等待别的线程使用pthread_cond_signal()或pthread_cond_broadcast来唤醒它。 pthread_cond_wait() 必须与pthread_mutex 配套使用。pthread_cond_wait()函数一进入wait状态就会自动release mutex。当其他线程通过pthread

关于C++中的虚拟继承的一些总结(虚拟继承,覆盖,派生,隐藏)

1.为什么要引入虚拟继承 虚拟继承是多重继承中特有的概念。虚拟基类是为解决多重继承而出现的。如:类D继承自类B1、B2,而类B1、B2都继承自类A,因此在类D中两次出现类A中的变量和函数。为了节省内存空间,可以将B1、B2对A的继承定义为虚拟继承,而A就成了虚拟基类。实现的代码如下: class A class B1:public virtual A; class B2:pu

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

问题:第一次世界大战的起止时间是 #其他#学习方法#微信

问题:第一次世界大战的起止时间是 A.1913 ~1918 年 B.1913 ~1918 年 C.1914 ~1918 年 D.1914 ~1919 年 参考答案如图所示

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

C/C++的编译和链接过程

目录 从源文件生成可执行文件(书中第2章) 1.Preprocessing预处理——预处理器cpp 2.Compilation编译——编译器cll ps:vs中优化选项设置 3.Assembly汇编——汇编器as ps:vs中汇编输出文件设置 4.Linking链接——链接器ld 符号 模块,库 链接过程——链接器 链接过程 1.简单链接的例子 2.链接过程 3.地址和

2024.6.24 IDEA中文乱码问题(服务器 控制台 TOMcat)实测已解决

1.问题产生原因: 1.文件编码不一致:如果文件的编码方式与IDEA设置的编码方式不一致,就会产生乱码。确保文件和IDEA使用相同的编码,通常是UTF-8。2.IDEA设置问题:检查IDEA的全局编码设置和项目编码设置是否正确。3.终端或控制台编码问题:如果你在终端或控制台看到乱码,可能是终端的编码设置问题。确保终端使用的是支持你的文件的编码方式。 2.解决方案: 1.File -> S

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

mysql索引四(组合索引)

单列索引,即一个索引只包含单个列,一个表可以有多个单列索引,但这不是组合索引;组合索引,即一个索引包含多个列。 因为有事,下面内容全部转自:https://www.cnblogs.com/farmer-cabbage/p/5793589.html 为了形象地对比单列索引和组合索引,为表添加多个字段:    CREATE TABLE mytable( ID INT NOT NULL, use