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

相关文章

C++ move 的作用详解及陷阱最佳实践

《C++move的作用详解及陷阱最佳实践》文章详细介绍了C++中的`std::move`函数的作用,包括为什么需要它、它的本质、典型使用场景、以及一些常见陷阱和最佳实践,感兴趣的朋友跟随小编一起看... 目录C++ move 的作用详解一、一句话总结二、为什么需要 move?C++98/03 的痛点⚡C++

Springboot3统一返回类设计全过程(从问题到实现)

《Springboot3统一返回类设计全过程(从问题到实现)》文章介绍了如何在SpringBoot3中设计一个统一返回类,以实现前后端接口返回格式的一致性,该类包含状态码、描述信息、业务数据和时间戳,... 目录Spring Boot 3 统一返回类设计:从问题到实现一、核心需求:统一返回类要解决什么问题?

详解C++ 存储二进制数据容器的几种方法

《详解C++存储二进制数据容器的几种方法》本文主要介绍了详解C++存储二进制数据容器,包括std::vector、std::array、std::string、std::bitset和std::ve... 目录1.std::vector<uint8_t>(最常用)特点:适用场景:示例:2.std::arra

C++构造函数中explicit详解

《C++构造函数中explicit详解》explicit关键字用于修饰单参数构造函数或可以看作单参数的构造函数,阻止编译器进行隐式类型转换或拷贝初始化,本文就来介绍explicit的使用,感兴趣的可以... 目录1. 什么是explicit2. 隐式转换的问题3.explicit的使用示例基本用法多参数构造

maven异常Invalid bound statement(not found)的问题解决

《maven异常Invalidboundstatement(notfound)的问题解决》本文详细介绍了Maven项目中常见的Invalidboundstatement异常及其解决方案,文中通过... 目录Maven异常:Invalid bound statement (not found) 详解问题描述可

C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解

《C++,C#,Rust,Go,Java,Python,JavaScript的性能对比全面讲解》:本文主要介绍C++,C#,Rust,Go,Java,Python,JavaScript性能对比全面... 目录编程语言性能对比、核心优势与最佳使用场景性能对比表格C++C#RustGoJavapythonjav

idea粘贴空格时显示NBSP的问题及解决方案

《idea粘贴空格时显示NBSP的问题及解决方案》在IDEA中粘贴代码时出现大量空格占位符NBSP,可以通过取消勾选AdvancedSettings中的相应选项来解决... 目录1、背景介绍2、解决办法3、处理完成总结1、背景介绍python在idehttp://www.chinasem.cna粘贴代码,出

C++打印 vector的几种方法小结

《C++打印vector的几种方法小结》本文介绍了C++中遍历vector的几种方法,包括使用迭代器、auto关键字、typedef、计数器以及C++11引入的范围基础循环,具有一定的参考价值,感兴... 目录1. 使用迭代器2. 使用 auto (C++11) / typedef / type alias

SpringBoot整合Kafka启动失败的常见错误问题总结(推荐)

《SpringBoot整合Kafka启动失败的常见错误问题总结(推荐)》本文总结了SpringBoot项目整合Kafka启动失败的常见错误,包括Kafka服务器连接问题、序列化配置错误、依赖配置问题、... 目录一、Kafka服务器连接问题1. Kafka服务器无法连接2. 开发环境与生产环境网络不通二、序

SpringSecurity中的跨域问题处理方案

《SpringSecurity中的跨域问题处理方案》本文介绍了跨域资源共享(CORS)技术在JavaEE开发中的应用,详细讲解了CORS的工作原理,包括简单请求和非简单请求的处理方式,本文结合实例代码... 目录1.什么是CORS2.简单请求3.非简单请求4.Spring跨域解决方案4.1.@CrossOr