旅行商问题(贪婪法)

//.................h

/*
 * greedyTSP.H
 *
 *  Created on: 2011-7-12
 *      Author: 哈哈
 */

#ifndef GREEDYTSP_H_
#define GREEDYTSP_H_
#include <iostream>
using namespace std;
#include <vector>
#include <fstream>

void PrintState(vector <int> unVisted) {
 //cout << "in PrintState*********" << endl;
 for (size_t i = 0; i < unVisted.size(); i++)
  cout << unVisted[i] << " ";
 cout << endl;
}
void Initial(vector<int> &unVisited, int n) {
 for (int i = 1; i < n; i++)
  unVisited.push_back(i);
}

//template <class float>
float ** ReadData(int &size) {
 ifstream file("data");
 if (!file) {
  cout << "read error" << endl;
  return NULL;
 }
 file >> size;
 float **C = new float *[size];
 for (int i = 0; i < size; i++)
  C[i] = new float[size];

 for (int i = 0; i < size; i++)
  for (int j = 0; j < size; j++)
   file >> C[i][j];
 file.close();
 //cout << "Data read over" << endl;
 return C;
}

//template<class float>
float GreedyTSP(float **C, int n, int *steps) {

 float totalCost = 0;
 vector<int> unVisted;
 float weight;
 Initial(unVisted, n);
 for (int i = 1; i < n; i++) {
  int toMove = 0;
  //PrintState(unVisted);
  steps[i] = unVisted[0];
  for (size_t j = 0; j < unVisted.size(); j++)
   if (C[steps[i - 1]][steps[i]] > C[steps[i - 1]][unVisted[j]])
   {
    //cout << unVisted[j] << endl;
    steps[i] = unVisted[j];
    toMove = j;
    weight = C[steps[i - 1]][unVisted[j]];
   }
  unVisted.erase(unVisted.begin() + toMove);
  totalCost += weight;

 }

 for (int i = 0; i < n; i++)
  cout << steps[i] << " ";
 cout << endl << totalCost << endl;
 return totalCost;
}

#endif /* GREEDYTSP_H_ */

//...........................cpp

int main(int argc, char *argv[]) {
 int matrixSize;
 int *steps;
 float **C = ReadData(matrixSize);
 steps = new int[matrixSize];
 memset (steps, 0, sizeof (int ) * matrixSize);
 steps[0] = 0;
 GreedyTSP(C, matrixSize, steps);
 return 0;
}

你可能感兴趣的:(c,vector,File,null,Class,float)