Cod sursă (job #625713)

Utilizator avatar rafaelrafy Chitan Rafael Alexandru rafaelrafy IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,42 kb
Rundă cex_gj11_12 Status evaluat
Dată 16 ian. 2022 16:03:47 Scor 70
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cctype>
using namespace std;
 
ifstream fin("zapada.in");
ofstream fout("zapada.out");
int t[10010],rang[10010];
int n, m, K, lung;
struct muchie{
    int x,y,c;
};
muchie v[110000];
bool cmp(muchie a, muchie b)
{
    return a.c < b.c;
}
int radacina(int x)
{
    if(t[x]==0)
        return x;
    int k = radacina(t[x]);
    t[x]=k;
    return k;
}
void uneste(int x,int y)
{
    int rx=radacina(x),ry=radacina(y);
    if(rang[rx] > rang[ry])
        t[ry]=rx;
    else if(rang[rx] < rang[ry])
        t[rx]=ry;
    else
    {
        rang[rx]++;
        t[ry]=rx;
    }
}
int Kruskal(int n)
{
    int poz=0;
    for(int i=1;i<=n;i++)
        t[i]=rang[i]=0;
    int cost=0,nr=0;
    sort(v+1,v+lung+1,cmp);
    for(int i=1;i<=lung;i++)
    {
        muchie it=v[i];
        if(radacina(it.x) != radacina(it.y))
        {
            v[++poz]=it;
            cost += it.c;
            uneste(it.x,it.y);
            nr++;
            if(nr == n-1)
                break;
        }
    }
    lung=n-1;
    return cost;
}
int main() {
    fin>>n>>m>>K;
    for(int i=1;i<=m;i++)
    {
        muchie x;
        fin>>x.x>>x.y>>x.c;
        v[++lung]=x;
    }
    fout<<Kruskal(n)<<'\n';
    for(int i=1;i<=K;i++)
    {
        muchie ct;
        fin>>ct.x>>ct.y>>ct.c;
        v[++lung]=ct;
        fout<<Kruskal(n)<<'\n';
    }
    return 0;
}