【发布时间】:2015-03-23 07:45:56
【问题描述】:
我正在使用 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++ 以更好的性能实现这一点?任何帮助,将不胜感激。提前致谢!
【问题讨论】:
-
哦,我什么都试过了。 getchar_unlocked() 而不是 scanf。我在必要时使用内联函数和注册变量。但是还是超过时限!!!看来逻辑部分必须以更好的方式进行修改。例如,如果我们试图在大约 10000 个时间段内寻找重叠或不重叠,它必须以更快的方式处理它以找到结果。
-
这个问题在stackoverflow中是没有的。仅当两个时间段重叠或在 stackoverflow 中不存在时。
-
听起来你会将每个区间与其他区间进行比较 => O(n^2)。您可以在 O(n log n) 中执行此操作,因为最昂贵的操作是对您的配对进行排序...
标签: c++