Cod sursa(job #777395)

Utilizator badmanDragan Dan badman Data 12 august 2012 11:11:01
Problema Radiatie Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.16 kb
#include <stdio.h>
#include <algorithm>
#define maxn 15001

using namespace std;

int lastWalk[maxn], costToParent[maxn], rank[maxn], parent[maxn];

class DisjointSets {

public:
    DisjointSets() {
      
    }

    void Union(int v1, int v2, int cost) {
	     if (rank[v1] > rank[v2]) {
		    parent[v2] = v1;
		    costToParent[v2] = cost;
	     }
	     else {
		      parent[v1] = v2;
		      costToParent[v1] = cost;
		      if (rank[v1] == rank[v2])
			     rank[v2]++;
         }
    }


    int Find(int vertex) {
	    if (parent[vertex] != 0)
		   return Find(parent[vertex]);
        return vertex;
     }
    
    int query(int a, int b, int color) {
	    int max = 0, first = a;
	
	    while (parent[a] != 0) {
		      lastWalk[a] = color;
		      a = parent[a];
        }
	
	    while (parent[b] != 0 && lastWalk[b] != color) {
		      if (max < costToParent[b])
			     max = costToParent[b];
		      b = parent[b];
        }
			
	    while (first != b) {
		      if (max < costToParent[first])
			     max = costToParent[first];
		      first = parent[first];
         }
	
	     return max;
    }

    ~DisjointSets() {
    }
};


struct edge {
    int a, b;
    int c;
};

struct cmp
{
     bool operator()(const edge &a, const edge &b)const
    {
          if(a.c <  b.c) return 1;
          return 0;
    }
};

int main() {

    int N, i, M, K;
    edge m[maxn << 1];
    FILE *input, *output;
    input = fopen("radiatie.in", "r");
    output = fopen("radiatie.out", "w");
    fscanf(input, "%d %d %d", &N, &M, &K) ;
    for (i = 1; i <= M; ++i)
            fscanf(input, "%d %d %d", &m[i].a, &m[i].b, &m[i].c);
    
    DisjointSets *dj;
    dj = new DisjointSets();
   
    sort(m + 1, m + M + 1, cmp());
    for(i = 1; i <= M; ++i) {
        int s1, s2;
        if((s1 = dj->Find(m[i].a)) != (s2 = dj->Find(m[i].b))) {
            dj->Union(s1, s2, m[i].c);
        }
    }
    for (int i = 1 ; i <= K ; ++i) {
		int a, b;
		fscanf(input, "%d %d", &a, &b);
		fprintf(output, "%d\n", dj->query(a, b, i));
	}    
    delete dj;
    fclose(input);
    fclose(output);
return 0;
}