Cod sursa(job #2004329)

Utilizator Horia14Horia Banciu Horia14 Data 25 iulie 2017 16:57:37
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include<cstdio>
#include<vector>
#define MAX_N 200000
#define oo 0x3f3f3f3f
using namespace std;

vector<pair<int, int> > G[MAX_N+1], APM;
int dist[MAX_N+1], h[MAX_N+1], pos[MAX_N+1], p[MAX_N+1], n, m, minCost, k;
bool used[MAX_N+1];

inline void Swap(int i, int j)
{
    int aux = h[i];
    h[i] = h[j];
    h[j] = aux;
    aux = pos[h[i]];
    pos[h[i]] = pos[h[j]];
    pos[h[j]] = aux;
}

void heapDown(int i)
{
    int l, r;
    if(2*i > k) return;
    l = dist[h[2*i]];
    if(2*i+1 <= k)
        r = dist[h[2*i+1]];
    else r = l + 1;
    if(l < r)
    {
        if(dist[h[i]] <= l) return;
        Swap(i,2*i);
        heapDown(2*i);
    }
    else
    {
        if(dist[h[i]] <= r) return;
        Swap(i,2*i+1);
        heapDown(2*i+1);
    }
}

void heapUp(int i)
{
    if(dist[h[i/2]] <= dist[h[i]]) return;
    Swap(i,i/2);
    heapUp(i/2);
}

void Prim(int source)
{
    int i, Node;
    vector<pair<int, int>> :: iterator it;
    for(i=1; i<=n; i++)
    {
        dist[i] = oo;
        h[i] = i;
        pos[i] = i;
    }
    dist[source] = 0;
    dist[0] = -oo;
    k = n;
    for(i=1; i<=n; i++)
    {
        Node = h[1];
        minCost += dist[h[1]];
        Swap(1,k);
        k--;
        heapDown(1);
        used[Node] = true;
        if(Node != source)
            APM.push_back(make_pair(p[Node],Node));
        for(it = G[Node].begin(); it != G[Node].end(); it++)
        {
            if(!used[(*it).first] && dist[(*it).first] > (*it).second)
            {
                dist[(*it).first] = (*it).second;
                p[(*it).first] = Node;
                heapUp(pos[(*it).first]);
            }
        }
    }
}

int main()
{
    int i, x, y, cost;
    vector<pair<int,int>>::iterator it;
    FILE *fin, *fout;
    fin = fopen("apm.in","r");
    fout = fopen("apm.out","w");
    fscanf(fin,"%d%d",&n,&m);
    for(i=1; i<=m; i++)
    {
        fscanf(fin,"%d%d%d",&x,&y,&cost);
        G[x].push_back(make_pair(y,cost));
        G[y].push_back(make_pair(x,cost));
    }
    fclose(fin);
    Prim(1);
    fprintf(fout,"%d\n",minCost);
    fprintf(fout,"%d\n",APM.size());
    for(it = APM.begin(); it != APM.end(); it++)
        fprintf(fout,"%d %d\n",(*it).first,(*it).second);
    fclose(fout);
    return 0;
}