Cod sursa(job #380031)

Utilizator cristiprgPrigoana Cristian cristiprg Data 4 ianuarie 2010 17:35:21
Problema Arbore partial de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 kb
/*
#include <cstdio>
#include <algorithm>
using namespace std;

struct muchie
{
    int i, j, cost;
    friend bool operator < (const muchie &a, const muchie &b)
    {
        return a.cost < b.cost;
    }
};

muchie v[400005];
int n, m, t[200005], a[200005], h[200005];

int radacina(int x)
{
    int y = x, tmp;
    while (t[x])
        x = t[x];

    while (t[y])    //smecherie tare
        tmp = t[y], t[y] = x, y = tmp;

    return x;
}

int main()
{
    FILE *f = fopen("apm.in", "r");
    fscanf(f, "%d%d", &n, &m);
    for (int i = 1; i <= m; ++i)
        fscanf(f, "%d%d%d", &v[i].i, &v[i].j, &v[i].cost);
    fclose(f);

    sort(v+1, v+m+1);

    int na = 0, cost = 0;
    for (int i = 1; i <= m; ++i)
    {
        int ri = radacina(v[i].i), rj = radacina(v[i].j);
        if (ri != rj)
        {
            if (h[ri] < h[rj])
                t[ri] = rj;
            else
                if (h[ri] > h[rj])
                    t[rj] = ri;
                else
                    t[ri] = rj, h[rj]++;

            a[++na] = i, cost += v[i].cost;
        }
    }

    f = fopen("apm.out", "w");
    fprintf (f, "%d\n%d\n", cost, n-1);
    for (int i = 1; i <= n - 1; ++i)
        fprintf(f, "%d %d\n", v[ a[i] ].i, v[ a[i] ].j);

    fclose(f);

    return 0;
}
*/

#include <cstdio>

struct nod
{
    int vf, cost;
    nod *next;
};

nod *graf[200002];

int n, m, t[200002];

void addMuchie (int i, int j, int c)
{
    nod *p = new nod;
    p -> vf = j;
    p -> cost = c;
    p -> next = graf[i];
    graf[i] = p;
}

int main()
{
    FILE *f = fopen("apm.in", "r");
    fscanf(f, "%d%d", &n, &m);

    int  x, y, c;
    for (int i = 1; i <= m; ++i)
    {
        fscanf(f, "%d%d%d", &x, &y, &c);
        addMuchie (x, y, c);
        addMuchie (y, x, c);

    }

    fclose(f);
    for (int i = 1; i <= n; ++i)
        t[i] = -1;

    t[1] = 0;
    int cost = 0;
    for (int k = 1; k < n; ++k)
    {
        int cmin = 1 << 30, imin, jmin ;
        for (int i = 1; i <= n; ++i)
            if (t[i] >= 0)
                for (nod *p = graf[i]; p ; p = p -> next)
                    if (t[ p->vf ] == -1)
                        if (p -> cost < cmin)
                            cmin = p -> cost, imin = i, jmin = p->vf;

        if (cmin < (1 << 30))
            t[jmin] = imin, cost += cmin;
    }

    f = fopen ("apm.out", "w");
    fprintf (f, "%d\n%d\n", cost, n - 1);
    for (int i = 1; i <= n; ++i)
        if (t[i] != 0)
            fprintf (f, "%d %d\n", i, t[i]);

    return 0;
}