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

相关文章

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

C++中全局变量和局部变量的区别

《C++中全局变量和局部变量的区别》本文主要介绍了C++中全局变量和局部变量的区别,全局变量和局部变量在作用域和生命周期上有显著的区别,下面就来介绍一下,感兴趣的可以了解一下... 目录一、全局变量定义生命周期存储位置代码示例输出二、局部变量定义生命周期存储位置代码示例输出三、全局变量和局部变量的区别作用域

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

nginx 负载均衡配置及如何解决重复登录问题

《nginx负载均衡配置及如何解决重复登录问题》文章详解Nginx源码安装与Docker部署,介绍四层/七层代理区别及负载均衡策略,通过ip_hash解决重复登录问题,对nginx负载均衡配置及如何... 目录一:源码安装:1.配置编译参数2.编译3.编译安装 二,四层代理和七层代理区别1.二者混合使用举例

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

C++中NULL与nullptr的区别小结

《C++中NULL与nullptr的区别小结》本文介绍了C++编程中NULL与nullptr的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编... 目录C++98空值——NULLC++11空值——nullptr区别对比示例 C++98空值——NUL

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.