Cod sursa(job #1560849)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 3 ianuarie 2016 13:31:37
Problema Lazy Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 200000;
const int MAX_M = 200000;

struct Edge
{
    int u, v;
    long long cost;
    long long profit;
};

Edge l[MAX_M];
int father[MAX_N];
int height[MAX_N];

int indx[MAX_N];

struct cmp
{
    inline bool operator () ( const int &A, const int &B )
    {
        return l[A].cost < l[B].cost || ( l[A].cost == l[B].cost && l[A].profit > l[B].profit );
    }
};

int getFather( int u )
{
    int r = u;

    while ( father[r] != r )
        r = father[r];

    while ( father[u] != u )
    {
        int v = father[u];
        father[u] = r;
        u = v;
    }
    return r;
}

void unionSet( int u, int v )
{
    if ( height[u] < height[v] )
        swap( u, v );

    father[v] = u;
    height[u] += ( height[u] == height[v] );
}

int main()
{
    ifstream in("lazy.in");
    ofstream out("lazy.out");
    in.tie(0);
    ios_base::sync_with_stdio(0);
    int N, M;

    in >> N >> M;
    for ( int i = 0; i < M; ++i )
    {
        in >> l[i].u >> l[i].v >> l[i].cost >> l[i].profit;
        l[i].u--; l[i].v--;

        indx[i] = i;
    }
    in.close();

    sort( indx, indx + M, cmp() );

    for ( int i = 0; i < N; ++i )
    {
        father[i] = i;
        height[i] = 1;
    }

    int numEdges = 0;
    int i = 0;
    while ( numEdges < N - 1 )
    {
        int u = getFather( l[ indx[i] ].u );
        int v = getFather( l[ indx[i] ].v );

        if ( u != v )
        {
            unionSet( u, v );
            numEdges++;
            out << 1 + indx[i] << '\n';
        }

        ++i;
    }
    out.close();
    return 0;
}