sicily 1083 Network【最小生成树】

最小生成树的水题,直接上代码了。
View Code
   
     
// source code of submission 689439, Zhongshan University Online Judge System
#include < iostream >
#include
< vector >
#include
< algorithm >

using namespace std;
struct Edge
{
int u,v,length;
Edge(
int uu, int vv, int ll): u(uu),v(vv),length(ll) {}
};
vector
< Edge > vec;
int root[ 60 ];
int P,R;

bool cmp(Edge x,Edge y)
{
return (x.length < y.length);
}

void makeSet()
{
for ( int i = 0 ;i <= 60 ; ++ i) root[i] = - 1 ;
}

int findSet( int x)
{
while (root[x] >= 0 ) x = root[x];

return x;
}

void unionSet( int a, int b)
{
int x = findSet(a),y = findSet(b);

root[x]
= y;
}


int main()
{
int u,v,l,i;
while ( true )
{
cin
>> P;
if (P == 0 ) break ;
cin
>> R;

for (i = 0 ;i < R; ++ i)
{
cin
>> u >> v >> l;
vec.push_back(Edge(u,v,l));
}

sort(vec.begin(),vec.end(),cmp);
int ans = 0 ; makeSet();

for (i = 0 ;i < vec.size(); ++ i)
{
int x = findSet(vec[i].u),y = findSet(vec[i].v);

if (x != y)
{
ans
+= vec[i].length;
unionSet(x,y);
}
}
cout
<< ans << endl;
vec.clear();
}

return 0 ;
}

你可能感兴趣的:(NetWork)