题目链接:PAT【甲级】1150
题目简述:输入一个N(节点数),M(边数),
然后接下来输入c1 c2 value
格式的M
组数据,value
就是该条边的值。而后呢去进行K
组查询,每一组给定一个将要遍历的总节点数u
,然后给出u
个遍历节点,输出其实哪一种环,如果是环的话输出他的路径值;否则输出不是环,路径值为NA
。最后再输出这K
组中,最短路径的环。
#include<bits/stdc++.h>
using namespace std;
int graph[201][201], vis[201];
int ans_id, ans_total = -1;
string ans_s, ans[3] = {"TS simple cycle", "TS cycle", "Not a TS cycle"};
vector<int> v;
int main(){
int N, M, K, u;
int c1, c2, r;
cin >> N >> M;
for (int i = 0; i < M;i++){
cin >> c1 >> c2 >> r;
graph[c1][c2] = graph[c2][c1] = r;
}
cin >> K;
for (int i = 1; i <= K; i++){//进行每组的判断
fill(vis, vis + 201, 0);//初始化
int total = 0;//记录这一组的路径值
cin >> u;
v.resize(u);
ans_s = ans[0];//默认为TS Simple Cycle
for (int j = 0; j < u;j++)
cin >> v[j];
for (int j = 1; j < u;j++){
if(graph[v[j - 1]][v[j]] != 0){//如果边存在
total += graph[v[j - 1]][v[j]];
vis[v[j]]++;
if(vis[v[j]] > 1)//如果该节点访问了多次,那可能是TS Cycle
ans_s = ans[1];
}
else{//边不存在,那自然路径不存在,也就是Not a Cycle,路径值自然也为0
ans_s = ans[2];
total = 0;
break;
}
}
for (int j = 1; j <= N;j++)//来判断是否遍历的每个节点
if(vis[j] == 0)
ans_s = ans[2];
if (v[0] != v[u - 1])//来判断是否回到最初的起点
ans_s = ans[2];
printf("Path %d: %s (%s)\n", i, total == 0 ? string("NA").c_str() : to_string(total).c_str(), ans_s.c_str());
if(ans_s != ans[2] && total != 0 && total < ans_total || ans_total == -1){//更新值
ans_total = total;
ans_id = i;
}
}
printf("Shortest Dist(%d) = %d", ans_id, ans_total);
return 0;
}
读清题意。题目中也给了很多的限制条件:边值为正数且小于100
,保证K
组查询中一定有最小路径的环,节点编号为1-N(<=200)
。这都是用到的点,可以简化代码编写。比如我这里定义的vis
数组,它的下标便是节点编号,以对应值来表示该节点访问了几次,不然的话还得用map
来转换下标。
逻辑应该是比较清楚的,就是去判断即可。我这边有个小技巧,那就是:去标记访问时只需标记后面节点,前面节点没必要,这样的话就避免记录开始节点同时防止在非简单环
判断中判断他。
下面的两个判断一定要有,来去判断是否回到起点,以及是否遍历了整个图节点。