Cod sursa(job #895204)

Utilizator TeOOOVoina Teodora TeOOO Data 27 februarie 2013 10:31:18
Problema Radiatie Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.1 kb
#include <stdio.h>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;

#define cost first
#define from second.first
#define to second.second

const int sz = 15001;

int getRoot(int node);
void DFS(int node1, int node2, int length);

FILE *in,*out;
int nodes, edges, questions;
int father[sz];
bool visited[sz];
bool found = false;

vector<pair<int, int> > graph[sz];

priority_queue < pair <int, pair<int, int> >, vector <pair <int, pair<int, int> > >, greater <pair <int, pair<int, int> > > > heap;

int main()
{
    in=fopen("radiatie.in","rt");
    out=fopen("radiatie.out","wt");

    fscanf(in,"%d%d%d",&nodes, &edges, &questions);

    while(edges--)
    {
        int rFrom, rTo, rCost;
        fscanf(in,"%d%d%d",&rFrom, &rTo, &rCost);
        heap.push(make_pair(rCost, make_pair(rFrom, rTo)));
    }

    while(!heap.empty())
    {
        pair<int, pair<int, int> > current = heap.top();
        heap.pop();

        int node1 = current.from;
        int node2 = current.to;

        int root1 = getRoot(node1);
        int root2 = getRoot(node2);

        if(root1 == root2)
            continue;

        father[root1] = root2;
        graph[node1].push_back(make_pair(current.cost, node2));
        graph[node2].push_back(make_pair(current.cost, node1));
    }
    while(questions--)
    {
        int nodut1, nodut2;
        fscanf(in,"%d%d",&nodut1, &nodut2);
        memset(visited, false, sizeof(visited));
        found = false;
        DFS(nodut1, nodut2, 0);
    }

    fclose(in);
    fclose(out);
    return 0;
}

int getRoot(int node)
{   return father[node] ? father[node] = getRoot(father[node]) : node;}

void DFS(int node1, int node2, int length)
{
    visited[node1] = true;
    if(node1 == node2)
    {
        fprintf(out,"%d\n",length);
        found = true;
        return;
    }
    vector< pair<int, int> >::iterator it, end = graph[node1].end();
    for(it=graph[node1].begin(); it!=end && node2; ++it)
        if(!visited[it->second])
            DFS(it->second, node2, max(it->first, length));
}