Cod sursa(job #1629295)

Utilizator clopotelNeamtu Sergiu clopotel Data 4 martie 2016 14:03:20
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <climits>
 
#define cost first
#define vt second
#define mp make_pair
#define inf 999999999
using namespace std;
 
vector < pair <int,int> > ::iterator it;
priority_queue < pair <int,int> > q;
vector < pair <int,int> > vect[50001];
pair <int,int> *u;
int n,m,k,ct,x,y;
int viz[50010],d[50001];
FILE *f=fopen("dijkstra.in","r");
FILE *g=fopen("dijkstra.out","w");
void citire()
{
 
    fscanf(f,"%d%d",&n,&m);
 
    for(int i=0;i<m;i++)
    {
        fscanf(f,"%d%d%d", &x,&y,&ct);
        vect[x].push_back(mp(-ct,y));
 
    }
    for (it = vect[1].begin(); it!=vect[1].end(); ++it)
    {
        q.push((*it));
    }
    for(int i=0;i<=n;++i)
        d[i]=-inf;
    while(!q.empty())
    {
        int w=q.top().vt;
        if(!viz[w])
            d[w]=q.top().cost;
        viz[w]=1;

        q.pop();
        for (it = vect[w].begin(); it!=vect[w].end(); ++it)
        {
 
            if(d[(*it).vt] < d[w]+(*it).cost)
                d[(*it).vt]=d[w]+(*it).cost,q.push(mp(d[(*it).vt],(*it).vt));
        }
    }
}
int main()
{
    citire();
    for(int i=2;i<=n;i++)
        if(d[i]!=-inf)
            fprintf(g,"%d ",-d[i]);
        else fprintf(g,"%d ",0);
   return 0;
}