Cod sursa(job #1002653)

Utilizator crisbodnarCristian Bodnar crisbodnar Data 28 septembrie 2013 13:50:47
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>

#define ff first
#define ss second
#define newn a[x.ss][i]

using namespace std;

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

const int N = 10001;

long long rez;
short n, k, x, y, msterse;
typedef pair <short, short> nod;
vector <nod> h;
vector <short> a[N];
vector <short> cost(N, 1);

inline bool cmp(const nod a, const nod b)
{
    return a.ff > b.ff;
}

int main()
{
    fin>>n>>k;
    for(int i=1; i<n; i++)
    {
        fin>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
    {
        if(a[i].size() == 1)
            h.push_back(nod(1, i));
    }

    while(n - msterse - 1 > k)
    {
        sort(h.begin(), h.end(), cmp);
        nod x = h.back(); h.pop_back(); msterse++; cost[x.ss] = 0;
        for(unsigned i=0; i<a[x.ss].size(); i++)
        if(cost[newn])
        {
            cost[newn] += x.ff;
            short sters = 0;
            for(unsigned j=0; j<a[newn].size(); j++)
                if(!cost[a[newn][j]]) sters++;
            if(a[newn].size() - sters == 1) h.push_back(nod(cost[newn], newn));
            break;
        }
        rez += x.ff;
    }

    fout<<rez;
    return 0;
}