I am using std::pair to get start time and end time of each time periods and I put all those time periods in an array (say classes[no_of_time_periods]). Code for it:
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;
}
I know I can check if two time periods overlap or not using following condition:
if(!(classes[i].first<classes[j].second && classes[i].second>classes[j].first))
But I want to check for more than two time periods. Example:
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
I found the logic and I wrote the code.But while submitting in Online Judge(SPOJ), it says "Time Limit Exceeded".So, Obviously my code was not well optimized. How to achieve this using c++ with better performance? Any Help would be appreciated. Thanks in advance!