Advertisement
nicuvlad76

Untitled

Nov 19th, 2022
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include<fstream>
  2. #include<algorithm>
  3. #include<vector>
  4. #include<cstring>
  5. #define N 10005
  6. using namespace std;
  7. ifstream fin ("zapada.in");
  8. ofstream fout ("zapada.out");
  9. int n,m,k,a,b,c;
  10. int cost;
  11. int t[N],viz[N],rang[N];
  12. struct T{int a,b,c;};
  13.  
  14. vector<T>mc,v;
  15. bool comp(T x, T y){return x.c<y.c;}
  16. int Rad(int x)
  17. {
  18.     while(x!=t[x])x=t[x];
  19.     return x;
  20. }
  21. void Uneste(int x, int y)
  22. {
  23.     if(rang[x]>rang[y])t[y]=x;
  24.     else{
  25.         t[x]=y;
  26.         if(rang[x]==rang[y])
  27.             rang[y]++;
  28.     }
  29. }
  30. int main()
  31. {
  32.   fin>>n>>m>>k;
  33.   for(int i=1;i<=m;i++)
  34.   {
  35.       fin>>a>>b>>c;
  36.       mc.push_back({a,b,c});
  37.   }
  38.   sort(mc.begin(), mc.end(),comp);
  39.   for(int i=1;i<=n;i++)t[i]=i;
  40.   for(int i=0;i<m;i++)
  41.   {
  42.       int rx=Rad(mc[i].a);
  43.       int ry=Rad(mc[i].b);
  44.       if(rx!=ry)
  45.       {
  46.           Uneste(rx, ry);
  47.           v.push_back(mc[i]);
  48.           cost+=mc[i].c;
  49.       }
  50.   }
  51.   fout<<cost<<"\n";
  52.   while(k--)
  53.   {
  54.     fin>>a>>b>>c;
  55.     if(v[v.size()-1].c>c)
  56.     {
  57.         v.push_back({a,b,c});
  58.         for(int i=v.size()-1;i>0;i--)
  59.             if(v[i].c<v[i-1].c)swap(v[i],v[i-1]);
  60.             else break;
  61.         mc=v;
  62.         v.clear();
  63.         cost=0;
  64.         for(int i=1;i<=n;i++){t[i]=i; rang[i]=0;}
  65.         for(int i=0;i<n;i++)
  66.         {
  67.             int rx=Rad(mc[i].a);
  68.             int ry=Rad(mc[i].b);
  69.             if(rx!=ry)
  70.             {
  71.                 Uneste(rx,ry);
  72.                 v.push_back(mc[i]);
  73.                 cost+=mc[i].c;
  74.             }
  75.         }
  76.         fout<<cost<<"\n";
  77.     }
  78.     else fout<<cost<<"\n";
  79.   }
  80.    return 0;
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement