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

相关文章

k8s容器放开锁内存限制问题

《k8s容器放开锁内存限制问题》nccl-test容器运行mpirun时因NCCL_BUFFSIZE过大导致OOM,需通过修改docker服务配置文件,将LimitMEMLOCK设为infinity并... 目录问题问题确认放开容器max locked memory限制总结参考:https://Access

Java中字符编码问题的解决方法详解

《Java中字符编码问题的解决方法详解》在日常Java开发中,字符编码问题是一个非常常见却又特别容易踩坑的地方,这篇文章就带你一步一步看清楚字符编码的来龙去脉,并结合可运行的代码,看看如何在Java项... 目录前言背景:为什么会出现编码问题常见场景分析控制台输出乱码文件读写乱码数据库存取乱码解决方案统一使

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

解决升级JDK报错:module java.base does not“opens java.lang.reflect“to unnamed module问题

《解决升级JDK报错:modulejava.basedoesnot“opensjava.lang.reflect“tounnamedmodule问题》SpringBoot启动错误源于Jav... 目录问题描述原因分析解决方案总结问题描述启动sprintboot时报以下错误原因分析编程异js常是由Ja

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据