source: tspsg-svn/trunk/src/tspsolver.cpp @ 66

Last change on this file since 66 was 66, checked in by laleppa, 15 years ago

Some documentation updates.

  • Property svn:keywords set to Id URL
File size: 7.0 KB
Line 
1/*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2009 Lёppa <contacts[at]oleksii[dot]name>
4 *
5 *  $Id: tspsolver.cpp 66 2009-10-21 12:48:49Z laleppa $
6 *  $URL: https://tspsg.svn.sourceforge.net/svnroot/tspsg/trunk/src/tspsolver.cpp $
7 *
8 *  This file is part of TSPSG.
9 *
10 *  TSPSG is free software: you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation, either version 3 of the License, or
13 *  (at your option) any later version.
14 *
15 *  TSPSG is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
19 *
20 *  You should have received a copy of the GNU General Public License
21 *  along with TSPSG.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24#include "tspsolver.h"
25
26//! Class constructor
27CTSPSolver::CTSPSolver()
28        : nCities(0)
29{
30}
31
32void CTSPSolver::cleanup()
33{
34        route.clear();
35        mayNotBeOptimal = false;
36}
37
38double CTSPSolver::findMinInRow(int nRow, tMatrix matrix, int exc)
39{
40double min = INFINITY;
41        for (int k = 0; k < nCities; k++)
42                if (((k != exc)) && (min > matrix.at(nRow).at(k)))
43                        min = matrix.at(nRow).at(k);
44        return min == INFINITY ? 0 : min;
45}
46
47double CTSPSolver::findMinInCol(int nCol, tMatrix matrix, int exr)
48{
49double min = INFINITY;
50        for (int k = 0; k < nCities; k++)
51                if ((k != exr) && (min > matrix.at(k).at(nCol)))
52                        min = matrix.at(k).at(nCol);
53        return min == INFINITY ? 0 : min;
54}
55
56void CTSPSolver::subRow(tMatrix &matrix, int nRow, double val)
57{
58        for (int k = 0; k < nCities; k++)
59                if (k != nRow)
60                        matrix[nRow][k] -= val;
61}
62
63void CTSPSolver::subCol(tMatrix &matrix, int nCol, double val)
64{
65        for (int k = 0; k < nCities; k++)
66                if (k != nCol)
67                        matrix[k][nCol] -= val;
68}
69
70double CTSPSolver::align(tMatrix &matrix)
71{
72double r = 0;
73double min;
74        for (int k = 0; k < nCities; k++) {
75                min = findMinInRow(k,matrix);
76                if (min > 0) {
77                        r += min;
78                        subRow(matrix,k,min);
79                }
80        }
81        for (int k = 0; k < nCities; k++) {
82                min = findMinInCol(k,matrix);
83                if (min > 0) {
84                        r += min;
85                        subCol(matrix,k,min);
86                }
87        }
88        return r;
89}
90
91bool CTSPSolver::findCandidate(tMatrix matrix, int &nRow, int &nCol)
92{
93        nRow = -1;
94        nCol = -1;
95bool alts = false;
96double h = -1;
97double sum;
98        for (int r = 0; r < nCities; r++)
99                for (int c = 0; c < nCities; c++)
100//                      if ((matrix.at(r).at(c) == 0) && !forbidden.values(r).contains(c)) {
101                        if (matrix.at(r).at(c) == 0) {
102                                sum = findMinInRow(r,matrix,c) + findMinInCol(c,matrix,r);
103                                if (sum > h) {
104                                        h = sum;
105                                        nRow = r;
106                                        nCol = c;
107                                        alts = false;
108                                } else if ((sum == h) && !hasSubCycles(r,c))
109                                        alts = true;
110                        }
111        return alts;
112}
113
114bool CTSPSolver::hasSubCycles(int nRow, int nCol)
115{
116        if ((nRow < 0) || (nCol < 0) || route.isEmpty() || !(route.size() < nCities - 1) || !route.contains(nCol))
117                return false;
118int i = nCol;
119        while (true) {
120                if ((i = route[i]) == nRow)
121                        return true;
122                if (!route.contains(i))
123                        return false;
124        }
125        return false;
126}
127
128/*!
129 * \brief Solves the given task.
130 * \param numCities Number of cities in the task.
131 * \param task The matrix of city-to-city travel costs.
132 * \param parent The parent widget for displaying messages and dialogs.
133 * \return Pointer to the root of the solution tree.
134 *
135 * \todo TODO: Comment the algorithm.
136 */
137sStep *CTSPSolver::solve(int numCities, tMatrix task, QWidget *parent)
138{
139        if (numCities <= 1)
140                return NULL;
141        cleanup();
142        nCities = numCities;
143QProgressDialog pd(parent);
144QProgressBar *pb = new QProgressBar(&pd);
145        pb->setAlignment(Qt::AlignCenter);
146        pb->setFormat(trUtf8("%v of %m parts found"));
147        pd.setBar(pb);
148        pd.setMaximum(nCities);
149        pd.setMinimumDuration(1000);
150        pd.setLabelText(trUtf8("Calculating optimal route..."));
151        pd.setWindowTitle(trUtf8("Solution Progress"));
152        pd.setWindowModality(Qt::ApplicationModal);
153        pd.setValue(0);
154
155sStep *step = new sStep();
156        step->matrix = task;
157        step->price = align(step->matrix);
158        root = step;
159
160sStep *left, *right;
161int nRow, nCol;
162bool firstStep = true;
163double check;
164        while (this->route.size() < nCities) {
165//              forbidden.clear();
166                step->alts = findCandidate(step->matrix,nRow,nCol);
167                while (hasSubCycles(nRow,nCol)) {
168//                      forbidden[nRow] = nCol;
169                        step->matrix[nRow][nCol] = INFINITY;
170                        step->price += align(step->matrix);
171                        step->alts = findCandidate(step->matrix,nRow,nCol);
172                }
173                if ((nRow == -1) || (nCol == -1) || pd.wasCanceled()) {
174                        root = NULL;
175                        break;
176                }
177
178                // Route with (nRow,nCol) path
179                right = new sStep();
180                right->matrix = step->matrix;
181                for (int k = 0; k < nCities; k++) {
182                        if (k != nCol)
183                                right->matrix[nRow][k] = INFINITY;
184                        if (k != nRow)
185                                right->matrix[k][nCol] = INFINITY;
186                }
187                right->price = step->price + align(right->matrix);
188                // Forbid selected route to exclude its reuse in next steps.
189                right->matrix[nCol][nRow] = INFINITY;
190                right->matrix[nRow][nCol] = INFINITY;
191
192                // Route without (nRow,nCol) path
193                left = new sStep();
194                left->matrix = step->matrix;
195                left->matrix[nRow][nCol] = INFINITY;
196                left->price = step->price + align(left->matrix);
197
198                step->candidate.nRow = nRow;
199                step->candidate.nCol = nCol;
200                step->plNode = left;
201                step->prNode = right;
202
203                if (right->price <= left->price) {
204                        // Route with (nRow,nCol) path is cheaper
205                        step = right;
206                        this->route[nRow] = nCol;
207                        pd.setValue(this->route.size());
208                        if (firstStep) {
209                                check = left->price;
210                                firstStep = false;
211                        }
212                } else {
213                        // Route without (nRow,nCol) path is cheaper
214                        step = left;
215                        qApp->processEvents();
216                        if (firstStep) {
217                                check = right->price;
218                                firstStep = false;
219                        }
220                }
221        }
222
223        if (!root && !pd.wasCanceled()) {
224                pd.reset();
225                QMessageBox(QMessageBox::Warning,trUtf8("Solution Result"),trUtf8("Unable to find solution.\nMaybe, this task has no solutions."),QMessageBox::Ok,parent).exec();
226        }
227
228        qApp->processEvents();
229
230        if (root) {
231                route = this->route;
232                mayNotBeOptimal = (check < step->price);
233        }
234        return root;
235}
236
237/*!
238 * \brief Returns the sorted optimal path, starting from City 1.
239 * \return A string, containing sorted optimal path.
240 */
241QString CTSPSolver::getSortedPath() const
242{
243        if (!root || route.isEmpty() || (route.size() != nCities))
244                return QString();
245
246int i = 0; // We start from City 1
247QString path = trUtf8("City %1").arg(1) + " -> ";
248        while ((i = route[i]) != 0) {
249                path += trUtf8("City %1").arg(i + 1) + " -> ";
250        }
251        // And finish in City 1, too
252        path += trUtf8("City %1").arg(1);
253
254        return path;
255}
256
257/*!
258 * \brief Returns CTSPSolver's version ID.
259 * \return A string: <b>\$Id: tspsolver.cpp 66 2009-10-21 12:48:49Z laleppa $</b>.
260 */
261QString CTSPSolver::getVersionId()
262{
263        return QString("$Id: tspsolver.cpp 66 2009-10-21 12:48:49Z laleppa $");
264}
265
266/*!
267 * \brief Returns whether or not the solution is definitely optimal.
268 * \return \c true if solution is definitely optimal, otherwise \c false.
269 *
270 *  The solution may need some further interations to determine whether it is optimal.
271 *  In such cases this function returns \c false.
272 */
273bool CTSPSolver::isOptimal() const
274{
275        return !mayNotBeOptimal;
276}
Note: See TracBrowser for help on using the repository browser.