直接利用 ASCII 码把字母转化为顶点跑最短路就可以了,
如果嫌我的方法浪费了部分空间 可以令 把所有的 ASCII 都-‘A’;
spfa
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define MAX_V 200
#define MAX_E (10000+10)
using namespace std;
int E, tot = 0;
int first[MAX_V], nxt[MAX_E << 1], dis[MAX_V];
bool used[MAX_V];
struct edge{
int from, to, cost;
}es[MAX_E << 1];
void build(int ff, int tt, int dd)
{
es[++tot] = (edge){ff,tt,dd};
nxt[tot] = first[ff];
first[ff] = tot;
}
queue <int> q;
void spfa(int s)
{
memset(dis,63,sizeof(dis));
dis[s] = 0;
q.push(s);
used[s] = 1;
while(q.size())
{
int x = q.front();
q.pop();
used[x] = 0;
for(int i = first[x]; i != -1; i = nxt[i])
{
int v = es[i].to;
if(dis[v] > dis[x] + es[i].cost)
{
dis[v] = dis[x] + es[i].cost;
if(!used[v])
{
q.push(v);
used[v] = 1;
}
}
}
}
}
int deal(char c)
{
return (int)(c);
}
char s[2];
int main()
{
cin >> E;
memset(first,-1,sizeof(first));
for(int i = 1; i <= E; i ++)
{
int f, t, d;
scanf("%s", s); f = deal(s[0]);
scanf("%s", s); t = deal(s[0]);
scanf("%d", &d);
build(f,t,d); build(t,f,d);
}
spfa(deal('Z'));
int minn = 1e9, ans;
for(int i = deal('A'); i < deal('Z'); i ++)
if(dis[i] < minn)
{
minn = dis[i];
ans = i;
}
cout << (char)ans << " " << minn << endl;
return 0;
}
dijkstra
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define MAX_V 200
#define MAX_E (10000+10)
using namespace std;
int E, tot = 0;
int first[MAX_V], nxt[MAX_E << 1], dis[MAX_V];
bool done[MAX_V];
struct edge{
int from, to, cost;
}es[MAX_E << 1];
void build(int ff, int tt, int dd)
{
es[++tot] = (edge){ff,tt,dd};
nxt[tot] = first[ff];
first[ff] = tot;
}
struct zt{
int v, d;
bool operator < (const zt b) const
{
return d > b.d;
}
};
priority_queue <zt> q;
void dijkstra(int s)
{
memset(dis,63,sizeof(dis));
dis[s] = 0;
q.push((zt){s,dis[s]});
while(q.size())
{
int x = q.top().v;
q.pop();
if(done[x]) continue;
done[x] = 1;
for(int i = first[x]; i != -1; i = nxt[i])
{
int v = es[i].to;
if(dis[v] > dis[x] + es[i].cost)
{
dis[v] = dis[x] + es[i].cost;
q.push((zt){v,dis[v]});
}
}
}
}
int deal(char c)
{
return (int)(c);
}
char s[2];
int main()
{
cin >> E;
memset(first,-1,sizeof(first));
for(int i = 1; i <= E; i ++)
{
int f, t, d;
scanf("%s", s); f = deal(s[0]);
scanf("%s", s); t = deal(s[0]);
scanf("%d", &d);
build(f,t,d); build(t,f,d);
}
dijkstra(deal('Z'));
int minn = 1e9, ans;
for(int i = deal('A'); i < deal('Z'); i ++)
if(dis[i] < minn)
{
minn = dis[i];
ans = i;
}
cout << (char)ans << " " << minn << endl;
return 0;
}