Cod sursă (job #675975)

Utilizator avatar and_ AndreiTurcul and_ IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,57 kb
Rundă vaslui_cls1112_15.11 Status evaluat
Dată 15 nov. 2022 19:40:02 Scor 40
#include <bits/stdc++.h>
#define N 10007
using namespace std;


ifstream fin("zapada.in");
ofstream fout("zapada.out");

int n,m,k;
vector< pair<int,pair<int,int>> >muchii;
int father[N];
int grad[N];

int Find(int x)
{
    if( !father[x] )
        return x;
    else
    {
        int f=Find( father[x] );
        father[x]=f;
        return f;
    }
}

void Union(int x,int y)
{
    int tx=Find(x),ty=Find(y);
    if( tx!=ty )
    {
        if( grad[tx]==grad[ty] )
        {
            grad[tx]++;
            father[ty]=tx;
        }
        if( grad[tx]>grad[ty] )
        {
            father[ty]=tx;
        }
        if( grad[tx]<grad[ty] )
        {
            father[tx]=ty;
        }
    }
}




void Kruskal()
{
    sort(muchii.begin(),muchii.end());
    long long sol=0;
    for(int i=1;i<=n;i++)father[i]=0;
    for(int i=1;i<=n;i++)grad[i]=0;
    for(int i=0;i<m;i++)
    {
        int x= muchii[i].second.first;
        int y= muchii[i].second.second;
        int c= muchii[i].first;
        if( Find(x)!=Find(y) )
        {
cout << x << " " << y << "   "<< c << "\n";
            sol+=c;
            Union(x,y);
        }
    }
    fout << sol << '\n';
cout << "\n\n";
}

void Citire()
{
    fin >> n >> m >> k;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        fin >> x >> y >> c;
        muchii.push_back( { c,{x,y} } );
    }
    Kruskal();
    for(int i=1;i<=k;i++)
    {
        int x,y,c;
        fin >> x >> y >> c;
        muchii.push_back( { c,{x,y} } );
        ++m;
        Kruskal();
    }
    fin.close();
    fout.close();
}
int main()
{
    Citire();
    return 0;
}