Pagini recente » Cod sursa (job #1314697) | Cod sursa (job #2078479) | Cod sursa (job #1482940) | Cod sursa (job #921350) | Cod sursa (job #1426344)
#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;
}