如何在c++中检查两个或多个时间段是否重叠
How to check if two or more time periods overlap each other in c++?
我使用std::pair来获取每个时间段的开始时间和结束时间,并将所有这些时间段放在一个数组中(比如classes[no_of_time_periods])。代码:
int getClassTimes(int N)
{
int subsets, startTime, endTime;
std::pair<int,int> classes[N];
for(int i=0;i<N;i++)
{
printf("Please Enter Class %d Start Time and End Time:",(i+1));
scanf("%d",&startTime);
scanf("%d",&endTime);
classes[i] = std::make_pair(startTime,endTime);
}
subsets = compute(classes,N);
return subsets;
}
我知道我可以使用以下条件检查两个时间段是否重叠:
if(!(classes[i].first<classes[j].second && classes[i].second>classes[j].first))
但我想检查两个以上的时间段。示例:
Input:
No_Of_Time_Periods = 5
Time_Period 1 = 1 to 3
Time_Period 2 = 3 to 5
Time_Period 3 = 5 to 7
Time_Period 4 = 2 to 4
Time_Period 5 = 4 to 6
Calculation(Number of subsets of non-overlapping Time Periods):
**Note: If end time of one class is start time of other, they are non-overlapping.
Ex((1 to 3) and (3 to 5) are non-overlapping.)**
(1 to 3)(3 to 5)
(1 to 3)(3 to 5)(5 to 7)
(1 to 3)(4 to 6)
(1 to 3)(5 to 7)
(2 to 4)(4 to 6)
(2 to 4)(5 to 7)
(3 to 5)(5 to 7)
Output:
Total Number of subsets of non-overlapping classes:7
我找到了逻辑并编写了代码。但是在提交在线法官(SPOJ)时,上面写着"超过时间限制"。所以,显然我的代码没有得到很好的优化。如何使用具有更好性能的c++来实现这一点?如有任何帮助,我们将不胜感激。提前感谢!
这太令人困惑了!重叠测试应该是这样的:
if ((classes[i].second < classes[j].first) || (classes[i].first > classes[j].second))
printf("no overlap");
if (!((classes[i].second < classes[j].first) || (classes[i].first > classes[j].second)))
printf("overlap");
假设classes[n].first
总是小于classes[n].second
检查区间树。您将获得对数复杂度:http://en.wikipedia.org/wiki/Interval_tree
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 给定两个偶数,求出它们之间所有偶数的平方和
- 比较两个大小不等的映射c++
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在for循环中包含两个索引值的测试条件
- 在声明中合并两个常量"std::set"(不是在运行时)
- 如何在c++中检查两个或多个时间段是否重叠