使用 Dijkstra算法,首先建立有向圖,將每個單詞作爲一個結點,和能直接接在其後的單詞連線,然後計算起點到終點的最短距離即可。
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
struct Word //單詞
{
int time; //查找後續單詞所需時間
char first[5], last[5]; //前4個字符,後4個字符
}word[MAXN];
int N; //單詞數
char str[MAXN]; //每次輸入的單詞
int mp[MAXN][MAXN];
int dis[MAXN];
bool vis[MAXN];
//建圖
void buildMap()
{
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
if (strcmp(word[i].last, word[j].first) == 0)
mp[i][j] = word[i].time;
else
mp[i][j] = INF;
}
}
}
//Dijkstra算法,計算結點s到其他點的最短路徑
void Dijkstra(int s)
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= N; i++)
{
dis[i] = mp[s][i];
}
int k = s, minDis;
vis[k] = true;
for (int i = 1; i < N; i++)
{
minDis = INF;
for (int j = 1; j <= N; j++)
{
if (vis[j] == true)
continue;
if (minDis > dis[j])
{
minDis = dis[j];
k = j;
}
}
vis[k] = true;
for (int j = 1; j <= N; j++)
{
if (vis[j] == false && dis[j] > dis[k] + mp[k][j])
dis[j] = dis[k] + mp[k][j];
}
}
}
int main()
{
while (cin >> N)
{
if (N == 0)
break;
for (int i = 1; i <= N; i++)
{
cin >> word[i].time >> str;
int len = strlen(str);
for (int j = 0; j < 4; j++)
{
word[i].first[j] = str[j];
word[i].last[j] = str[len - 4 + j];
}
}
buildMap();
Dijkstra(1);
if (dis[N] != INF)
cout << dis[N] << endl;
else
cout << -1 << endl;
}
return 0;
}
繼續加油。