题目从别的帖子看来的,自己写了个算法,就记在自己的博客里,欢迎大家交流
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
void FindMin(string testStr, vector<vector<int>> distanceMatrix, int query, int &min)
{
<span style="white-space:pre"> </span>int last=0;
<span style="white-space:pre"> </span>int cur=0;
<span style="white-space:pre"> </span>int dis=0;
<span style="white-space:pre"> </span>int j=0;
<span style="white-space:pre"> </span>for (;j<testStr.size();j++)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>cur=(int)testStr[j]-48;;
<span style="white-space:pre"> </span>dis+=distanceMatrix[last][cur];
<span style="white-space:pre"> </span>if (cur==query)<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>break;
<span style="white-space:pre"> </span>last=cur;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if (dis<min)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>min=dis;
<span style="white-space:pre"> </span>}
}
void ReadInputFromConsole( int &totalNum, int &query, vector<vector<int>> &distanceMatrix )
{
<span style="white-space:pre"> </span>cin>>totalNum>>query;<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>for (int i=0;i<totalNum;i++)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>vector<int> oneLineInDistanceMatrix;
<span style="white-space:pre"> </span>int tempInput;
<span style="white-space:pre"> </span>for (int j=0;j<totalNum;j++)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>cin>>tempInput;
<span style="white-space:pre"> </span>oneLineInDistanceMatrix.push_back(tempInput);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>distanceMatrix.push_back(oneLineInDistanceMatrix);
<span style="white-space:pre"> </span>}
}
int _tmain(int argc, _TCHAR* argv[])
{
<span style="white-space:pre"> </span>int totalNum=0,query=0;
<span style="white-space:pre"> </span>vector<vector<int>> distanceMatrix;
<span style="white-space:pre"> </span>ReadInputFromConsole(totalNum, query, distanceMatrix);
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>stringstream aa;
<span style="white-space:pre"> </span>for (int i=1;i<totalNum;i++)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>aa<<i;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>string testStr=aa.str();
<span style="white-space:pre"> </span>int min=100000;
<span style="white-space:pre"> </span>do
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>FindMin(testStr, distanceMatrix, query, min);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>while (next_permutation(testStr.begin(),testStr.end()));
<span style="white-space:pre"> </span>cout<<min<<endl;
<span style="white-space:pre"> </span>return 0;
}