-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDAA_Weighted_Interval_Scheduling.cpp
114 lines (113 loc) · 1.93 KB
/
DAA_Weighted_Interval_Scheduling.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<iostream>
using namespace std;
#define MAX 20
int M[MAX];
struct Interval
{
int start_time, finish_time, weight;
};
class WIS
{
Interval I[MAX];
public:
int n;
WIS()
{
for (int i = 0; i <= MAX; i++)
M[i] = 0;
}
int input();
void interval_sort();
int z(int); //getting finished and non-overlapping intervals
int m_compute_opt(int);
};
int WIS::z(int j)
{
for (int i = j - 1; i > 0; i--)
{
if (I[i].finish_time <= I[j].start_time)
{
return i;
}
}
return 0;
}
int WIS::input()
{
cout << "\nEnter number of intervals: ";
cin >> n;
cout << "\nEnter the starting time, finishing time and weight value of intervals: ";
cout << "\n\nSi "<<" Fi "<<" Vi\n";
for (int i = 1; i <= n; i++)
{
cin >> I[i].start_time;
cin >> I[i].finish_time;
cin >> I[i].weight;
}
}
void WIS::interval_sort()
{
int i, flag = 1;
Interval temp;
for (i = 1; (i <= n) && flag; i++)
{
flag = 0;
for (int j = 1; j < n; j++)
{
if (I[j+1].finish_time < I[j].finish_time)
{
temp = I[j];
I[j] = I[j + 1];
I[j + 1] = temp;
flag = 1;
}
}
}
for (i = 1; i <= n; i++)
{
for (int j = i + 1; j <= n; j++)
{
if (I[i].finish_time == I[j].finish_time && I[i].start_time > I[j].start_time)
{
temp = I[i];
I[i] = I[j];
I[j] = temp;
}
}
}
cout << "I<i>\t\tS<i>\t\tF<i>\t\tV<i>\n";
for (int i = 1; i <= n; i++)
{
cout << i << "\t\t" << I[i].start_time << "\t\t" << I[i].finish_time << "\t\t" << I[i].weight << "\n";
}
}
int WIS::m_compute_opt(int j)
{
if (j == 0)
{
return 0;
}
else if (M[j])
{
return M[j];
}
else
{
M[j] = max((I[j].weight + m_compute_opt(z(j))),m_compute_opt(j - 1));
}
return M[j];
}
int main()
{
WIS job;
job.input();
cout << "\nSorted Input Intervals: \n";
job.interval_sort();
cout << endl;
for (int i = 1; i <= job.n; i++)
cout << "OPT[" << i << "]\t";
cout << endl;
for (int i = 1; i <= job.n; i++)
cout << job.m_compute_opt(i) << "\t";
return 0;
}