Mai intai trebuie sa te autentifici.
Cod sursa(job #2547123)
Utilizator | Data | 14 februarie 2020 23:12:20 | |
---|---|---|---|
Problema | Algoritmul lui Dijkstra | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.73 kb |
#include <bits/stdc++.h>
#define pii pair<int,int>
#define make_pii(a,b) make_pair(a,b)
#define INF -1
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n,p;
const int lmt =5e4+1 ;
int dist[lmt];
bool viz[lmt] = {0};
vector<pii> aList[lmt];
priority_queue<pii, vector<pii>, greater_equal<pii> > pq;
void citire()
{
fin>>n>>p;
int x,y,z;
while(fin>>x>>y>>z)
{
pii a = make_pii(y,z);
aList[x].push_back(a);
}
//first ii nodul, second ii costul
}
void dijkstra(int nod)
{
//first ii nodul curent si second ii distanta de la el la nod
pii strtNod = make_pii(nod,0);
dist[nod] = 0;
viz[strtNod.first] = 1;
pq.push(strtNod);
while(!pq.empty())
{
pii crnt = pq.top();
pq.pop();
viz[crnt.first]=1;
if(dist[crnt.first] >= crnt.second)
{
vector<pii>::iterator i;
for(i = aList[crnt.first].begin();i!=aList[crnt.first].end();++i)
{
pii nd = *i;
if(!viz[nd.first])
{
int newDistance = dist[crnt.first] + nd.second;
if(dist[nd.first] == INF || dist[nd.first]>=newDistance)
{
dist[nd.first] = newDistance;
pii toAdd = make_pii(nd.first,dist[nd.first]);
pq.push(toAdd);
}
}
}
}
}
}
int main()
{
citire();
for(int i=1;i<=n;++i)
dist[i]=INF;
dijkstra(p);
for(int i=1;i<=n;++i)
fout<<dist[i]<<' ';
fout<<endl;
return 0;
}