Cod sursa(job #1426344)

Utilizator alina.luparuFMI Luparu Alina alina.luparu Data 29 aprilie 2015 15:23:24
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include<iostream>
#include<fstream>
#include <stack>
#include<set>
#define p pair<int, int>
#define my_pair pair<p, int>
using namespace std;
void MakeSet(int x, int*h, int *l)
{
    h[x]=0;
    l[x]=0;
}
int FindSet(int x,int *l)
{
    if (l[x]==0)
    return x;
    l[x]=FindSet(l[x], l);
    return l[x];
}
void Union(int x, int y, int *h, int *l)
{
    x=FindSet(x, l);
    y=FindSet(y, l);
    if(h[x]>h[y])
        l[y]=x;
    else {
        l[x]=y;
        if(h[x]==h[y])
            h[y]++;
         }

}

class compare{
    public:
    bool operator()(const my_pair& a, const my_pair& b)
    {
        return a.second<=b.second;
    }
};

int main ()
{
    stack<p> A;
    set <my_pair, compare> M;
    set<my_pair>:: iterator it;
    int v, *h, *l, x, y,z;
    ifstream f("kruskal.in");
    f>>v;
    h=new int[v];
    l=new int[v];
    while(f>>x>>y>>z)
        M.insert(make_pair(make_pair(x, y), z));



    for(int i=0;i<v;i++)
        MakeSet(i,h, l);
        int S=0;
    for(it=M.begin();it!=M.end();it++)
        if(FindSet(it->first.first, l)!= FindSet(it->first.second, l) )
        {
           A.push(make_pair(it->first.first, it->first.second));
           S+=it->second;
           Union(it->first.first, it->first.second, h, l);
           if(A.size()==v-1)
           break;
        }
    while(!A.empty())
    {
        cout<<A.top().first+1<<"-"<<A.top().second+1<<endl;
        A.pop();
    }
    cout<<"costul="<<S;
}