Cod sursa(job #2163200)

Utilizator MatteusTanase Matei Matteus Data 12 martie 2018 17:09:03
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream cin ("apm.in");
ofstream cout("apm.out");

const int INF = 999999999;
const int N = 500005;

vector <int> a[N];
vector <int> c[N];

int x, y, cost, n, m, h[N], poz[N], d[N], pred[N], p, q, nh;
bool viz[N];

void citire()
{
    int x,y,cost;
    cin>>n>>m;
    for(int i=0; i<=m; i++)
    {
        cin>>x>>y>>cost;
        a[x].push_back(y);
        a[y].push_back(x);
        c[x].push_back(cost);
        c[y].push_back(cost);
    }
}

void swapp(int p, int q)
{
    swap(h[p], h[q]);
    poz[h[p]]=p;
    poz[h[q]]=q;
}

void urca(int p)
{
    while(p>1 && d[h[p]]<d[h[p/2]])
    {
        swapp(p, p/2);
        p/=2;
    }
}

void coboara(int p)
{
    int fs=2*p, fd=2*p+1, bun=p;
    if(fs<=nh && d[h[fs]]<d[h[bun]])
    {
        bun=fs;
    }
    if(fd<=nh && d[h[fd]]<d[h[bun]])
    {
        bun=fd;
    }
    if(bun!=p)
    {
        swapp(p, bun);
        coboara(bun);
    }
}

void adauga(int p)
{
    h[++nh]=p;
    poz[p]=nh;
    urca(nh);
}

void sterge(int p)
{
    swapp(p, nh--);
    urca(p);
    coboara(p);
}

void dijkstra(int x0)
{
	nh=n;
	for(int i=1; i<=n; i++)
	{
		d[i]=INF;
		h[i]=i;
		poz[i]=i;
	}
	d[x0]=0;
	urca(poz[x0]);
	while(nh>0 && d[h[1]] != INF)
	{
		int x=h[1];
		sterge(1);
		viz[x]=true;
		for(int i=0; i<a[x].size(); i++)
		{
			int y=a[x][i];
			cost=c[x][i];
			if(viz[y])
                continue;
			if(cost<d[y])
			{
				d[y]=cost;
				pred[y]=x;
				urca(poz[y]);
			}
		}
	}
}


int main()
{
    int ct=0;
    citire();
    dijkstra(1);
    for(int i=2; i<=n; i++)
        ct+=d[i];
    cout<<ct<<'\n'<<n-1<<'\n';
    for(int i=2; i<=n; i++)
        /*if(d[i]==INF)
            cout<<0<<' ';
        else*/
            cout<<pred[i]<<' '<<i<<'\n';
    return 0;
}