Cod sursa(job #777392)

Utilizator badmanDragan Dan badman Data 12 august 2012 11:05:22
Problema Radiatie Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.64 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

class DisjointSets {

private:
    int *parent, *size, N, lastWalk[15001], costToParent[15001];

public:
    DisjointSets(int n) {
      parent = new int[n + 1];
      size = new int[n + 1];
      for (int i = 1; i <= n; i++) {
        parent[i] = 0;
        size[i] = 1;
      }
      N = n;
    }

    void Union(int x, int y, int cost) {
      if (x <= 0 || x > N || y <= 0 || y > N)
        return;
      int rx = Find(x), ry = Find(y);
      if (rx != ry) {
        if (size[rx] > size[ry]) {
            parent[ry] = rx;
            costToParent[ry] = cost;
            size[rx] += size[ry];
        }
        else {
     	 	parent[rx] = ry;
     	 	costToParent[rx] = cost;
        	size[ry] += size[rx];
        }
     }

    }

    int Find(int x) {
        if (x <= 0 || x > N)
            return 0;
        int rx=x,next;
        while (parent[rx] > 0)
            rx = parent[rx];

        while(x != rx) {
            next = parent[x];
            parent[x] = rx;
            x = next;
        }

        return rx;
    }
    
    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, cost, M, K;
    edge m[50000];
    FILE *input, *output;
    input = fopen("radiatie.in", "r");
    output = fopen("radiatie.out", "w");
    fscanf(input, "%d %d %d", &N, &M, &K) ;
    for (i = 0; i < M; i++)
            fscanf(input, "%d %d %d", &m[i].a, &m[i].b, &m[i].c);
    
    DisjointSets *dj;
    dj = new DisjointSets(M);
   
    sort(m, m + M, cmp());
    for(i = 0; 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;
}