Cod sursa(job #1243300)

Utilizator andreea_alexandraAndreea Alexandra andreea_alexandra Data 15 octombrie 2014 19:18:27
Problema Lazy Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.37 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#define MAX_M 200000
using namespace std;

struct muchie
{
    int nod1;
    int nod2;
    long long c1;
    long long c2;
    int poz;
};

FILE *in, *out;
int n, m, h[MAX_M], parent[MAX_M];
std::vector<muchie> v;


int rule(muchie a, muchie b)
{
    if(a.c1 == b.c1)
        return a.c1*a.c2 > b.c1*b.c2;
    return a.c1<b.c1;
}

int ancestor(int nod)
{
    while (parent[nod] != nod)
        nod=parent[nod];
    return nod;
}

void unite(int a, int b)
{
    if(h[a]>h[b])
        parent[b]=a;
    else
        parent[a]=b;
    if(h[a]==h[b])
        h[a]++;
}

int main()
{
    in = fopen("lazy.in", "r");
    out = fopen("lazy.out", "w");

    fscanf(in, "%d%d", &n, &m);
    for(int i=0; i<m; i++)
    {
        muchie aux;
        fscanf(in, "%d%d%lld%lld", &aux.nod1, &aux.nod2, &aux.c1, &aux.c2);
        aux.poz=i+1;
        v.push_back(aux);
        parent[i+1]=i+1;
        h[i+1]=1;
    }

    std::sort(v.begin(), v.end(), rule);

    int p, i;
    for(i=0, p=0; i<m && p<n-1; i++)
    {
        int x, y;
        x=ancestor(v[i].nod1);
        y=ancestor(v[i].nod2);
        if(x!=y)
        {
            fprintf(out, "%d\n", v[i].poz);
            unite(x, y);
            p++;
        }
    }


    fclose(in);
    fclose(out);
    return 0;
}