POJ 1251 Jungle Roads minimal spanning tree

Source: Internet
Author: User

POJ 1251 Jungle Roads minimal spanning tree

The question is to give your graph and then find the value of the minimum spanning tree. Note the input.

Idea: kruskal water stops using the bare minimum spanning tree. I did not write the minimum spanning tree for a long time. I thought about it carefully and wrote it out.

Code:

 

  1. # Include
  2. # Include
  3. # Include
  4. # Include
  5. # Include
  6. Using namespace std;
  7.  
  8. # Define CLR (arr, val) memset (arr, val, sizeof (arr ))
  9. Const int N = 32;
  10. Vector Vv [N];
  11. Int numedge, father [N];
  12. Struct edge {
  13. Int leftp, rightp, value;
  14. } Ee [1, 1000];
  15. Bool cmp (edge a, edge B ){
  16. Return a. value <B. value;
  17. }
  18. Int find (int x ){
  19. If (x = father [x])
  20. Return father [x];
  21. Return find (father [x]);
  22. }
  23. Bool union_set (int lp, int rp ){
  24. Int sequence = find (lp );
  25. Int frp = find (rp );
  26. If (records = frp ){
  27. Return false;
  28. }
  29. Else {
  30. Father [frp] = frp;
  31. Return true;
  32. }
  33. }
  34. Int kruskal (){
  35. Int sum = 0;
  36. For (int I = 0; I <numedge; ++ I ){
  37. Int lp = ee [I]. leftp;
  38. Int rp = ee [I]. rightp;
  39. If (union_set (lp, rp ))
  40. Sum + = ee [I]. value;
  41. }
  42. Return sum;
  43. }
  44. Int main (){
  45. // Freopen(1.txt, r, stdin );
  46. Int n;
  47. While (scanf (% d, & n ){
  48. Char ch;
  49. Int num, x;
  50. Numedge = 0;
  51. For (int I = 1; I <n; ++ I ){
  52. Cin> ch;
  53. Scanf (% d, & num );
  54. While (num --){
  55. Cin> ch;
  56. Scanf (% d, & x );
  57. Int y = (int) (ch-'A' + 1 );
  58. Ee [numedge]. leftp = I;
  59. Ee [numedge]. rightp = y;
  60. Ee [numedge]. value = x;
  61. Numedge ++;
  62. }
  63. }
  64. Sort (ee, ee + numedge, cmp );
  65. For (int I = 1; I <N; ++ I)
  66. Father [I] = I;
  67. Int ans = kruskal ();
  68. Printf (% d, ans );
  69. }
  70. Return 0;
  71. }

     

Related Article

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.