Cod sursa(job #851356)

Utilizator UnforgivenMihai Catalin Botezatu Unforgiven Data 9 ianuarie 2013 21:37:14
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.67 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <string.h>
#define MAX_SIZE 50001


using namespace std;

vector <int> graf[MAX_SIZE];
vector <int> w[MAX_SIZE];
pair <int , int> tree[2 * MAX_SIZE];
bool sel[MAX_SIZE];
int cost[MAX_SIZE];
int N , M;
const int infinit = 1000000;


void build_tree(int nod , int left , int right)
{
    if (left == right)
    {
        tree[nod].first = infinit;
        tree[nod].second = left;
        return;
    }
    int middle = (left + right) >> 1;
    int left_son = nod << 1;
    int right_son = left_son + 1;
    build_tree(left_son , left , middle);
    build_tree(right_son, middle+1 , right);

}

void update_tree(int nod , int left , int right ,int A , int B , const int value)
{
    if (left == right)
    {
        tree[nod].first = value;
        tree[nod].second = A;
    }
    else
    {
        int middle  = (left + right) >> 1;
        int left_son = nod << 1;
        int right_son = left_son + 1;
        if (A <= middle)
        {
            update_tree(left_son , left , middle , A ,  B , value);
        }
        if ( middle < B)
        {
            update_tree(right_son , middle + 1 , right , A , B , value);
        }
        if ( tree[left_son].first > tree[right_son].first)
        {
            tree[nod] = tree[right_son];
        }
        else
        {
            tree[nod] = tree[left_son];
        }
    }
}

void dijkstra(int nod)
{
    cost[nod] = 0;
    update_tree(1,1,N,nod,nod,0);
    for (int k =0;k<N-1;k++)
    {
        nod = tree[1].second;
        sel[nod] = true;
        update_tree(1,1,N,nod,nod,infinit);

        for (int i =0;i<graf[nod].size();i++)
        {
            int x = graf[nod][i];

            if (cost[x] > w[nod][i] + cost[nod] && sel[x] == false)
            {
                cost[x] = w[nod][i] + cost[nod];
                update_tree(1,1,N,x,x,w[nod][i] + cost[nod]);
            }
        }
    }
}

void read_data()
{
    ifstream input("dijkstra.in");
    input >> N >> M;
    for (int i = 0;i<M;i++)
    {
        int x , y , c;
        input >> x >> y >> c;
        graf[x].push_back(y);
        graf[y].push_back(x);
        w[x].push_back(c);
        w[y].push_back(c);
    }
    input.close();
}

void print_data()
{
    ofstream output("dijkstra.out");
    for (int i = 2;i<=N;i++)
    {
        if (cost[i] != infinit)
        {
            output << cost[i] << " ";
        }
        else
        {
            output << 0 << " ";
        }
    }
    output.close();
}

void fill()
{
    for (int i= 1;i<=MAX_SIZE;i++)
    {
        cost[i] = infinit;
    }
}

int main()
{
    read_data();
    fill();
    build_tree(1,1,N);
    dijkstra(1);
    print_data();
    return 0;
}