HDU 3371 connect the cities

Source: Internet
Author: User

And check the set + set container Kruskal

 # Include  <  Stdio. h  >  
# Include < String . H >
# Include < Set >
Using Namespace STD;
Const Int Maxn = 501 ;
Struct E
{
Int X, Y;
Int Weight;
};
E edge [ 25001 ];
Int Father [maxn];

Int CMP ( Const Void * D1, Const Void * D2 ){
Return ( * (E * ) D1). Weight - ( * (E * ) D2). weight;
}

Void Makeset ( Int N ){
For ( Int I = 0 ; I <= N; I ++ )
Father [I] = I;
}

Int Find ( Int X ){
If (X ! = Father [x])
Father [x] = Find (father [x]);
Return Father [x];
}

Void Merge ( Int X, Int Y ){
If (X > Y ){
Father [x] = Y;
} Else {
Father [y] = X;
}
}

Int Main (){
Set < Int > S;
Int CAS, n, m, K, cost;
Scanf ( " % D " , & CAS );
While (CAS -- ){
Scanf ( " % D " , & N, & M, & K );
S. Clear ();
Makeset (N );
Cost = 0 ;
For ( Int I = 1 ; I <= M; I ++ ){
Scanf ( " % D " , & Edge [I]. X, & Edge [I]. y, & Edge [I]. weight );
}
Int Num, first, city;
For ( Int I = 1 ; I <= K; I ++ ){
Scanf ( " % D " , & Num, & First );
For ( Int J = 1 ; J < Num; j ++ ){
Scanf ( " % D " , & City );
Int Xx = Find (first );
Int YY = Find (city );
If (Xx ! = YY)
Merge (XX, YY );
}
}
Qsort (edge + 1 , M, Sizeof (E), CMP );
For ( Int I = 1 ; I <= M; I ++ ){
Int Xx = Find (edge [I]. X );
Int YY = Find (edge [I]. y );
If (Xx ! = YY ){
Merge (XX, YY );
Cost + = Edge [I]. weight;
}
}
For ( Int I = 1 ; I <= N; I ++ ){
Find (I );
}
For ( Int I = 1 ; I <= N; I ++ ){
S. insert (father [I]);
}
If (S. Size () > 1 ){
Printf ( " -1 \ n " );
} Else {
Printf ( " % D \ n " , Cost );
}
}
Return 0 ;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.