Source:
Description:
The "travelling salesman problem" asks the following question: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?" It is an NP-hard problem in combinatorial optimization, important in operations research and theoretical computer science. (Quoted from "".)
In this problem, you are supposed to find, from a given list of cycles, the one that is the closest to the solution of a travelling salesman problem.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive integers N (2), the number of cities, and M, the number of edges in an undirected graph. Then Mlines follow, each describes an edge in the format
City1 City2 Dist
, where the cities are numbered from 1 to N and the distanceDist
is positive and is no more than 100. The next line gives a positive integer K which is the number of paths, followed by K lines of paths, each in the format:n C1 C2 ... Cn
where n is the number of cities in the list, and Ci's are the cities on a path.
Output Specification:
For each path, print in a line
Path X: TotalDist (Description)
whereX
is the index (starting from 1) of that path,TotalDist
its total distance (if this distance does not exist, outputNA
instead), andDescription
is one of the following:
TS simple cycle
if it is a simple cycle that visits every city;TS cycle
if it is a cycle that visits every city, but not a simple cycle;Not a TS cycle
if it is NOT a cycle that visits every city.Finally print in a line
Shortest Dist(X) = TotalDist
whereX
is the index of the cycle that is the closest to the solution of a travelling salesman problem, andTotalDist
is its total distance. It is guaranteed that such a solution is unique.
Sample Input:
6 106 2 13 4 11 5 12 5 13 1 84 1 61 6 16 3 11 2 14 5 177 5 1 4 3 6 2 57 6 1 3 4 5 2 66 5 1 4 3 6 29 6 2 1 6 3 4 5 2 64 1 2 5 17 6 1 2 5 4 3 17 6 3 2 5 4 1 6
Sample Output:
Path 1: 11 (TS simple cycle)Path 2: 13 (TS simple cycle)Path 3: 10 (Not a TS cycle)Path 4: 8 (TS cycle)Path 5: 3 (Not a TS cycle)Path 6: 13 (Not a TS cycle)Path 7: NA (Not a TS cycle)Shortest Dist(4) = 8
Keys:
Attention:
- 注意检查是否遍历了所有结点
Code:
1 /* 2 Data: 2019-06-20 15:15:19 3 Problem: PAT_A1150#Travelling Salesman Problem 4 AC: 20:24 5 6 题目大意: 7 给出城市结点列表,及其路径,问遍历所有结点并返回初始结点的最短路径 8 现在给出一系列路径,找出能够遍历所有结点的最短回路 9 输入:10 第一行给出,结点数2<=200,边数M11 接下来M行, City1 City2 Distance, 1<=City<=N, 0 <=100;12 接下来一行,给出查询数K13 接下来K行,首先给出城市数目N,接着依次给出N个城市14 输出:15 Path 1~K: 总距离/NA(不可达)16 描述:17 简单回路,TS simple cycle18 非简单回路,TS cycle19 非回路,Not a TS cycle(未回到起点或未遍历所有结点)20 最后一行,输出所给回路中最短的一条21 */22 #include 23 #include 24 #include 25 using namespace std;26 const int M=1e3,INF=1e9;27 int grap[M][M],path[M];28 29 int main()30 {31 #ifdef ONLINE_JUDGE32 #else33 freopen("Test.txt", "r", stdin);34 #endif // ONLINE_JUDGE35 36 fill(grap[0],grap[0]+M*M,INF);37 int n,m,k,v1,v2;38 scanf("%d%d", &n,&m);39 for(int i=0; i