#include <iostream>
#include <queue>
#include <string>
#include <map>
#include <cstring>
using namespace std;
const int N=1000;
int id; //the number of vertex
const int INI=1000000;
int G[N][N];
class edge{
public:
int v1,v2,wi;
edge(int i,int j,int wi){
this->v1=i;
this->v2=j;
this->wi=wi;
}
}; //vital ! struct and class self-define should add ;
priority_queue<edge> que;
bool operator<(const edge &e1,const edge &e2)
{
return e1.wi>e2.wi;
}
int dijstra(int source,int target)
{
que=priority_queue<edge>();
for (int i=1;i<=id;i++)
{
if(source!=i)
que.push(edge(source,i,G[source][i]));
}
while(que.size())
{
int v1=que.top().v1;
int v2=que.top().v2;
int wei=que.top().wi;
for (int i=1;i<=id;i++)
{
if (wei+G[v2][i]<G[v1][i])
{
G[v1][i]=wei+G[v2][i];
que.push(edge(v1,i,G[v1][i]));
// que.push(edge(v1,v2));
}
}
if (v2==target)
{
break;
}
que.pop();
}
if( G[source][target]==INI) return -1;
else
return G[source][target];
}
int main()
{
int T,n,d,u,v;
string su,sv;
cin>>T;
while (T--)
{
map<string,int>m;
memset(G,0,sizeof(G));
cin>>n;
id=0;
for (int i = 0; i < n; i ++)
{
cin >> su >> sv >> d;
if(!m[su])
u = m [su] = ++ id;
else
u = m [su];
if(!m[sv])
v = m [sv] = ++ id;
else
v = m [sv];
if(u==v)
continue;
G[u][v]=d;
G[v][u]=d;
}
for (int i=1;i<=id;i++) //initiate Graph G set to INIfinite
{
for (int j=1;j<=id;j++)
{
if (G[i][j]==0) //G初始化皆为0 ?
{
G[i][j]=INI;
}
}
}
cin>>su>>sv;
u=m[su];
v=m[sv];
if (su==sv)
{
cout<<0<<endl;
continue;
}
if (!u || !v)
{
cout<<-1<<endl;
continue;
}
cout<<dijstra(u,v)<<endl;
}
return 0;
}
failed 矩阵版 dijkstra
最新推荐文章于 2024-11-01 14:34:15 发布
