赤裸的最短路, (diy 1003)2066一个人的旅行用邻接表写的不知为何没过, 拿来改一下,交diy(1004)这题是AC的。 。 。 #include <iostream> #include <cstring> #include <string> #include <cstdio> #include <map> #include <queue> #include <algorithm> using namespace std; #define MAXN 10010 #define MAX 0x3fffffff bool hash[MAXN]; struct Edge {//边 int adj; int weight; Edge *next; }; Edge *maze[MAXN], vex[MAXN];//vex顶点 struct Dij { int id; int dis; bool friend operator < (const Dij a, const Dij b) { return a.dis > b.dis; } }; Dij now, next; void Init() { for (int i = 0; i < MAXN; i++) { maze[i] = &vex[i];//初始指向顶点 } } void Creat(int a, int b, int c) {//建邻接表 与a邻接是b Edge *pa = new Edge; pa->adj = b; pa->weight = c; pa->next = NULL; maze[a]->next = pa; maze[a] = maze[a]->next; } int Bfs(int st, int ed) { memset(hash, false, sizeof(hash)); priority_queue<Dij> Q; now.id = st; now.dis = 0; Q.push(now); while (!Q.empty()) { now = Q.top(); Q.pop(); if (hash[now.id]) { continue; } if (now.id == ed) { return now.dis; } hash[now.id] = true; Edge *first = vex[now.id].next; for (Edge *j = first; j != NULL; j = j->next) { if (hash[j->adj]) { continue; } next.id = j->adj; next.dis = now.dis + j->weight; Q.push(next); } } return -1; } int main() { int i, n, m, t, s, d, ss, dd, c; int st, ed; char aa[33], bb[33]; string a, b; while (scanf("%d %d", &n, &m) != EOF) { Init(); int k = 1; map<string, int> hash_str; for (i = 0; i < m; i++) { scanf("%s %s %d", aa, bb, &c); a = aa; b = bb; if (!hash_str[a]) { hash_str[a] = k++; } if (!hash_str[b]) { hash_str[b] = k++; } Creat(hash_str[a], hash_str[b], c); Creat(hash_str[b], hash_str[a], c); } scanf("%s %s", aa, bb); a = aa; b = bb; st = hash_str[aa]; ed = hash_str[bb]; int ans = Bfs(st, ed); printf("%d/n", ans); } return 0; }