Cod sursa(job #3198340)

Utilizator gabriel.9619Gabriel Stefan Tita gabriel.9619 Data 28 ianuarie 2024 22:28:32
Problema Floyd-Warshall/Roy-Floyd Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <algorithm>
#define NODE_DIM 1010
#define EDGE_DIM 1000010

using namespace std;

ifstream fin("oracol.in");
ofstream fout("oracol.out");

struct muchie{
    int x, y, c;
};

int n, x, edgeCnt;
int father[NODE_DIM];
muchie edges[EDGE_DIM];

int getRoot(int node)
{
    while(father[node]>0)
    {
        node = father[node];
    }
    return node;
}

void join(int root1, int root2)
{
    if(father[root1]<=father[root2])
    {
        father[root1]+=father[root2];
        father[root2]=root1;
    }
    else
    {
        father[root2]+=father[root1];
        father[root1]=root2;
    }
}

int main(){
    fin>>n;
    for(int i=1;i<=n;i++)
    {
        for(int j=i;j<=n;j++)
        {
            fin>>x;
            edges[++edgeCnt]={i, j+1, x};
        }
    }
    sort(edges+1, edges+edgeCnt+1, [](muchie a,muchie b) { return a.c<b.c;});
    for (int i=1;i<=n+1;i++)
    {
        father[i]=-1;
    }
    int minCost=0;
    for (int i=1;i<=edgeCnt;i++)
    {
        int root1=getRoot(edges[i].x);
        int root2=getRoot(edges[i].y);
        if(root1!=root2)
        {
            minCost+=edges[i].c;
            join(root1, root2);
        }
    }
    fout<<minCost;
    return 0;
}