Cod sursa(job #1839461)

Utilizator TimitocArdelean Andrei Timotei Timitoc Data 2 ianuarie 2017 22:19:38
Problema Salvare Scor 35
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.95 kb
#include <iostream>
#include <cstdio>
#include <vector>
#define MAXN 1050
#define MAXK 350
#define inf 0x3f3f3f3f

using namespace std;

int n, k, parent[MAXN];
vector<int> graf[MAXN];

void read()
{
    scanf("%d %d", &n, &k);
    for (int i = 1; i <= n-1; i++) {
        int x, y;
        scanf("%d %d", &x, &y);
        graf[x].push_back(y);
        graf[y].push_back(x);
    }
}

int brig, best[MAXN], cost[MAXN], used[MAXN];

void dfs(int nod)
{
    for (int y : graf[nod]) {
        if (parent[nod] != y) {
            parent[y] = nod;
            dfs(y);
        }
    }
    if (graf[nod].size() == 1 && parent[nod] == graf[nod][0]) {
        if (brig == 0) {
            used[nod] = 1;
            best[nod] = 1;
        }
    }
    else {
        int maxi = -1, mini = inf;
        for (int y : graf[nod])
            if (parent[y] == nod) {
                maxi = max(maxi, cost[y]+1);
                mini = min(mini, cost[y]+1);
                best[nod] += best[y];
            }
        if (maxi >= brig) {
            best[nod]++;
            used[nod] = 1;
        }
        else
            cost[nod] = maxi;
    }
}

int can(int prag)
{
    brig = prag;
    for (int i = 1; i <= n; i++)
        best[i] = cost[i] = used[i] = 0;
    dfs(1);
    return best[1] <= k;
}

void traseu()
{
    int cnt = 0;
    for (int i = 1; i <= n; i++)
        if (used[i])
            cnt++;
    if (cnt < k)
        used[1] = 1;
    for (int i = 1; i <= n; i++)
        if (used[i])
            printf("%d ", i);
}

void solve()
{
    int step, val = MAXN;
    for (step = 1; step < MAXN; step <<= 1);
    for (step; step; step >>= 1)
        if (val - step >= 0 && can(val-step))
            val -= step;
    can(val);
    printf("%d\n", val);
    traseu();
}

int main()
{
    freopen("salvare.in", "r", stdin);
    freopen("salvare.out", "w", stdout);

    read();
    solve();

    return 0;
}