查看题目:
声明:程序源码并非完美,提交后结果为“部分正确”。因博主看到这个题目网上的答案较少,所以将未完善的代码发出来供大家参考!
本程序采用深度优先搜索算法(DFS),由于递归的调用方式,占用内存过大导致程序提交错误。
#include "pch.h"#includeusing namespace std;const int MAXV = 50;const int INF = 99999;struct Graph { int Vex[MAXV]; int arcs[MAXV][MAXV]; int vexnum, arcsnum;}G;bool visited[MAXV];int path[MAXV];int length = 0;int min_length = INF;int num = 0;int team = 0;int maxteam = 0;void DFS(Graph G, int c1, int c2) { team += G.Vex[c1]; if (c1 == c2) { //走到终点了 //length += G.arcs[c1][c2]; if (length < min_length) { num = 1; min_length = length; maxteam = team; } else if (length == min_length) { num++; if (team > maxteam)maxteam = team; } return; } visited[c1] = true; for (int i = 0; i < G.vexnum; i++) { if (G.arcs[c1][i] != INF && visited[i] == false) { //访问v的邻接点 length += G.arcs[c1][i]; //team += G.Vex[i]; DFS(G,i,c2); length -= G.arcs[c1][i]; //team -= G.Vex[i]; } } team -= G.Vex[c1]; return;}int main() { for (int i = 0; i < MAXV; i++) { for (int j = 0; j < MAXV; j++) { G.arcs[i][j] = INF; } } int c1, c2; cin >> G.vexnum >> G.arcsnum >> c1 >> c2; for (int i = 0; i < G.vexnum; i++) { //城市救援队数量 cin >> G.Vex[i]; } int temp1, temp2, temp3; for (int i = 0; i < G.arcsnum; i++) { cin >> temp1 >> temp2 >> temp3; G.arcs[temp1][temp2] = temp3; } DFS(G, c1, c2); cout << num <<' '<< maxteam << endl;}