我的PAT-ADVANCED代码仓:https://github.com/617076674/PAT-ADVANCED
原题链接:https://pintia.cn/problem-sets/994805342720868352/problems/1038430013544464384
题目描述:
题目翻译:
1150 旅行推销员问题
“旅行推销员问题”提出了以下问题:“给出城市列表和每对城市之间的距离,访问每个城市并返回原始城市的最短路线是什么?” 它是组合优化中的NP-hard问题,在运筹学和理论计算机科学中很重要。(引用自“https://en.wikipedia.org/wiki/Travelling_salesman_problem”。)
本题中,你需要从给定的周期列表中找到最接近“旅行推销员问题”解决方案的那个。
输入格式:
每个输入文件包含一个测试用例。对每个测试用例,第一行包含2个正整数N(2 < N <= 200),代表城市数量,M,代表无向图中的边数。然后紧跟着M行,每个以格式“City1 City2 Dist”描述一条边,其中城市为1 ~ N,距离Dist为正且不超过100。下一行给出正整数K,即路径数量,后面是K行路径,每个路径格式如下:
n C1 C2 ... Cn,其中n是列表中的城市数量,Ci是路径中的城市编号。
输出格式:
对每条路径,在一行中输出“Path X: TotalDist (Description)”,其中“X”是路径编号(编号从1开始计数),“TotalDist”是路径总距离,如果距离不存在,输出“NA”,“Description”选择以下选项中的一项:
“TS simple cycle”,如果是一个访问了每个节点的简单环。
“TS cycle”,如果该环访问了每个节点,但不是一个简单环。
“Not a TS cycle”,如果这不是一个访问了每个节点的环。
在最后一行输出“Shortest Dist(X) = TotalDist”,其中“X”是最接近“旅行推销员问题”解决方案的索引,而“TotalDist”是其总距离。题目保证这种解决方案是独一无二的。
输入样例:
6 10
6 2 1
3 4 1
1 5 1
2 5 1
3 1 8
4 1 6
1 6 1
6 3 1
1 2 1
4 5 1
7
7 5 1 4 3 6 2 5
7 6 1 3 4 5 2 6
6 5 1 4 3 6 2
9 6 2 1 6 3 4 5 2 6
4 1 2 5 1
7 6 1 2 5 4 3 1
7 6 3 2 5 4 1 6
输出样例:
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
知识点:图的表示、set集合的应用
思路:分辨清楚每种情况的条件
题目所给图最多200个节点,因此可以方便地用邻接矩阵来表示。
“TS simple cycle”:每个相邻节点间存在路径,节点个数为N + 1,不同的节点个数为N,其中首节点和末节点相同。
“TS cycle”:每个相邻节点间存在路径,节点个数为大于N + 1,不同的节点个数为N,其中首节点和末节点相同。
“Not a TS cycle”:不满足上述两种情况。
用set集合来自动滤除相同的节点编号,以此获得每个序列中不同的节点个数。
对于“TS simple cycle”或“TS cycle”,我们需要更新最小路径信息。
时间复杂度和空间复杂度与输入数据中的路径数量K以及每条路径中的节点数息息相关,不好分析。
C++代码:
#include<iostream>
#include<set>
using namespace std;
int INF = 1000000000;
int graph[201][201];
int main() {
for(int i = 0; i < 201; i++) {
for(int j = 0; j < 201; j++) {
graph[i][j] = INF;
}
}
int N, M;
scanf("%d %d", &N, &M);
int city1, city2, dist;
for(int i = 0; i < M; i++) {
scanf("%d %d %d", &city1, &city2, &dist);
graph[city1][city2] = graph[city2][city1] = dist;
}
int K;
scanf("%d", &K);
int minIndex, min = INF;
for(int i = 1; i <= K; i++) {
int n;
scanf("%d", &n);
int nums[n];
set<int> numSet;
for(int j = 0; j < n; j++) {
scanf("%d", &nums[j]);
numSet.insert(nums[j]);
}
int distance = 0;
bool flag = true;
for(int j = 0; j < n - 1; j++) {
if(graph[nums[j]][nums[j + 1]] == INF) {
flag = false;
break;
}
distance += graph[nums[j]][nums[j + 1]];
}
if(numSet.size() == N && nums[0] == nums[n - 1] && flag) {
if(n == N + 1) {
printf("Path %d: %d (TS simple cycle)\n", i, distance);
} else {
printf("Path %d: %d (TS cycle)\n", i, distance);
}
if(distance < min) {
min = distance;
minIndex = i;
}
} else {
if(flag) {
printf("Path %d: %d (Not a TS cycle)\n", i, distance);
} else {
printf("Path %d: NA (Not a TS cycle)\n", i);
}
}
}
printf("Shortest Dist(%d) = %d\n", minIndex, min);
return 0;
}
C++解题报告: