If std::vector<vector<pair<int,int> > > v(n)
represents the adjacency list of the graph with pair<int,int>
is the {vertex,weight}
pair, I tried to implement the algorithm the following way:
while (true)
{
long long yo = LLONG_MAX;
int ind = -1;
for (int i = 0; i < n; ++i)
{
if (ans[i] < yo && !v[i].empty())
{
ind = i;
yo = ans[i];
}
}
if (ind == -1)
break;
for (int i = 0; i < v[ind].size(); ++i)
{
if (ans[v[ind][i].first] > ans[ind] + v[ind][i].second)
ans[v[ind][i].first] = ans[ind] + v[ind][i].second;
v[ind].erase(v[ind].begin() + i);
}
}
Where ans[i]
stores the shortest paths which is initialised as {LLONG_MAX,...0,...LLONG_MAX}
, 0
being the source. Since this is the first time I tried implementing it, is there a better way to implement using the vectors/list in stl (in terms of time/space complexity maybe)?