Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. ifstream f("apm.in");
  9. ofstream g("apm.out");
  10.  
  11. vector<int> tata;
  12. vector<pair<pair<int,int>,int>> m,fn;
  13.  
  14. int Find (int x)
  15. {
  16.     if(tata[x]==x)
  17.         return x;
  18.     tata[x]=Find(tata[x]);
  19. }
  20.  
  21. void Union (int x, int y)
  22. {
  23.     int a=Find(x);
  24.     int b=Find(y);
  25.     tata[a]=b;
  26. }
  27.  
  28. bool cmp(pair<pair<int,int>,int> a, pair<pair<int,int>,int> b)
  29. {
  30.     return a.second<b.second;
  31. }
  32.  
  33. int n,mm;///n este numarul de noduri,iar mm este numarul de muchii
  34.  
  35. int main()
  36. {
  37.     int i,a,b,c,nr=0,cost=0;
  38.    
  39.     f>>n>>mm;
  40.     for(i=0; i<=n; i++)
  41.         tata.push_back(i);
  42.     for(i=1; i<=mm; i++)
  43.     {
  44.         f>>a>>b>>c;
  45.         m.push_back({{a,b},c});
  46.     }
  47.     f.close();
  48.     sort(m.begin(),m.end(),cmp);
  49.    
  50.     /*for (i=0; i<m.size(); i++)
  51.         cout<<m[i].first.first<<" "<<m[i].first.second<<" "<<m[i].second<<endl;*/
  52.    
  53.     i=0;
  54.     while(i!=m.size())
  55.     {
  56.         if(Find(m[i].first.first) != Find(m[i].first.second))
  57.         {
  58.             nr++;
  59.             fn.push_back(m[i]);
  60.             cost+=m[i].second;
  61.             Union(m[i].first.first,m[i].first.second);
  62.         }
  63.         i++;
  64.     }
  65.     g<<cost<<endl<<nr<<endl;
  66.     for(i=0; i<fn.size(); i++)
  67.     {
  68.         g<<fn[i].first.first<<" "<<fn[i].first.second<<endl;
  69.     }
  70.     g.close();
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement