校园导航问题(限1 人完成)
设计要求:设计你的学校的平面图,至少包括10个以上的场所,每两个场所间可以有不同的路,且路长也可能不同,找出从任意场所到达另一场所的最佳路径(最短路径).
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <map> using namespace std; #define TITLE "路径查询系统" const int MENU_MAIN_COUNT = 4; const int MAXN = 1001; const int INF = 0x3f3f3f3f; bool vis[MAXN]; int pre[MAXN], lowcost[MAXN], ans[MAXN], cnt, q; int cost[MAXN][MAXN]; int n, m, w; string s, t, u, v; map<string, int>mp; map<int, string>mp2; void input_road(); void show_road(); void exit_system(); void Dijkstra(int n, int beg) { for (int i = 0; i < n; i++) { lowcost[i] = INF; vis[i] = false; pre[i] =-1; } lowcost[beg] = 0; for (int j = 0; j < n; j++) { int k = -1; int Min = INF; for (int i = 0; i < n; i++) { if (!vis[i] && lowcost[i] < Min) { Min = lowcost[i]; k = i; } } if (k == -1) break; vis[k] = true; for (int i = 0; i < n; i++) { if (!vis[i] && lowcost[k] + cost[k][i] < lowcost[i]) { lowcost[i] = lowcost[k] + cost[k][i]; pre[i] = k; } } } } void init() { memset(cost, 0x3f, sizeof(cost)); cnt = 1; q = 0; mp.clear(); mp2.clear(); } void add(string u) { if (!mp[u]) { mp[u] = cnt; mp2[cnt] = u; cnt++; } } void dfs(int u) { if (u == -1) return; ans[q++] = u; dfs(pre[u]); } void print_menu_title(char*title) { printf("=================================================\n"); printf("| %s\n",title); printf("-------------------------------------------------\n"); } char menu_main[]= "|\n" "| 1 输入路径\n" "| 2 查询路径\n" "| 3 退出\n" "|\n"; void (*menu_main_func[])()= { input_road, show_road, exit_system }; void print_menu_main() { int selected=0; system("cls"); print_menu_title(TITLE); printf(menu_main); printf("=================================================\n"); while(!(selected>=1&&selected<=MENU_MAIN_COUNT)) { printf(">请选择:"); scanf("%d",&selected); if(selected>=1&&selected<=MENU_MAIN_COUNT) { break; } printf("\n>输入错误!(请选择1 - %d)\n",MENU_MAIN_COUNT); } menu_main_func[selected-1](); } void input_road() { cout << "| 输入建筑数量 " << ‘ ‘ << " 输入路的数量 " << endl; cin >> n >> m; init(); cout << "| 输入起点 " << endl; cin >> s; add(s); cout << "| 输入终点 " << endl; cin >> t; add(t); cout << "| 输出" << m << "条边的两个端点和长度 " << endl; for (int i = 0; i < m; i++) { cin >> u >> v >> w; add(u); add(v); cost[mp[u]][mp[v]] = min(cost[mp[u]][mp[v]], w); cost[mp[v]][mp[u]] = cost[mp[u]][mp[v]]; } print_menu_main(); } void show_road() { Dijkstra(n+1, mp[s]); cout << "| 最短路径长度为:" << lowcost[mp[t]] << endl; dfs(mp[t]); cout << "| 路线为:" <<" "<< mp2[ans[q-1]]; for (int i = q-2; i >= 0; i--) cout << "->" << mp2[ans[i]]; cout << endl; getchar(); getchar(); cout << "按任意键退出" << endl; print_menu_main(); } void exit_system() { exit(0); } int main(){ print_menu_main(); return 0; }
时间: 2024-10-13 06:28:31