Cod sursa(job #2171075)

Utilizator laptop_boyCatalin Stretcu laptop_boy Data 15 martie 2018 11:10:41
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

int n,m,s=0,nr=0,ok[100002],j;

struct muchii
{
    int m1,m2,c;
};

muchii w[400002];

vector<int> v[100002];

bool condsort(muchii x, muchii y)
{
    if(x.c<y.c)
        return 1;
    return 0;
}

bool kkk=0;

void conexitate(int x, int y, int c)
{
    if(ok[x]==0 && ok[y]==0)
    {
        ok[x]=x;
        ok[y]=x;
        v[x].push_back(x);
        v[x].push_back(y);
        s+=c;
        nr++;
        kkk=1;
    }
    else
    {
        if(ok[x]!=0 && ok[y]==0)
        {
            ok[y]=ok[x];
            v[ok[x]].push_back(y);
            s+=c;
            nr++;
            kkk=1;
        }
        else
        {
            if(ok[x]==0 && ok[y]!=0)
            {
                ok[x]=ok[y];
                s+=c;
                nr++;
                kkk=1;
                v[ok[y]].push_back(x);
            }
            else
            {
                if(ok[x]!=0 && ok[y]!=0 && ok[y]!=ok[x])
                {
                    s+=c;
                    nr++;
                    kkk=1;
                    int ky;
                    ky=ok[y];
                    for(int i=0;i<v[ky].size();i++)
                    {
                        v[ok[x]].push_back(v[ky][i]);
                        ok[v[ky][i]]=ok[x];
                    }
                }
            }
        }
    }
    if(kkk!=1)
        w[j].m1=-1;
}

int main()
{
    f>>n>>m;
    for(int i=1;i<=m;i++)
        f>>w[i].m1>>w[i].m2>>w[i].c;

    sort(w+1,w+m+1,condsort);

    for(j=1;j<=m;j++)
    {
        kkk=0;
        conexitate(w[j].m1,w[j].m2,w[j].c);
    }

    g<<s<<"\n"<<nr<<"\n";

    for(int i=1;i<=m;i++)
        if(w[i].m1!=-1)
            g<<w[i].m2<<" "<<w[i].m1<<"\n";

    f.close();
    g.close();
    return 0;
}