情况分好即可 可以设置三个布尔变量分别代表是否为环,是否为简单环 两个节点之间是否有边;
#include <bits/stdc++.h>
using namespace std;
int graph[205][205];
int N,M,K,T;
int main(){
cin>>N>>M;
while (M--){
int a,b,c;
cin>>a>>b>>c;
graph[a][b]=graph[b][a]=c;
}
cin>>K;
int shortIndex=-1,shortDis=INT_MAX;
for(int k=1;k<=K;k++){
cin>>T;
int A[T],dis=0;
bool cycle=true,Na= false,simple= true;
unordered_map<int,int> m;
for (int i = 0; i < T; ++i) {
cin>>A[i];
if (i>0){
m[A[i]]++;
Na=graph[A[i-1]][A[i]]==0? true:Na;
dis+=graph[A[i-1]][A[i]];
}
}
cycle=!Na and A[T-1]==A[0] and m.size()==N?cycle:false;
for(auto &it:m) {
if (it.second > 1)
simple = false;
}
printf("Path %d: ",k);
if (Na)
printf("NA ");
else {
printf("%d ", dis);
}
printf("(%s)\n",cycle?(simple?"TS simple cycle":"TS cycle"):"Not a TS cycle");
if (cycle and shortDis>dis){
shortDis=dis;
shortIndex=k;
}
}
printf("Shortest Dist(%d) = %d",shortIndex,shortDis);
return 0;
}