1150 Travelling Salesman Problem

#include<iostream>

#include<set>

#include<vector>

using namespace std;

//定义全局变量

int n,m,k,e[300][300];

int ansid;//最短路径的查询编号

int ans=999999999;//最短路径初始化

void check(int index){

int sum=0;//路径总长度

int cnt;//当前路径包含的顶点数

int flag=1;//判断当前路径是否联通

cin>>cnt;

set<int>s;//用于记录路径中访问的不同顶点

vector<int>v(cnt);//存储路径中顶点的序列

//将顶点存入序列中

for(int i=0;i<cnt;i++){

cin>>v[i];

s.insert(v[i]);

}

//计算路径长度并存入集合

for(int i=0;i<cnt-1;i++){

//如果相邻节点之间没有边,则路径不连通

if(e[v[i]][v[i+1]]==0){

flag=0;

}

sum+=e[v[i]][v[i+1]];

}

//情况1:如果路径不连通

if(flag==0){

cout<<"Path "<<index<<": NA (Not a TS cycle)"<<endl;

}

//情况2:不是环或未访问所有顶点

else if(v[0]!=v[cnt-1]||s.size()!=n){

cout<<"Path "<<index<<": "<<sum<<" (Not a TS cycle)"<<endl;

}

//情况3:TS是环,但不是简单环

else if(cnt!=n+1){

cout << "Path " << index << ": " << sum << " (TS cycle)" << endl;

if(sum<ans){

ans=sum;

ansid=index;

}

}

//情况4:TS简单环

else{

cout << "Path " << index << ": " << sum << " (TS simple cycle)" << endl;

if(sum<ans){

ans=sum;

ansid=index;

}

}

}

int main(){

cin>>n>>m;

for(int i=0;i<m;i++){

int t1,t2,t;

cin>>t1>>t2>>t;

e[t1][t2]=e[t2][t1]=t;

}

cin>>k;

//逐条检查每条路径

for(int i=1;i<=k;i++){

check(i);

}

cout << "Shortest Dist(" << ansid << ") = " << ans << endl;

return 0;

}

相关推荐
爱编程的小吴1 天前
【力扣练习题】55. 跳跃游戏
算法·leetcode
春日见1 天前
控制算法:PID算法
linux·运维·服务器·人工智能·驱动开发·算法·机器人
Maỿbe1 天前
常见的垃圾收集算法
java·jvm·算法
郝学胜-神的一滴1 天前
Qt OpenGL 生成Mipmap技术详解
开发语言·c++·qt·系统架构·游戏引擎·图形渲染·unreal engine
珂朵莉MM1 天前
2025年睿抗机器人开发者大赛CAIP-编程技能赛-本科组(国赛)解题报告 | 珂学家
java·人工智能·算法·机器人·无人机
w-w0w-w1 天前
C++中vector的操作和简单实现
开发语言·数据结构·c++
Larry_Yanan1 天前
Qt安卓开发(一)Qt6.10环境配置
android·开发语言·c++·qt·学习·ui
l1t1 天前
郭其先生利用DeepSeek实现的PostgreSQL递归CTE实现DFS写法
sql·算法·postgresql·深度优先
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——力扣 227 题:基本计算机Ⅱ
c++·算法·leetcode·职场和发展·结构于算法
信奥卷王1 天前
2025年12月GESPC++二级真题解析(含视频)
算法