forked from woodbri/vrpdptw
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Solution.cpp
116 lines (95 loc) · 2.72 KB
/
Solution.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
114
115
116
#include "Route.h"
#include "Solution.h"
// NON class functions for sorting
bool sortByOid(Order a, Order b)
{
return a.oid < b.oid;
}
// Class functions
void Solution::sequentialConstruction() {
// std::cout << "Enter Problem::sequentialConstruction\n";
int M = 0;
R.clear();
int numUnassigned = P.O.size() - 1;
while (numUnassigned > 0) {
Route r(P);
r.rid = M;
for (int i=0; i<P.O.size(); i++) {
if (P.O[i].oid == 0) continue; // don't add the depot
if (mapOtoR[P.O[i].oid] != -1) continue; // search unassigned orders
r.addOrder(P.O[i]);
mapOtoR[P.O[i].oid] = r.rid;
r.hillClimbOpt();
// if route is not feasible
if (r.orders.size() > 1 && (r.TWV > 0 || r.CV > 0)) {
r.removeOrder(P.O[i]);
mapOtoR[P.O[i].oid] = -1;
}
// else if it is feasible
else {
mapOtoR[P.O[i].oid] = r.rid;
numUnassigned--;
}
}
R.push_back(r);
M++;
}
sort(P.O.begin(), P.O.end(), sortByOid);
//std::cout << "Exit Problem::sequentialConstruction\n";
}
void Solution::initialConstruction() {
int M = 0;
R.clear();
for (int i=0; i<P.O.size(); i++) {
if (P.O[i].oid == 0) continue; // don't add the depot
Route r(P);
r.rid = M++;
r.addOrder(P.O[i]);
mapOtoR[P.O[i].oid] = r.rid;
R.push_back(r);
}
sort(P.O.begin(), P.O.end(), sortByOid);
}
void Solution::computeCosts() {
totalCost = 0.0;
totalDistance = 0.0;
for (int i=0; i<R.size(); i++) {
totalCost += R[i].getCost();
totalDistance += R[i].D;
}
}
double Solution::getCost() {
return totalCost;
}
double Solution::getDistance() {
return totalDistance;
}
void Solution::dump() {
computeCosts();
std::cout << "Solution: totalDistance: " << totalDistance
<< ", totalCost: " << totalCost
<< std::endl << "Routes:" << std::endl;
for (int i=0; i<R.size(); i++)
R[i].dump();
std::cout << "mapOtoR: ";
for (int i=0; i<mapOtoR.size(); i++) {
if (i) std::cout << ", ";
std::cout << mapOtoR[i];
}
std::cout << std::endl;
}
double Solution::getAverageRouteDurationLength() {
double len = 0.0;
int n = 0;
for (int i=0; i<R.size(); i++) {
if (R[i].path.size() == 0) continue;
if (R[i].updated) R[i].update();
len += R[i].D;
n++;
}
if (n == 0) {
std::string errmsg = "Solution.getAverageRouteDurationLength: There do not appear to be any routes!";
throw std::runtime_error(errmsg);
}
return len/n;
}