Pagini recente » Cod sursa (job #3266353) | Cod sursa (job #902510) | Cod sursa (job #611367) | Cod sursa (job #2416783) | Cod sursa (job #2634988)
#include <iostream>
#include <fstream>
#include <queue>
#include <list>
#include <vector>
using namespace std;
#define INFINITY INT_MAX
#define MAX_N 50001
int n,m;
list<pair<int,int>> *links;
void addLink(int origin,int destination, int weight)
{
links[origin].push_back(make_pair(weight,destination));
links[destination].push_back(make_pair(weight,origin));
}
int Dijkstra(int source, int destination)
{
priority_queue< pair<int,int>,
vector< pair<int,int> >,
greater< pair<int,int> >
> pq;
pq.push(make_pair(0, source));
vector<int> dist(n,INFINITY);
dist[source] = 0;
while(!pq.empty())
{
int u = pq.top().second;
pq.pop();
for(auto it = links[u].begin(); it != links[u].end(); it++)
{
int v = (*it).second;
int weight = (*it).first;
if( dist[v] > dist[u] + weight )
{
if( v == destination)
{
return dist[u] + weight;
}
else
{
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v],v));
}
}
}
}
return 0;
}
int main()
{
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
// read
f>>n;
links = new list< pair<int,int> >[n];
f>>m;
for(int i = 0; i < m; i++)
{
int o,d,w;
f>>o;
f>>d;
f>>w;
addLink(o-1,d-1,w);
}
for(int i = 1; i <= n; i++)
{
cout<<"[0 -> "<<i<<"] = "<<Dijkstra(0,i)<<endl;
}
}