思路
单源最短路。从终点Dijkstra一遍就行。
代码
#include <cstdio>
#include <algorithm>
#include <functional>
#include <stack>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <map>
#include <cmath>
#define LL long long
#define lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
const int MAXN = 1000 + 5;
const int INF = 0x3f3f3f3f;
using namespace std;
typedef pair<int, int> pii;
typedef vector<int>::iterator viti;
typedef vector<pii>::iterator vitii;
vector<pii> mp[MAXN];
priority_queue<pii, vector<pii>, greater<pii> >pqu;
int d[MAXN];
void Dijkstra(int st)
{
memset(d, INF, sizeof d);
d[st] = 0;
pqu.push(MP(d[st], st));
while (!pqu.empty())
{
pii u = pqu.top(); pqu.pop();
int x = u.second, curDis = u.first;
if (u.first != d[x]) continue;
for (vitii it = mp[x].begin(); it != mp[x].end(); it++)
{
int t = it->first;
if (d[t] > curDis + it->second)
{
d[t] = curDis + it->second;
pqu.push(MP(d[t], t));
}
}
}
}
int main()
{
int n, i, j;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
char ch[10], cch[10];
int dis, a, b;
scanf("%s%s%d", ch, cch, dis);
if (isupper(ch[0])) a = ch[0]- 'A' + 26;
else a = ch[0] - 'a';
if (isupper(cch[0])) b = ch[0] - 'A' + 26;
else b = cch[0] - 'a';
mp[a].push_back(MP(b, dis)); mp[b].push_back(MP(a, dis));
int st = 'Z' - 'A';
Dijkstra(st);
int pos, ans = INF;
for (i = 0; i < 55; i++)
{
ans = min(ans, d[i]);
pos = i;
}
printf("%c %d\n", pos + 'A', ans);
}
return 0;
}